-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathBeyondSingleCore.Rpres
2222 lines (1637 loc) · 68.5 KB
/
BeyondSingleCore.Rpres
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
Beyond Single-Core R
========================================================
author: Jonathan Dursi
date: http://github.com/ljdursi/beyond-single-core-R
font-import: http://fonts.googleapis.com/css?family=Average
font-import: http://fonts.googleapis.com/css?family=Oswald
font-family: 'Average'
autosize: false
transition-speed: fast
css: assets/oicr.css
```{r setup, include="false"}
library(knitr)
set.seed(1)
opts_knit$set(root.dir='.')
trunc.gc <- function() { gc(TRUE)[,c(1:2,5:6)] }
```
Today's Outline
========================================================
Today will look something like this:
- How to think about scaling
- Parallel Package
- Multicore
- mcparallel/mccollect/mclapply
- parallel RNG
- load balancing, chunking
- pvec
- Snow
- makecluster/stopcluster/clusterExport
- clusterSplit
- Foreach
- chunking, iterators
- Scalable Data Analysis Best Practices
Extra material online
========================================================
- R and Memory
- Data file formats
- BigMemory
- Rdsm
- pbdR
Not Covered
========================================================
- R in other frameworks
- SparkR (R + Apache Spark)
- RHadoop
- Cool but more about the other framework than R
Thinking about scaling
============================================
type: sub-section
Some hardware terms
============================================
Hardware:
- Node: A single motherboard, with possibly multiple sockets
- Processor/Socket: the silicon containing likely multiple cores
- Core: the unit of computation; often has hardware support for
- Pseudo-cores: can appear to the OS as multiple cores but share much functionality between other pseudo-cores on the same core
***
![Sockets, Cores, and Hardware therads](images/sockets-cores.png)
Some software terms
============================================
Processes and threads:
- Process: Data and code in memory
- One or more **threads** of execution within a process
- Threads in the same process can see most of the same memory
- Processes generally cannot peer into another processes memory
Interpreted languages: generally you can only directly work with processes
Can call libraries that invoke threads (BLAS/LAPACK)
***
![Processes vs threads](images/process-threads.png)
Parallel computing: faster, bigger, more
============================================
One turns to parallel computing to solve one of three problems:
My program is too **slow**.
Perhaps using more cores --- *e.g.*, all cores on my desktop --- will make things **faster**.
- Compute bound.
- Tools:
- parallel/multicore
- Rdsm
- GPUs
***
![Rack of Computers](images/rack.png)
Parallel computing: faster, bigger, more
============================================
My problem is too **big**.
Perhaps splitting the problem up onto multiple computers in a cluster will give it access to enough memory to run effectively.
- Memory bound
- Tools:
- parallel/snow
- pbdR
***
![Rack of Computers](images/rack.png)
Parallel computing: faster, bigger, more
============================================
There are too **many** computations to do - one task runs in a reasonable amount of time, but I have to run thousands!
Perhaps splitting the problem up onto multiple computers in a cluster will give it access to enough memory to run.
- Tools:
- gnu-parallel
- parallel
- job queues...
***
![Rack of Computers](images/rack.png)
Concurrency: Multiple Independant Computations
========================================================
For more cores/nodes to help, there has to be something for them to do.
Find largely independent computations to occupy them.
Classic example of this is a parameter study, or set of simulations with
different seeds:
"More" case
***
![Parameter Study](images/paramstudy.png)
Scaling of parameter study: Througput
========================================================
In this example, no individual task runs any faster with more processors,
but the workload as a whole can.
How long it takes to process the N tasks you want done
Throughput: how many tasks/time
For completely independent tasks, P processors can increase throughput by factor P!
***
![Throughput](images/throughput-sm.png)
Scaling of parameter study with number of processors
========================================================
How a problem scales: how throughput behaves as processor number increases.
In this case, the throughput scales linearly with the number of processors.
This is the best case: "Perfect scaling"
***
```{r echo=FALSE}
time.per.task <- 2.
p <- 1:12
throughput <- p/time.per.task
plot(p, throughput, pch=16, xlab="Number of Processors", ylab="Throughput (tasks/time)")
```
Scaling of parameter study with number of processors
========================================================
Another way to look at it: time it takes to get some fixed amount of work done
More usual (and more important!)
Perfect scaling: time to completion ~ 1/P
P procesors - P times faster
***
```{r echo=FALSE}
time.per.task <- 2.
ntasks <- 12
total.time <- (time.per.task*ntasks)/p
plot(p, total.time, pch=16, xlab="Number of Processors", ylab="Total Time Required")
```
Scaling of parameter study with number of processors
========================================================
Another way to look at it: time it takes to get some fixed amount of work done
More usual (and more important!)
Perfect scaling: time to completion ~ 1/P
P procesors - P times faster
***
```{r echo=FALSE}
plot(p, total.time, log="xy", pch=16, xlab="Number of Processors", ylab="Total Time Required")
```
Scaling of parameter study with number of processors
========================================================
Finally, how efficient is the scaling - when you throw 10 processors at the problem,
are you getting 10 times the processing?
Perfect scaling - efficiency = 100%
***
```{r echo=FALSE}
ideal.time <- (time.per.task*ntasks)/p
efficiency <- ideal.time/total.time
plot(p, efficiency, pch=16, xlab="Number of Processors", ylab="Parallel Efficiency)")
```
Finding concurrency: Split, Apply, Combine
========================================================
Popularized by Hadley Wickham, this has
become a model for thinking about data analysis in R in the tidyverse.
Split the data set up into relevant sub-sets; apply some analysis to it; combine the
results.
This is exactly the way to think about scalable data analysis. Split the data -
or tasks on that data - up between computing elements; do the analyses; then combine
the results somehow.
The details depend a great deal on the analyses (and the nature of the data.)
***
![Split, Apply, Combine](images/split-apply-combine.png)
Imperfect parallelism
========================================================
"Split" and "Combine" aren't free!
Partitioning the work, and assembling the final results from the partial results,
represents some overhead - some fraction of the work that must be done in serial.
Splitting the work and distributing it over a network takes even more time.
Amdal's Law:
$$
T \approx \left ( f + \frac{1 - f}{P} \right )
$$
***
```{r echo=FALSE}
amdall.efficiency <- function(f,p) (1./p) / (f + (1.-f)/p)
serial.fracs <- seq(0.,.75,by=.15)
eff <- matrix(nrow=length(serial.fracs), ncol=length(p))
for (i in 1:length(serial.fracs)) {
eff[i,] <- sapply(p, function(np) amdall.efficiency(serial.fracs[i], np))
}
matplot(t(eff), type = c("b"), pch=16, xlab="Number of Processors", ylab="Efficiency", col=1:6)
legend("topright", legend = serial.fracs, pch=16, col=1:6, title="Serial Fraction")
```
Task vs data parallelism
========================================================
What we've described has been finding concurrency by analyzing
different chunks of data the same way
- seeds for simulation
- parameters for parameter sweep
- subsets of data
Also possible is to identify different tasks that must be done and perform those in parallel:
multiple fits, summary analysis + generating several plots, etc.
Generally more manual but can work very well.
Dependencies limit parallelism
***
![Diagram showing dependencies](images/gantt.png)
Existing parallelism (BLAS, package support)
========================================================
type: sub-section
Existing parallelism
========================================================
It's important to realize that many fundamental routines as well as higher-level packages come with some degree of scalability and parallelism "baked in".
Running `top` (or `glances`, or...) while executing the following in R:
```{r eval=FALSE}
n <- 4*1024
A <- matrix( rnorm(n*n), ncol=n, nrow=n )
B <- matrix( rnorm(n*n), ncol=n, nrow=n )
C <- A %*% B
```
Existing parallelism
========================================================
![Top while running matrix mult](images/BLAS-parallel-sm.png)
One R process using 458% of a processor.
R can be built using high performance threaded libraries for math in general, and linear algebra
--- which underlies *many* data analysis algorithms --- in particular.
Here the single R process has launched several threads of execution -- all of which are part of the same process, and so can see the same memory, eg the large matrices.
Packages that explicitly use parallelism
========================================================
For a complete list, see
http://cran.r-project.org/web/views/HighPerformanceComputing.html .
- Biopara
- BiocParallel for Bioconductor
- bigrf - Random Forests
- caret - cross-validation, bootstrap characterization of predictive models
- GAMBoost - boosting glms
Plus packages that use linear algebra or other expensive math operations which
can be implicitly multithreaded.
When at all possible, don't do the hard work yourself --- look to see if a package already
exists which will do your analysis at scale.
Caret
========================================================
Caret is a widely-used machine learning package, that uses `foreach` (which we'll learn about)
to parallelize things like CV-folds, etc:
```{r caret}
data(iris)
library(caret)
control <- trainControl(method="repeatedcv", number=10, repeats=3)
metric <- "Accuracy"
system.time(fit.lda.ser <- train(Species~., data=iris, method="svmRadial", metric=metric, trControl=control)
)
```
Caret
========================================================
```{r caretparallel}
library(doParallel)
registerDoParallel(4)
system.time(fit.lda.par <- train(Species~., data=iris, method="svmRadial", metric=metric, trControl=control)
)
stopImplicitCluster()
```
Packages for Implementing Parallel Workflows
========================================================
type: sub-section
The Parallel Package
========================================================
Since R 2.14.0 (late 2011), the `parallel` package has been part of core R.
Incorporates - and mostly supersedes - two other packages:
- `multicore`: for using all processors on a single processor. Not on windows.
- `snow`: for using any group of processors, possibly across a cluster.
Many packages which use parallelism use one of these two, so worth understanding.
Both create new *processes* (not threads) to run on different processors; but in importantly
different ways.
Multicore - forking
========================================================
Multicore creates new processes by forking --- cloning -- the original process.
That means the new processes starts off seeing a copy of exactly the same data as the original.
*E.g.*, first process can read a file, and then fork two new processes - each will see copy of the
file.
*Not* shared memory; changes in one process will not be reflected in others.
Windows doesn't have fork(), so windows can't use these routines.
***
![Multicore: fork()](images/fork-sm.png)
Multicore - forking
========================================================
**Performance Tip**: Modern OSs are lazy - the copy of memory isn't made unless it has to be, and
it doesn't have to be until one process or the other writes to the memory.
That copy is slow, and takes new memory.
So in `multicore`, don't overwrite old variables if possible.
***
![Multicore: fork()](images/fork-sm.png)
Snow - Spawning
========================================================
Snow creates entirely new R processes to run the jobs.
A downside is that you need to explicitly copy over any needed data, functions.
But the upsides are that spawning a new process can be done on a remote machine,
not just current machine. So you can in principle use entire clusters.
In addition, the flipside of the downside: new processes don't have any unneeded data
- less total memory footprint.
***
![SNOW: spawn()](images/spawn-sm.png)
mcparallel/mccollect
========================================================
The simplest use of the `multicore` package is the pair of functions `mcparallel()` and
`mccollect()`.
`mcparallel()` forks a task to run a given function; it then runs in the background.
`mccollect()` waits for and gets the result.
Let's pick an example: reading the airlines data set, we want --- for a particular month --- to
know both the total number of planes in the data (by tail number) and the median elapsed flight
time. These are two independant calculations, and so can be done independantly.
mcparallel/mccollect
========================================================
We start the two tasks with `mcparallel`, and collect the answers with `mccollect`:
```{r}
library(parallel, quiet=TRUE)
source("data/airline/read_airline.R")
jan2010 <- read.airline("data/airline/airOT201001.csv.gz")
unique.planes <- mcparallel( length( unique( sort(jan2010$TAIL_NUM) ) ) )
median.elapsed <- mcparallel( median( jan2010$ACTUAL_ELAPSED_TIME, na.rm=TRUE ) )
ans <- mccollect( list(unique.planes, median.elapsed) )
ans
```
We get a list of answers, with each element "named" by the process ID that ran the job. We find that there are 4555 planes in the data set, and the median flight in the data set is 110 minutes
in the air.
mcparallel/mccollect
========================================================
Does this save any time? Let's do some independent fits to the data. Let's try to see what
the average in-flight speed is by fitting time in the air to distance flown; and let's see how the
arrival delay correlates with the departure delay. (Do planes, on average, make up some time
in the air, or do delays compound?)
```{r}
system.time(fit1 <- lm(DISTANCE ~ AIR_TIME, data=jan2010))
system.time(fit2 <- lm(ARR_DELAY ~ DEP_DELAY, data=jan2010))
```
mcparallel/mccollect
========================================================
So the time to beat is about 0.7s:
```{r}
parfits <- function() {
pfit1 <- mcparallel(lm(DISTANCE ~ AIR_TIME, data=jan2010))
pfit2 <- mcparallel(lm(ARR_DELAY ~ DEP_DELAY, data=jan2010))
mccollect( list(pfit1, pfit2) )
}
system.time( parfits() )
```
Clearly actually forking the processes and waiting for them to rejoin itself takes some time.
This overhead means that we want to launch jobs that take a significant length of
time to run - much longer than the overhead (hundredths to tenths of seconds for fork().)
Clustering
========================================================
Typically we want to do more than an itemized list of independent tasks - we have a list
of similar tasks we want to perform.
`mclapply` is the multicore equivalent of `lapply` - apply a function to a list, get
a list back.
Let's say we want to see what similarities there are between delays at O'Hare airport
in Chicago in 2010. Clustering methods attempt to uncover "similar" rows in a dataset
by finding points that are near each other in some $p$-dimensional space, where $p$ is the
number of columns.
$k$-Means is a particularly simple, randomized, method; it picks $k$ cluster centre-points
at random, finds the rows closest to them, assigns them to the cluster, then moves the
cluster centres towards the centre of mass of their cluster, and repeats.
Quality of result depends on number of random trials.
Clustering
========================================================
Let's try that with our subset of data:
```{r}
# columns listing various delay measures
delaycols <- c(18, 28, 40, 41, 42, 43, 44)
air2010 <- readRDS("data/airline/airOT2010.RDS")
ord.delays <- air2010[(air2010$ORIGIN=="ORD"), delaycols]
rm(air2010)
ord.delays <- ord.delays[(ord.delays$ARR_DELAY_NEW > 0),]
ord.delays <- ord.delays[complete.cases(ord.delays),]
system.time( serial.res <- kmeans(ord.delays, centers=2, nstart=40) )
serial.res$withinss
```
Clustering with lapply
========================================================
Running 40 random trials is the same as running 10 random trials 4 times. Let's try that approach with `lapply`:
```{r}
do.n.kmeans <- function(n) { kmeans(ord.delays, centers=2, nstart=n) }
system.time( list.res <- lapply( rep(10,4), do.n.kmeans ) )
res <- sapply( list.res, function(x) x$tot.withinss )
lapply.res <- list.res[[which.min(res)]]
lapply.res$withinss
```
Get the same answer, but a little longer - bit of overhead from splitting it up and starting the
process four times. We could make the overhead less important by using more trials, which would be
better anyway.
Clustering with mclapply
========================================================
`mclapply` works the same way as lapply, but forking off the processes (as with
`mcparallel`)
```{r}
system.time( list.res <- mclapply( rep(10,4), do.n.kmeans, mc.cores=4 ) )
res <- sapply( list.res, function(x) x$tot.withinss )
mclapply.res <- list.res[[which.min(res)]]
mclapply.res$tot.withinss
```
Clustering with mclapply
========================================================
Note what the output of top looks like when this is running:
![top with mclapply](images/top-mclapply.png)
There are four separate processes running - not one process using multiple CPUs via threads.
Clustering with mclapply
========================================================
Looks good! Let's take a look at the list of results:
```{r}
res
```
What happened here?
Parallel RNG
========================================================
Depending on what you are doing, it may be very important to have different (or the same!)
random numbers generated in each process.
Here, we definitely want them different - the whole point is to generate different
random realizations.
`parallel` has a good RNG suitable for parallel work based on the work of Pierre L'Ecuyer
in Montréal:
```{r}
RNGkind("L'Ecuyer-CMRG")
mclapply( rep(1,4), rnorm, mc.cores=4, mc.set.seed=TRUE)
```
Load balancing
========================================================
Let's say that, instead of running multiple random trials to find the best given a set of clusters,
we were unsure of how many clusters we wanted to run:
```{r}
do.kmeans.nclusters <- function(n) { kmeans(ord.delays, centers=n, nstart=10) }
time.it <- function(n) { system.time( res <- do.kmeans.nclusters(n)) }
lapply(1:4, time.it)
```
Load balancing
========================================================
More clusters takes longer. If we were to `mclapply` these four tasks on 2 CPUs, the first
CPU would get the two short tasks, and the second CPU would get the second, longer tasks -
bad _load_ _balance_.
Normally, we want to hand multiple tasks of work off to each processor and only hear back when
they're completely done - minimal overhead. But that works best when all tasks have similar
lengths of time.
If you don't know that this is true, you can do _dynamic_ scheduling - give each processor one
task, and when they're done they can ask for another task.
More overhead, but better distribution of work.
Load balancing
========================================================
```{r}
system.time( res <- mclapply(1:4, time.it, mc.cores=2) )
system.time( res <- mclapply(1:4, time.it, mc.cores=2, mc.preschedule=FALSE) )
```
Splitting the data set
========================================================
So far we've seen splitting the tasks; let's consider splitting the dataset.
Let's make a histogram of the times flights took off - say, binned by the hour.
```{r}
get.hour <- function(timeInt) timeInt %/% 100
count.hours <- function(range) {
counts <- rep(0,24)
hours <- sapply(jan2010$DEP_TIME[range], get.hour)
hist <- rle( sort(hours) )
for (i in 1:length(hist$values)) {
j <- hist$values[i] + 1
if (j == 25) j = 1
counts[j] <- hist$lengths[i]
}
counts
}
```
Splitting the data set
========================================================
We can count up *all* flight hours like so:
```{r}
system.time(scounts <- count.hours(1:nrow(jan2010)))
scounts
```
Splitting the data set
========================================================
Can we split this up between tasks? Let's try this:
```{r}
nr <- nrow(jan2010)
ncores <- 4
chunks <- split(1:nr, rep(1:ncores, each=nr/ncores))
system.time(counts <- mclapply( chunks, count.hours, mc.cores=ncores) )
```
Splitting the data set
========================================================
That was definitely faster - how do the answers look?
```{r}
str(counts)
Reduce("+", counts)
```
To be fair, we'd have to include the Reduction time in the total time - but that's just the sum of
four short vectors, probably not a big deal.
pvec - simplified mclapply
========================================================
For the simple and common case of applying a function to each element of a vector and returning a
vector, the parallel package has a simplified version of mclapply called `pvec`.
```{r}
fx <- function(x) x^5-x^3+x^2-1
maxn <- 1e6
system.time( res <- sapply(1:maxn, fx) )
system.time( res <- vapply(1:maxn, fx, 0.) )
```
pvec - simplified mclapply
========================================================
```{r}
system.time( res <- pvec(1:maxn, fx, mc.cores=2) )
system.time( res <- pvec(1:maxn, fx, mc.cores=4) )
system.time( res <- mclapply(1:maxn, fx, mc.cores=4) )
```
Test your skills: parallel/multicore
========================================================
Using the entire 2010 dataset, and the examples above, examine one of the following questions:
- In 2010, what airport (with more than say 10 outgoing flights) had the largest fraction of
outgoing flights delayed?
- For some given airport - what hour of the day had the highest relative fraction of delayed flights?
- For all airports?
- What is the effect of including the `split()` and the `Reduce()` on the serial-vs-parallel timings for this histogram? Is there a better way of doing the splitting?
Summary: parallel/multicore
========================================================
The `mc*` routines in parallel work particularly well when:
- You want to make full use of the processors on a single computer
- Each task only reads from some big common data structure and produces modest-sized results
- `mcparallel` works very well for task parallelism; the `mclapply` for data parallelism.
Things to watch for:
- Modifying the big common data structure:
- Won't be seen by other processes,
- But will blow up the memory requirements
- You can only use one machine's processors
- Won't work on Windows (but what does?)
- `mc.cores` is a lie. It's the number of _tasks_, not _cores_. Can easily oversubscribe cores explicitly or implicitly
Multiple computers with parallel/snow
========================================================
type: sub-section
```{r include=FALSE}
# Get rid of the data up to this point
rm(list=ls())
```
Multiple computers with parallel/snow
========================================================
The other half of parallel, routines that were in the still-active `snow` package, allow you
to again launch new R processes --- by default, on the current computer, but also on any computer
you have access to. (SNOW stands for "Simple Network of Workstations", which was the original
use case).
The recipe for doing computations with snow looks something like:
```{r eval=FALSE}
library(parallel)
cl <- makeCluster(nworkers,...)
results1 <- clusterApply(cl, ...)
results2 <- clusterApply(cl, ...)
stopCluster(cl)
```
other than the `makeCluster()`/`stopCluster()`, it looks very much like multicore and `mclapply`.
Hello world
========================================================
Let's try starting up a "cluster" (eg, a set of workers) and generating some random numbers
from each:
```{r}
library(parallel)
cl <- makeCluster(4)
clusterCall(cl, rnorm, 5)
stopCluster(cl)
```
Hello world
========================================================
`clusterCall()` runs the same function (here, `rnorm`, with argument `5`) on all workers in
the cluster. A related helper function is `clusterEvalQ()` which is handier to use for some
setup tasks - eg,
```{r eval=FALSE}
clusterEvalQ(cl, {library(parallel); library(foreach); NULL} )
```
Clustering on Clusters
========================================================
Emboldened by our success so far, let's try re-doing our $k$-means calculations:
```{r}
delaycols <- c(18, 28, 40, 41, 42, 43, 44)
source("data/airline/read_airline.R")
jan2010 <- read.airline("data/airline/airOT201001.csv.gz")
jan2010 <- jan2010[,delaycols]
jan2010 <- jan2010[complete.cases(jan2010),]
do.n.kmeans <- function(n) { kmeans(jan2010, centers=4, nstart=n) }
```
```{r eval=FALSE}
library(parallel)
cl <- makeCluster(4)
res <- clusterApply(cl, rep(5,4), do.n.kmeans)
stopCluster(cl)
```
```{r eval=FALSE}
Error in checkForRemoteErrors(val) :
-----------------------------
4 nodes produced errors; first error: object 'jan2010' not found
-----------------------------
```
Ah! Failure.
Clustering on Clusters
========================================================
Recall that we aren't forking here; we are creating processes from scratch. These processes,
new to this world, are not familiar with our ways, customs, or datasets. We actually have to
ship the data out to the workers:
```{r}
cl <- makeCluster(4)
system.time(clusterExport(cl, "jan2010"))
system.time(cares <- clusterApply(cl, rep(5,4), do.n.kmeans))
stopCluster(cl)
system.time( mcres <- mclapply(rep(5,4), do.n.kmeans, mc.cores=4) )
```
Clustering on Clusters
========================================================
Note that the costs of shipping out data back and forth, and creating the processes from
scratch, is relatively costly - but this is the price we pay for being able to spawn the processes
anywhere.
(And if our computations take hours to run, we don't really care about several-second delays.)
Running across machines
========================================================
The default cluster is a sockets-based cluster; you can run on multiple machines by
specifying them to a different call to makeCluster:
```{r eval=FALSE}
hosts <- c( rep("localhost",8), rep("192.168.0.10", 8) )
cl <- makePSOCKcluster(names=hosts)
clusterCall(cl, rnorm, 5)
clusterCall(cl, system, "hostname")
stopCluster(cl)
```
Once it is done, you have succcessfully run random number
generators across multiple hosts.
Cluster types
========================================================
`parallel` has several different cluster types:
- PSOCK (Posix sockets): the default type
- Fork workers: but if you're going to use this, you may as well just use multicore.
- MPI: this is similar in a way to PSOCK clusters, but startup and communications can be much faster once you start going to large numbers (say >64) of hosts. We won't cover this today; using the MPI cluster type is conceptually identical to PSOCK clusters.
Work distribution and Load Balancing
========================================================
Because of the need to send (possibly large) data to the workers, the scheduling of
workers is even more important than with multicore.
The `snow` library has very nice visualization tools for timing that are inexplicably absent
from `parallel`; so let's temporarily use snow:
```{r}
library(snow,quiet=TRUE)
```
Work distribution and Load Balancing
========================================================
```{r}
do.kmeans.nclusters <- function(n) { kmeans(jan2010, centers=n, nstart=10) }
cl <- makeCluster(2)
clusterExport(cl,"jan2010")
tm <- snow.time( clusterApply(cl, 1:6, do.kmeans.nclusters) )
```
Work distribution and Load Balancing
========================================================
```{r}
plot(tm)
```
Work distribution and Load Balancing
========================================================
```{r}
tm.lb <- snow.time(clusterApplyLB(cl, 1:6, do.kmeans.nclusters))
plot(tm.lb)
stopCluster(cl)
```
Work distribution and Load Balancing
========================================================
The default `clusterApply` sends off one task to each worker, waits until they're both done, then
sends off another. (Question: why?)
`clusterApplyLB` does something more like `mc.preschedule=FALSE`; it fires off tasks to each worker
as needed.
Sending off one task at a time can be inefficient if there is a lot of commnication involved. But it allows
flexibility in scheduling, which is vitally important if the tasks are of widely varying durations.
clusterSplit and Hour Histogram
========================================================
Of course, for some applications, we don't need to send the entire data structure across. Let's consider
the departure-time histogram again. This time, we're only going to send across the data that's going t
be computed:
```{r}
jan2010 <- read.airline("data/airline/airOT201001.csv.gz")
jan2010 <- jan2010[complete.cases(jan2010),]
get.hour <- function(timeInt) timeInt %/% 100
count.hours <- function(timesInt) {
counts <- rep(0,24)
hours <- sapply(timesInt, get.hour)
hist <- rle( sort(hours) )
for (i in 1:length(hist$values)) {
j <- hist$values[i] + 1
if (j == 25) j = 1
counts[j] <- hist$lengths[i]
}
counts
}
```
clusterSplit and Hour Histogram
========================================================
This time, rather than exporting the entire data set, we'll just send across the bits we need:
```{r}
cl <- makeCluster(2)
clusterExport(cl,"get.hour") # have to export _functions_, too.
datapieces <- clusterSplit(cl,jan2010$DEP_TIME)
str(datapieces)
ans <- clusterApply(cl, datapieces, count.hours)
Reduce("+", ans)
```
clusterSplit and Hour Histogram
========================================================
To look a little more closely at some communciations and load balance issues, I'm going to
split the data up into more pieces than workers, and distribute them:
```{r}
stopCluster(cl)
cl <- makeCluster(6)
datapieces <- clusterSplit(cl,jan2010$DEP_TIME)
stopCluster(cl)
cl <- makeCluster(2)
clusterExport(cl,"get.hour") # have to export _functions_, too.
str(datapieces)
```
clusterSplit and Hour Histogram
========================================================
```{r}
tm <- snow.time( ans <- clusterApply(cl, datapieces, count.hours) )
plot(tm)
```
clusterSplit and Hour Histogram
========================================================
```{r}
tm <- snow.time( ans <- parLapply(cl, datapieces, count.hours) )
plot(tm)
stopCluster(cl)
```