Medindo os benefícios

Programação Paralela em R

Nabeel Imam

Data Scientist

Exemplo simples

numbers <- 1:1000000


# Sequencial sqroots <- lapply(numbers, sqrt)
# Paralelo cl <- makeCluster(4) sqroots <- parLapply(cl, numbers, sqrt) stopCluster(my_cluster)

Qual terá melhor desempenho?

Programação Paralela em R

Medição de desempenho

Execute o código várias vezes para estimar o tempo médio

library(microbenchmark)


microbenchmark( "Sequential" = lapply(numbers, sqrt),
"Parallel" = { cl <- makeCluster(4) parLapply(cl, numbers, sqrt) stopCluster(my_cluster) },
times = 10 )

 

 

Unit: milliseconds
      expr     min    mean     max neval
Sequential  633.96  838.09  993.59    10
  Parallel 1136.95 1247.29 1557.58    10
  • Operações numéricas simples raramente ganham com paralelização
  • Profiling traz relatório linha a linha; benchmarking mede tempos totais
Programação Paralela em R

O elefante na sala

sqroots <- sqrt(numbers)

Um elefante sentado no sofá de uma sala, com pessoas reconhecendo sua presença.

Programação Paralela em R

Vetorização

sqroots <- sqrt(numbers)
  • Funções base do R, como sqrt(), são vetorizadas.
  • Mapeiam uma função para muitas entradas
  • Muito rápidas, mas válidas só para operações simples
microbenchmark(
  "Vectorized" = sqrt(numbers),
  "Sequential" = lapply(numbers, sqrt),
  "Parallel" = {
    cl <- makeCluster(4)
    parLapply(cl, numbers, sqrt)
    stopCluster(my_cluster)
  },
  times = 10)
Unit: milliseconds
      expr       min      mean      max neval
Vectorized    2.3904    9.2071   66.303    10
Sequential  352.1166  771.7491 1004.753    10
  Parallel 1191.3176 1377.6926 1700.316    10
Programação Paralela em R

O bootstrap

Amostragem com reposição dos dados atuais

print(ls_df)
$`2001`
   Country             Life_expectancy  Year
 1 Afghanistan                    56.3  2001
 2 Albania                        74.3  2001
 3 Algeria                        71.1  2001
...
$`2002`
   Country             Life_expectancy  Year
 1 Afghanistan                    56.8  2002
 2 Albania                        74.6  2002
 3 Algeria                        71.6  2002
...
Programação Paralela em R

Versão clássica

df <- ls_df$`2001`


estimates <- rep(0, 10000)
for (i in 1:10000) { b <- sample(df$Life_expectancy, replace = T)
estimates[i] <- mean(b) }

Um histograma de estimativas bootstrap da expectativa de vida média global em 2001, mostrando a clássica curva em sino.

  • Intervalo de confiança via quantis: quantile(estimates, c(0.025, 0.975))
Programação Paralela em R

A boa notícia

Bootstraps podem ser paralelizados

estimates <- rep(0, 10000)

for (i in 1:10000) {

  b <- sample(df$Life_expectancy,
              replace = T)

  estimates[i] <- mean(b)
  }
boot_dist <- function (df) {

  estimates <- rep(0, 10000)

  for (i in 1:10000) {
    b <- sample(df$Life_expectancy, replace = T)
    estimates[i] <- mean(b)
  }

  return(estimates)
}


cl <- makeCluster(4) ls_dists <- parLapply(cl, ls_df, boot_dist) stopCluster(cl)
Programação Paralela em R

Os benefícios

microbenchmark(
  "lapply" = lapply(ls_df, boot_dist),
  "parLapply" = {
    cl <- makeCluster(4)
    parLapply(cl, ls_df, boot_dist)
    stopCluster(cl)
  },
  times = 10
)
Unit: seconds
     expr    min   mean    max neval
   lapply 3.6938 4.2184 4.5267    10
parLapply 1.9006 2.5166 2.7292    10

Como chegar lá:

  • Faça o profiling do código e ache o trecho mais lento
  • Paralelize/otimize essa etapa
  • Faça benchmarking e compare
Programação Paralela em R

Vamos praticar!

Programação Paralela em R

Preparing Video For Download...