...
 
Commits (2)
Package: optimParallel
Type: Package
Title: Parallel Versions of the Gradient-Based optim() Methods
Version: 0.7-4
Date: 2018-10-15
Title: Parallel Version of the L-BFGS-B Optimization Method
Version: 0.8
Date: 2019-02-25
Author: Florian Gerber
Maintainer: Florian Gerber <florian.gerber@math.uzh.ch>
Description: Provides parallel versions of the gradient-based optim() methods. The main function of the package is optimParallel(), which has the same usage and output as optim(). Using optimParallel() can significantly reduce the optimization time.
Description: Provides a parallel version of the L-BFGS-B method of optim(). The main function of the package is optimParallel(), which has the same usage and output as optim(). Using optimParallel() can significantly reduce the optimization time.
License: GPL (>= 2)
URL: https://git.math.uzh.ch/florian.gerber/optimParallel
BugReports: https://git.math.uzh.ch/florian.gerber/optimParallel/issues
Depends: R (>= 3.1), stats, parallel
Suggests: R.rsp, roxygen2, spam, microbenchmark, testthat, ggplot2, numDeriv
Depends: R (>= 3.5), stats, parallel
Suggests: R.rsp, roxygen2, spam, microbenchmark, testthat, ggplot2, numDeriv, lbfgsb3, lbfgsb3c
VignetteBuilder: R.rsp
RoxygenNote: 6.0.1
RoxygenNote: 6.1.1
# Generated by roxygen2: do not edit by hand
export(optimParallel)
importFrom(parallel,clusterEvalQ)
importFrom(parallel,clusterExport)
importFrom(parallel,getDefaultCluster)
importFrom(parallel,parLapply)
importFrom(stats,optim)
- version 0.8:
commit f0a8ed6e658cb481d549fd908d5640bf03abf394
Author: Florian Gerber <florian.gerber@math.uzh.ch>
Date: Mon Feb 25 18:38:17 2019 +0100
(1) the mechanism to call 'fn' and 'gr' in parallel
was improved to avoid unecessary copies of objects
between processes in the cluster.
(2) the 'BFGS' and 'GC' methods are nolonger supported.
- version 0.7-4: bug fix
commit 813a06269b6e777157fbe529bc62e38fc4d59de4
Author: Florian Gerber <florian.gerber@math.uzh.ch>
......
integrateArgs <- function(f, args) {
if(is.null(formals(f))) ## like sin()
args <- args[1]
else if (all(names(formals(f)) != "..."))
args <- args[names(args) %in% names(formals(f))]
do.call(function (f, ...){
# inspired from purrr::partial()
eval(call("function", NULL, substitute(f(...))),
envir=environment(f))
}, c(f=list(f), args))
##do.call(purrr::partial, c(list(f), args))
}
getFunctions <- function(f,
args, ## potential other arguments
firstArg, ## first argument
parnames){
if(is.vector(firstArg))
firstArg <- matrix(data=firstArg)
lapply(seq_len(ncol(firstArg)), function(x){
fa <- firstArg[,x]
names(fa) <- parnames
args <- args[names(args) != names(formals(args(f)))[1]]
allargs <- c(list(fa), args)
names(allargs)[1] <- names(formals(args(f)))[1]
integrateArgs(f=f, args=allargs)
})
}
#' @importFrom parallel parLapply
evalParallel <- function(cl, f, args, firstArg, parnames){
funlist <- getFunctions(f=f, args=args, firstArg=firstArg, parnames=parnames)
parallel::parLapply(cl=cl, X=funlist, fun=function(x) x())
}
This diff is collapsed.
.onLoad <- function(libname, pkgname)
.onAttach <- function(libname, pkgname)
{
options(optimParallel.forward=getOption("optimParallel.forward", FALSE))
options(optimParallel.loginfo=getOption("optimParallel.loginfo", FALSE))
......
The R package optimParallel
===========================
The package provides parallel versions of the gradient-based optim methods
"L-BFGS-B", "BFGS", and "CG". If the evaluation of the function fn takes more than 0.05 seconds,
optimParallel can significantly reduce the optimization time. For a p-parameter optimization based
on "L-BFGS-B", the speed increase is about factor 1+2p when no analytic gradient is specified and
The package provides a parallel versions of the L-BFGS-B optim method.
If the evaluation of the function fn takes more than 0.1 seconds,
optimParallel can significantly reduce the optimization time. For a p-parameter optimization,
the speed increase is about factor 1+2p when no analytic gradient is specified and
1+2p processor cores are available.
See the ArXiv e-prints URL http://arxiv.org/abs/1804.11058
......
......@@ -10,12 +10,10 @@
\alias{OptimParallel-Package}
\alias{optimparallel-package}
\alias{optimparallel-Package}
\alias{optimParallel-package}
\title{parallel version of \code{\link[stats]{optim}}}
\title{parallel version of the L-BFGS-B method of \code{\link[stats]{optim}}}
\usage{
optimParallel(par, fn, gr = NULL, ..., method = c("L-BFGS-B", "BFGS", "CG"),
lower = -Inf, upper = Inf, control = list(), hessian = FALSE,
parallel = list())
optimParallel(par, fn, gr = NULL, ..., lower = -Inf, upper = Inf,
control = list(), hessian = FALSE, parallel = list())
}
\arguments{
\item{par}{see the documentation of \code{\link[stats]{optim}}.}
......@@ -25,13 +23,7 @@ optimParallel(par, fn, gr = NULL, ..., method = c("L-BFGS-B", "BFGS", "CG"),
\item{gr}{see the documentation of \code{\link[stats]{optim}}.}
\item{...}{see the documentation of \code{\link[stats]{optim}}.
Note that depending on the chosen cluster type for parallel execution, the \code{.GlobalEnv} of the R processes in the cluster contain different R objects compared to the main R process.
In that case, it may be necessary to add all R object required by \code{fn} and \code{gr} here in order to pass them to the R processes in the cluster.}
\item{method}{parallel versions of the gradient-based methods \code{"L-BFGS-B"} (default), \code{"BFGS"}, and \code{"CG"} of \code{\link[stats]{optim}} are available.
The recommended method is \code{"L-BFGS-B"} because it triggers one (approximate) gradient evaluation per iteration, which best fits the implemented parallel processing scheme.
See the documentation of \code{\link[stats]{optim}} for information on the methods.
If another method is specified, all arguments are directly passed to \code{\link[stats]{optim}}.}
All R object required by \code{fn} and \code{gr} have to be added here.}
\item{lower}{see the documentation of \code{\link[stats]{optim}}.}
......@@ -48,23 +40,22 @@ See \code{\link[parallel]{makeCluster}} for more information.
If the argument is not specified or \code{NULL}, the default cluster is used.
See \code{\link[parallel]{setDefaultCluster}} for information on how to set up a default cluster.}
\item{\code{forward}}{ logical vector of length 1. If \code{FALSE} (default when loading the package), a numeric central difference approximation of the gradient defined as
\eqn{(fn(x+\epsilon)-fn(x-\epsilon))/(2\epsilon)} is used, which corresponds to the approximation used in \code{\link[stats]{optim}}.
\eqn{(fn(x+\epsilon)-fn(x-\epsilon))/(2\epsilon)} is used, which corresponds to the gradient approximation used in \code{\link[stats]{optim}}.
If \code{TRUE}, a numeric forward difference approximation of the gradient essentially defined as
\eqn{(fn(x+\epsilon)-fn(x))/\epsilon} is used. This reduces the number of function calls from \eqn{1+2p} to \eqn{1+p} and can be useful if the number of available cores is smaller than \eqn{1+2p} and if the memory limit is reached.}
\eqn{(fn(x+\epsilon)-fn(x))/\epsilon} is used. This reduces the number of function calls from \eqn{1+2p} to \eqn{1+p} and can be useful if the number of available cores is smaller than \eqn{1+2p} or if the memory limit is reached. Note that the numeric central difference approximation is more accurate than the numeric forward difference approximation.}
\item{\code{loginfo}}{ logical vector of length 1 with default value \code{FALSE} when loading the package. If \code{TRUE},
additional log information containing the evaluated parameters as well as return values of \code{fn} and \code{gr} is returned.}
}}
}
\value{
Same as the return value of \code{\link[stats]{optim}}. See the documentation thereof for more information.\cr
If a gradient-based method is specified and \code{parallel=list(loginfo=TRUE)}, additional log information containing the evaluated parameters as well as
If \code{parallel=list(loginfo=TRUE)}, additional log information containing the evaluated parameters as well as
the return values of \code{fn} and \code{gr} is returned.
}
\description{
The function provides parallel versions of the gradient-based \code{\link[stats]{optim}} methods
\code{"L-BFGS-B"}, \code{"BFGS"}, and \code{"CG"}.
If the evaluation of the function \code{fn} takes more than 0.05 seconds, \code{optimParallel} can significantly reduce the optimization time.
For a \eqn{p}-parameter optimization based on \code{"L-BFGS-B"}, the speed increase is about factor \eqn{1+2p} when no analytic gradient is specified and \eqn{1+2p} processor cores are available.
The function provides a parallel version of the L-BFGS-B method of \code{\link[stats]{optim}}.
If the evaluation time of the objective function \code{fn} is more than 0.1 sceconds, \code{optimParallel} can significantly reduce the optimization time.
For a \eqn{p}-parameter optimization the speed increase is about factor \eqn{1+2p} when no analytic gradient is specified and \eqn{1+2p} processor cores are available.
}
\details{
\code{optimParallel} is a wrapper to \code{\link[stats]{optim}} and relies on the lexical scoping mechanism of R
......@@ -72,29 +63,6 @@ and the R package \pkg{parallel} to evaluate \code{fn}
and its (approximate) gradient in parallel.\cr\cr
Some default values of the argument \code{parallel} can be set via\cr\code{options("optimParallel.forward", "optimParallel.loginfo")}.
}
\section{Notes}{
\describe{
\item{1.}{If \code{fn} or \code{gr} depend on functions or methods from loaded packages,
it may be necessary to explicitly load those packages in all processes of the cluster.
For \code{cl} of class \code{"cluster"} one can use \code{clusterEvalQ(cl, search())} to check
whether all required packages are on the search paths of all processes.
If, for example, the R package \pkg{spam} is required and missing on those search paths,
it can be added via \code{clusterEvalQ(cl, library("spam"))}.}
\item{2.}{If \code{fn} or \code{gr} depend on functions or objects defined in the current R session,
it may be necessary to pass them to \code{optimParallel} via the \code{...} argument.
Alternatively, they can be made available to the R processes in the cluster via \code{\link[parallel]{clusterEvalQ}}.}
\item{3.}{Using parallel R code inside \code{fn} and \code{gr} may not work, because this results in nested parallel processing.}
\item{4.}{Using \code{optimParellel} with \eqn{n} parallel processes increases the memory usage by about factor \eqn{n} compared to a call to \code{\link[stats]{optim}}.
If the memory limit is reached this may severely slowdown the optimization.
Strategies to reduce memory usage are
(1) kill all unused processes on the computer,
(2) revise the code of \code{fn} and/or \code{gr} to reduce its memory usage, and
(3) reduce the number of parallel processes by specifying the argument \code{parallel=list(forward=TRUE)} and/or
setting up a cluster with less parallel processes.}
}
}
\section{Issues and bug report}{
A list of known issues of \code{optimParallel} can be found at \url{https://git.math.uzh.ch/florian.gerber/optimParallel/issues}.
......@@ -114,12 +82,10 @@ set.seed(13); x <- rnorm(1000, 5, 2)
cl <- makeCluster(2) # set the number of processor cores
setDefaultCluster(cl=cl) # set 'cl' as default cluster
optimParallel(par=c(1,1), fn=negll, x=x,
method = "L-BFGS-B", lower=c(-Inf, .0001))
optimParallel(par=c(1,1), fn=negll, x=x, lower=c(-Inf, .0001))
optimParallel(par=c(1,1), fn=negll, x=x,
method = "L-BFGS-B", lower=c(-Inf, .0001),
parallel=list(loginfo=TRUE))
optimParallel(par=c(1,1), fn=negll, x=x, sleep=0, verbose=TRUE,
lower=c(-Inf, .0001), parallel=list(loginfo=TRUE))
setDefaultCluster(cl=NULL); stopCluster(cl)
......@@ -142,14 +108,12 @@ options(optimParallel.loginfo=TRUE)
## stop if change of f(x) is smaller than 0.01
control <- list(factr=.01/.Machine$double.eps)
optimParallel(par=c(1,1), fn=negll, x=x, sleep=.5,
verbose=TRUE, method="L-BFGS-B",
lower=c(-Inf, .0001), control=control)
optimParallel(par=c(1,1), fn=negll, x=x, sleep=.5, verbose=TRUE,
verbose=TRUE, lower=c(-Inf, .0001), control=control)
## each step invokes 5 parallel calls to negll()
optimParallel(par=c(1,1), fn=negll, x=x, sleep=.5,
method ="L-BFGS-B", lower=c(-Inf, .0001),
control=control,
optimParallel(par=c(1,1), fn=negll, x=x, sleep=.5, verbose=TRUE,
lower=c(-Inf, .0001), control=control,
parallel=list(forward=TRUE))
## each step invokes 3 parallel calls to negll()
......
## rm(list=ls())
## library("testthat")
## library("optimParallel", lib.loc = "../../../lib/")
context("test-evalParallel")
source("testsetup.R")
f1 <- function(x){
x
}
f2 <- function(x,y){
sum(10*x, y)
}
f3 <- function(x,y=1){
x+y
}
fnames <- function(x){
x["a"]+x["b"]+x["c"]
}
test_that("evalParallel: f1", {
expect_equal(optimParallel:::evalParallel(cl=cl, f=f1, args=NULL,
firstArg=c(1), parnames=NULL),
list(1))
expect_equal(optimParallel:::evalParallel(cl=cl, f=f1, args=NULL,
firstArg=c(1,2), parnames=NULL),
list(c(1,2)))
expect_equal(optimParallel:::evalParallel(cl=cl, f=f1, args=NULL,
firstArg=matrix(c(1,2), ncol=2), parnames=NULL),
list(1,2))
expect_equal(optimParallel:::evalParallel(cl=cl, f=f1, args=NULL,
firstArg=c(1,2,3,4,5), parnames=NULL),
list(c(1,2,3,4,5)))
expect_equal(optimParallel:::evalParallel(cl=cl, f=f1, args=list(a=1),
firstArg=c(1,2,3,4,5), parnames=NULL),
list(c(1,2,3,4,5)))
expect_equal(optimParallel:::evalParallel(cl=cl, f=f1, args=list(x=100),
firstArg=c(1,2,3,4,5), parnames=NULL),
list(c(1,2,3,4,5)))
expect_equal(optimParallel:::evalParallel(cl=cl, f=f1, args=NULL,
firstArg=matrix(c(1,2,3,4,5), ncol=5), parnames=NULL),
list(1,2,3,4,5))
expect_equal(optimParallel:::evalParallel(cl=cl, f=f1, args=list(a=1),
firstArg=matrix(c(1,2,3,4,5), ncol=5), parnames=NULL),
list(1,2,3,4,5))
expect_equal(optimParallel:::evalParallel(cl=cl, f=f1, args=list(x=100),
firstArg=matrix(c(1,2,3,4,5), ncol=5), parnames=NULL),
list(1,2,3,4,5))
})
test_that("evalParallel: f2", {
expect_equal(optimParallel:::evalParallel(cl=cl, f=f2, args=list(x=1,y=1),
firstArg=matrix(c(1:4), ncol=4), parnames=NULL),
list(f2(x=1, y=1),
f2(x=2, y=1),
f2(x=3, y=1),
f2(x=4, y=1)))
expect_equal(optimParallel:::evalParallel(cl=cl, f=f2, args=list(x=1,y=1),
firstArg=t(array(1:4, c(4,3))), parnames=NULL),
list(f2(x=c(1,1,1), y=1),
f2(x=c(2,2,2), y=1),
f2(x=c(3,3,3), y=1),
f2(x=c(4,4,4), y=1)))
expect_equal(optimParallel:::evalParallel(cl=cl, f=f2, args=list(y=1,x=1),
firstArg=t(array(1:4, c(4,3))), parnames=NULL),
list(f2(x=c(1,1,1), y=1),
f2(x=c(2,2,2), y=1),
f2(x=c(3,3,3), y=1),
f2(x=c(4,4,4), y=1)))
expect_error(optimParallel:::evalParallel(cl=cl, f=f2, args=list(x=1),
firstArg=t(array(1:4, c(4,3))), parnames=NULL))
})
test_that("evalParallel: f3 defaults", {
expect_equal(optimParallel:::evalParallel(cl=cl, f=f3, args=list(x=1),
firstArg=1, parnames=NULL),
list(f3(x=1)))
})
test_that("evalParallel: fnames", {
expect_equal(optimParallel:::evalParallel(cl=cl, f=fnames, args=list(x=1),
firstArg=array(1:3, c(3,1)), parnames=c("a","b","c")),
list(fnames(x=c(a=1,b=2,c=3))))
expect_equal(optimParallel:::evalParallel(cl=cl, f=fnames, args=list(x=1),
firstArg=array(1:6, c(3,2)),
parnames=c("a","b","c")),
list(fnames(x=c(a=1,b=2,c=3)),
fnames(x=c(a=4,b=5,c=6))))
expect_equal(optimParallel:::evalParallel(cl=cl, f=fnames, args=list(x=1),
firstArg=array(1:9, c(3,3)),
parnames=c("a","b","c")),
list(fnames(x=c(a=1,b=2,c=3)),
fnames(x=c(a=4,b=5,c=6)),
fnames(x=c(a=7,b=8,c=9))))
})
......@@ -21,7 +21,7 @@ GR1 <- function(par, sleep){
test_that("optimParallel",{
compareOptim(list(par=c(1,2,3), fn=FN1, gr=GR1, sleep=0,
method = "L-BFGS-B",
control=control),
verbose=verbose)
})
......@@ -46,42 +46,26 @@ GR3 <- function(par, sleep){
test_that("optimParallel - named arguments",{
compareOptim(list(par=c(a=1,b=2), fn=FN2, sleep=0,
method = "L-BFGS-B",
control=control),
verbose=verbose)
compareOptim(list(par=c(a=1,b=2), fn=FN2, gr= GR2, sleep=0,
method = "L-BFGS-B",
control=control),
verbose=verbose)
compareOptim(list(par=c(a=1), fn=FN3, sleep=0,
method = "L-BFGS-B",
control=control),
verbose=verbose)
compareOptim(list(par=c(a=1), fn=FN3, gr= GR3, sleep=0,
method = "L-BFGS-B",
control=control),
verbose=verbose)
})
test_that("optimParallel - use compiled code from other packages",{
compareOptim(list(par=1, fn=abs, method = "L-BFGS-B",
compareOptim(list(par=c(a=1), fn=dnorm,
control=control),
verbose=verbose)
expect_equal(optimParallel(par=1, fn=abs, aflaf=1, method = "L-BFGS-B"),
optim(par=1, fn=abs, method = "L-BFGS-B"))
compareOptim(list(par=1, fn=abs, gr=abs, method = "L-BFGS-B",
compareOptim(list(par=c(a=1), fn=dnorm, mean=1,
control=control),
verbose=verbose)
expect_equal(optimParallel(par=1, fn=abs, gr=abs, aflaf=1, method = "L-BFGS-B"),
optim(par=1, fn=abs, gr=abs, method = "L-BFGS-B"))
compareOptim(list(par=1, fn=dnorm, method = "L-BFGS-B",
control=control),
verbose=verbose)
compareOptim(list(par=1, fn=dnorm, mean=3, method = "L-BFGS-B",
control=control),
verbose=verbose)
expect_equal(optimParallel(par=1, fn=dnorm, mean=2, aflaf=1, method = "L-BFGS-B"),
optim(par=1, fn=dnorm, mean=2, method = "L-BFGS-B"))
})
......@@ -7,16 +7,14 @@ source("testsetup.R")
verbose <- FALSE
f1 <- function(x){
if(verbose) cat(x, "\n")
# if(verbose) cat(x, "\n")
sum(x)
}
f2 <- function(x){
if(verbose) cat(x, "\n")
if(any(x<0)) stop()
sum(x)
}
f3 <- function(x){
if(verbose) cat(x, "\n")
if(any(x>0)) stop()
sum(x)
}
......@@ -27,27 +25,67 @@ f5 <- function(x){
x[1]^2 + (1-x[2])^2+log(x[3])
}
test_that("basic",{
o1 <- optimParallel:::parallel_fg_generator(f1, cl=cl, args_list=list(verbose=verbose))
o1 <- optimParallel:::FGgenerator(par=c(1), f1, parallel=list(cl=cl))
expect_equal(o1$f(1), 1)
expect_equal(o1$g(1), 1)
o1 <- optimParallel:::FGgenerator(par=c(4,3), f1, parallel=list(cl=cl))
expect_equal(o1$f(c(1,1)), 2)
expect_equal(o1$g(c(1,1)), c(1,1))
o1 <- optimParallel:::FGgenerator(par=1:3, f1, parallel=list(cl=cl))
expect_equal(o1$f(c(1,1,2)), 4)
expect_equal(o1$g(c(1,1,2)), c(1,1,1))
o1 <- optimParallel:::FGgenerator(par=c(1), f1, gr=f1, parallel=list(cl=cl))
expect_equal(o1$f(1), 1)
expect_equal(o1$g(1), 1)
o1 <- optimParallel:::parallel_fg_generator(f1, args_list=list(verbose=verbose))
o1 <- optimParallel:::FGgenerator(par=c(4,3), f1, parallel=list(cl=cl))
expect_equal(o1$f(c(1,1)), 2)
expect_equal(o1$g(c(1,1)), c(1,1))
o1 <- optimParallel:::parallel_fg_generator(f1, args_list=list(verbose=verbose))
o1 <- optimParallel:::FGgenerator(par=1:3, f1, parallel=list(cl=cl))
expect_equal(o1$f(c(1,1,2)), 4)
expect_equal(o1$g(c(1,1,2)), c(1,1,1))
})
test_that("default args",{
ff1 <- function(x, a=1){
sum(x)+a
}
o1 <- optimParallel:::FGgenerator(par=c(1), ff1, parallel=list(cl=cl))
expect_equal(o1$f(1), 2)
expect_equal(o1$g(1), 1)
o1 <- optimParallel:::FGgenerator(par=c(1), ff1, a=10, parallel=list(cl=cl))
expect_equal(o1$f(1), 11)
expect_equal(o1$g(1), 1)
ff2 <- function(x, ...){
sum(x)+list(...)[["a"]]
}
o1 <- optimParallel:::FGgenerator(par=c(1), ff2, a=1, parallel=list(cl=cl))
expect_equal(o1$f(1), 2)
expect_equal(o1$g(1), 1)
o1 <- optimParallel:::FGgenerator(par=c(1), ff2, a=10, parallel=list(cl=cl))
expect_equal(o1$f(1), 11)
expect_equal(o1$g(1), 1)
o1 <- optimParallel:::FGgenerator(par=c(1), dnorm, a=1, parallel=list(cl=cl))
expect_equal(o1$f(2), dnorm(2))
expect_equal(o1$g(2), (dnorm(2+0.001)-dnorm(2-0.001))/0.002)
o1 <- optimParallel:::FGgenerator(par=c(1), dnorm, log=TRUE, parallel=list(cl=cl))
expect_equal(o1$f(2), dnorm(2, log=TRUE))
expect_equal(o1$g(2), (dnorm(2+0.001, log=TRUE)-dnorm(2-0.001, log=TRUE))/0.002)
})
test_that("bounds",{
o2 <- optimParallel:::parallel_fg_generator(f2, args_list=list(verbose=verbose), lower=0)
o2 <- optimParallel:::FGgenerator(1, f2, lower=0, parallel=list(cl=cl))
expect_equal(o2$f(1), 1)
expect_equal(o2$g(1), 1)
expect_equal(o2$f(0), 0)
expect_equal(o2$g(0), 1)
expect_error(o2$g(-1))
o3 <- optimParallel:::parallel_fg_generator(f3, upper=0, args_list=list(verbose=verbose))
o3 <- optimParallel:::FGgenerator(1, f3, upper=0, parallel=list(cl=cl))
expect_equal(o3$f(-1), -1)
expect_equal(o3$g(-1), 1)
expect_equal(o3$f(0), 0)
......@@ -58,12 +96,12 @@ test_that("bounds",{
test_that("derivative",{
o4 <- optimParallel:::parallel_fg_generator(f4)
o4 <- optimParallel:::FGgenerator(1:3, f4, parallel=list(cl=cl))
expect_equal(o4$g(c(1,2,3)), numDeriv::grad(f4, c(1,2,3)),
tolerance=1e-3)
expect_equal(o4$g(c(-1,2,-3.3)), numDeriv::grad(f4, c(-1,2,-3.3)),
tolerance=1e-3)
o4_2 <- optimParallel:::parallel_fg_generator(f4, forward=TRUE)
o4_2 <- optimParallel:::FGgenerator(1:3, f4, forward=TRUE, parallel=list(cl=cl))
expect_equal(o4_2$g(c(1,2,3)), numDeriv::grad(f4, c(1,2,3)),
tolerance=1e-3)
expect_equal(o4_2$g(c(-1,2,-3.3)), numDeriv::grad(f4, c(-1,2,-3.3)),
......@@ -71,15 +109,15 @@ test_that("derivative",{
})
test_that("eps",{
o5 <- optimParallel:::parallel_fg_generator(f5, ndeps=1e-3)
o5 <- optimParallel:::FGgenerator(1:3, f5, ndeps=1e-3, parallel=list(cl=cl))
expect_equal(o5$g(c(5,6,7)), numDeriv::grad(f5, c(5,6,7)),
tolerance=1e-3)
o5_2 <- optimParallel:::parallel_fg_generator(f5, ndeps=c(.01,.05,.001))
o5_2 <- optimParallel:::FGgenerator(1:3, f5, ndeps=c(.01,.05,.001), parallel=list(cl=cl))
expect_equal(o5_2$g(c(5,6,71)),
numDeriv::grad(f5, c(5,6,71),
method="simple"),
tolerance=1e-3)
o5_3 <- optimParallel:::parallel_fg_generator(f5, ndeps=c(.01,.05))
o5_3 <- optimParallel:::FGgenerator(1:3, f5, ndeps=c(.01,.05), parallel=list(cl=cl))
expect_equal(o5_3$g(c(5,6,71)),
numDeriv::grad(f5, c(5,6,71),
method="simple"),
......
......@@ -10,6 +10,7 @@ f1 <- function(par, x){
-sum(dnorm(x, par[1], par[2], log=TRUE))
}
f2 <- function(par, y){
# print(y)
-sum(dnorm(y, par[1], par[2], log=TRUE))
}
f3 <- function(par){
......@@ -49,61 +50,66 @@ f7 <- function(x, ...){
sum(x^2)
}
f8 <- function(zz, x){
# print(par)
-sum(dnorm(x, zz[1], zz[2], log=TRUE))
}
test_that("optimParallel",{
compareOptim(list(par=c(2,1), fn=f1, x=x, method = "L-BFGS-B",
lower=c(-Inf,0.001),
compareOptim(list(par=c(2,1), fn=f1, x=x, lower=c(-Inf,0.001),
control=list(factr=factr)), verbose=verbose)
compareOptim(list(par=c(2,1), fn=f1, x=x, method = "L-BFGS-B",
compareOptim(list(par=c(2,1), fn=f1, x=x,
lower=c(-Inf,0.001),
control=list(factr=factr)),
parallel=list(forward=TRUE),
verbose=verbose, tolerance=1e-2)
compareOptim(list(par=c(12,100), fn=f1, x=x, method = "L-BFGS-B",
compareOptim(list(par=c(12,100), fn=f1, x=x,
lower=c(-Inf,0.001),
control=list(factr=factr)), verbose=verbose)
compareOptim(list(par=c(12,100), fn=f1, x=x, method = "L-BFGS-B",
compareOptim(list(par=c(12,100), fn=f1, x=x,
lower=c(-Inf,0.001),
control=list(factr=factr)),
parallel=list(forward=TRUE), tolerance=1e-2,
verbose=verbose)
compareOptim(list(par=c(12,100), fn=f2, y=x,
method = "L-BFGS-B", lower=c(-Inf,0.001),
lower=c(-Inf,0.001),
control=list(factr=factr)), verbose=verbose)
expect_error(optimParallel(par=c(12,100), fn=f2,
method = "L-BFGS-B",
lower=c(-Inf,0.001),
control=list(factr=factr)))
control=list(factr=factr)),
"argument \"y\" is missing, with no default")
})
test_that("bounds",{
compareOptim(list(par=c(2), fn=f3, method = "L-BFGS-B",
compareOptim(list(par=c(2), fn=f3,
upper = c(10),
control=list(factr=factr)),
verbose=verbose)
compareOptim(list(par=c(2), fn=f3, method = "L-BFGS-B",
compareOptim(list(par=c(2), fn=f3,
upper = c(10),
control=list(factr=factr)),
parallel=list(forward=TRUE),
verbose=verbose)
compareOptim(list(par=c(2,1), fn=f3, method = "L-BFGS-B",
compareOptim(list(par=c(2,1), fn=f3,
upper = c(10,15),
control=list(factr=factr)),
verbose=verbose)
compareOptim(list(par=c(2,1), fn=f3, method = "L-BFGS-B",
compareOptim(list(par=c(2,1), fn=f3,
upper = c(10,15),
control=list(factr=factr)),
parallel=list(forward=TRUE),
verbose=verbose)
compareOptim(list(par=c(12,100), fn=function(x) sum(x), method = "L-BFGS-B",
compareOptim(list(par=c(12,100), fn=function(x) sum(x),
lower=c(14,-21),
control=list(factr=factr)), verbose=verbose)
compareOptim(list(par=c(12,100), fn=function(x) sum(x), method = "L-BFGS-B",
compareOptim(list(par=c(12,100), fn=function(x) sum(x),
lower=c(14,-21),
control=list(factr=factr)),
parallel=list(forward=TRUE), verbose=verbose)
......@@ -111,22 +117,22 @@ test_that("bounds",{
test_that("ndeps",{
compareOptim(list(par=c(2,1), fn=f1, x=x, method = "L-BFGS-B",
compareOptim(list(par=c(2,1), fn=f1, x=x,
lower=c(-Inf,0.001),
control=list(factr=factr, ndeps=c(.1,.1))),
verbose=verbose)
## compareOptim(list(par=c(2,1), fn=f1, method = "L-BFGS-B",
## compareOptim(list(par=c(2,1), fn=f1,
## lower=c(-Inf,0.001),
## control=list(factr=factr, ndeps=c(.1,.1))),
## parallel=list(forward=TRUE), tolerance=1e-3,
## verbose=verbose)
compareOptim(list(par=c(12,100), fn=f1, x=x, method = "L-BFGS-B",
compareOptim(list(par=c(12,100), fn=f1, x=x,
lower=c(-Inf,0.001),
control=list(factr=factr, ndeps=c(.1,.1))),
verbose=verbose)
## compareOptim(list(par=c(12,100), fn=f1, method = "L-BFGS-B",
## compareOptim(list(par=c(12,100), fn=f1,
## lower=c(-Inf,0.001),
## control=list(factr=factr, ndeps=c(.1,.1))),
## parallel=list(forward=TRUE), tolerance=1e-3,
......@@ -135,10 +141,10 @@ test_that("ndeps",{
test_that("fnscale",{
compareOptim(list(par=c(2,1), fn=f1, x=x, method = "L-BFGS-B",
compareOptim(list(par=c(2,1), fn=f1, x=x,
lower=c(-Inf,0.001),
control=list(factr=factr, fnscale=1000)), verbose=verbose)
compareOptim(list(par=c(2,1), fn=f1, x=x, method = "L-BFGS-B",
compareOptim(list(par=c(2,1), fn=f1, x=x,
lower=c(-Inf,0.001),
control=list(factr=factr, fnscale=1000)),
parallel=list(forward=TRUE), tolerance=1e-3,
......@@ -147,71 +153,44 @@ test_that("fnscale",{
test_that("parscale",{
compareOptim(list(par=c(2,1), fn=f1, x=x, method = "L-BFGS-B",
compareOptim(list(par=c(2,1), fn=f1, x=x,
lower=c(-Inf,0.001),
control=list(factr=factr,
parscale=c(2,4))),
verbose=verbose)
compareOptim(list(par=c(2,1), fn=f1, x=x, method = "L-BFGS-B",
compareOptim(list(par=c(2,1), fn=f1, x=x,
lower=c(-Inf,0.001),
control=list(parscale=c(2,4), maxit=1)),
parallel=list(forward=TRUE), tolerance=1e-2,
verbose=verbose)
compareOptim(list(par=c(2,1), fn=f1, x=x, method = "L-BFGS-B", lower=c(-Inf,0.001),
compareOptim(list(par=c(2,1), fn=f1, x=x, lower=c(-Inf,0.001),
control=list(factr=factr, parscale=c(.2,4))), verbose=verbose)
## compareOptim(list(par=c(2,1), fn=f1, method = "L-BFGS-B", lower=c(-Inf,0.001),
## compareOptim(list(par=c(2,1), fn=f1, lower=c(-Inf,0.001),
## control=list(factr=factr, parscale=c(.2,4))),
## parallel=list(forward=TRUE), tolerance=1e-3, verbose=verbose)
})
test_that("gradient",{
compareOptim(list(par=c(2), fn=f4, gr=g4, method = "L-BFGS-B",
compareOptim(list(par=c(2), fn=f4, gr=g4,
control=list(factr=factr)),
verbose=verbose)
compareOptim(list(par=c(2,1), fn=f4, gr=g4, method = "L-BFGS-B",
compareOptim(list(par=c(2,1), fn=f4, gr=g4,
control=list(factr=factr)),
verbose=verbose)
compareOptim(list(par=c(3,2,1), fn=f4, gr=g4, method = "L-BFGS-B",
compareOptim(list(par=c(3,2,1), fn=f4, gr=g4,
control=list(factr=factr)),
verbose=verbose)
})
test_that("... args",{
compareOptim(list(par=c(2), fn=f5, gr=g5, method = "L-BFGS-B",
control=list(factr=factr), a=1),
verbose=verbose)
compareOptim(list(par=c(2), fn=f5, method = "L-BFGS-B",
control=list(factr=factr), a=1),
verbose=verbose)
})
test_that("method = BFGS and CG",{
compareOptim(list(par=c(2), fn=f5, gr=g5, method = "BFGS",
compareOptim(list(par=c(2), fn=f5, gr=g5,
control=list(factr=factr), a=1),
verbose=verbose)
compareOptim(list(par=c(2), fn=f5, method = "BFGS",
control=list(factr=factr), a=1),
verbose=verbose)
compareOptim(list(par=c(2), fn=f5, gr=g5, method = "CG",
control=list(factr=factr), a=1),
verbose=verbose)
compareOptim(list(par=c(2), fn=f5, method = "CG",
compareOptim(list(par=c(2), fn=f5,
control=list(factr=factr), a=1),
verbose=verbose)
})
test_that("fn can have ... arguments",{
compareOptim(list(par=2, fn=f7, method = "L-BFGS-B",
control=list(factr=factr)),
verbose=verbose)
compareOptim(list(par=2, fn=f7, kjvasfa=4, method = "L-BFGS-B",
control=list(factr=factr)),
verbose=verbose)
expect_warning(optimParallel(par=2, fn=f7, x=2, control=list(factr=factr)),
"has the same name as one argument passed through")
})
......@@ -2,7 +2,6 @@
## library("testthat")
## library("optimParallel", lib.loc = "../../../lib/")
source("testsetup.R")
context("test-spam")
control <- structure(list(maxit = 10,
......@@ -12,7 +11,7 @@ control <- structure(list(maxit = 10,
test_that("optimParallel - mle.spam",{
skip_if_not(require("spam"), message="spam not available for testing dispatching to loaded packages")
clusterEvalQ(cl, require("spam"))
clusterEvalQ(getDefaultCluster(), require("spam"))
truebeta <- c(1,2,.2)
truetheta <- c(.5,2,.02)
......@@ -36,9 +35,9 @@ test_that("optimParallel - mle.spam",{
}
p <- dim(X)[2]
n <- length(y)
neg2loglikelihood <- function(fulltheta, ...) {
neg2loglikelihood <- function(fulltheta) {
Sigma <- do.call(Covariance, list(distmat, fulltheta[-(1:p)]))
cholS <- update.spam.chol.NgPeyton(Rstruct, Sigma, ...)
cholS <- update.spam.chol.NgPeyton(Rstruct, Sigma)
resid <- y - X %*% fulltheta[1:p]
return(n * log(2 * pi) + 2 * c(determinant.spam.chol.NgPeyton(cholS)$modulus) +
sum(resid * solve.spam(cholS, resid)))
......
......@@ -7,7 +7,7 @@ factr <- .01/.Machine$double.eps
set.seed(13)
compareOptim <- function(optim_args, parallel=NULL, tolerance = 1e-5, verbose=FALSE){
ref <- do.call("optim", optim_args)
ref <- do.call("optim", c(method="L-BFGS-B", optim_args))
o <- do.call("optimParallel",
c(optim_args, parallel=list(parallel)))
if(verbose){
......
rm(list=ls())
set.seed(11)
x <- rnorm(n = 1e7, mean = 5, sd = 2)
negll <- function(par, x) -sum(dnorm(x = x, mean = par[1], sd = par[2], log = TRUE))
o1 <- optim(par = c(1, 1), fn = negll, x = x, method = "L-BFGS-B",
lower = c(-Inf, 0.0001))
o1$par
# install.packages("optimParallel")
library("optimParallel")
library("microbenchmark")
library("ggplot2"); theme_set(theme_bw())
cl <- makeCluster(detectCores()); setDefaultCluster(cl = cl)
o2 <- optimParallel(par = c(1, 1), fn = negll, x = x, lower = c(-Inf, 0.0001))
identical(o1, o2)
o3 <- optimParallel(par = c(1, 1), fn = negll, x = x, lower = c(-Inf, 0.0001),
parallel=list(loginfo = TRUE))
head(o3$loginfo, n = 3)
tail(o3$loginfo, n = 3)
negll_gr <- function(par, x){
sm <- mean(x); n <- length(x)
c(-n*(sm-par[1])/par[2]^2,
n/par[2] - (sum((x-sm)^2) + n*(sm-par[1])^2)/par[2]^3)
}
o4 <- optimParallel(par = c(1, 1), fn = negll, gr = negll_gr, x = x,
lower = c(-Inf, 0.0001), parallel=list(loginfo = TRUE))
tail(o4$loginfo, n = 3)
measure <- function(expr, times=5, unit="s"){
## make Figure 1
library(ggplot2); theme_set(theme_bw())
library(foreach)
library(doParallel); registerDoParallel(12)
pdf("path.pdf", width = 8*.9*.9, height = 5*.8*.9)
grid <- expand.grid(par1=seq(.7, 7, length.out=100),
par2=seq(.7, 4, length.out=100),
z=NA)
grid$z <- foreach(i=1:nrow(grid), .combine=c) %dopar% {
negll(c(grid$par1[i], grid$par2[i]), x=x)
}
col <- alpha(colorRampPalette(c("gray"))(55), 1)
stroke <- 1.1
shape <- 1
ggplot(data=data.frame(o3$log), aes(x=par1, y=par2)) +
geom_contour(mapping=aes(x=par1, y=par2, z=z, color=..level..), data=grid,
bins=55) +
geom_vline(xintercept=data.frame(o3$log)[nrow(o3$log),"par1"], color="darkRed") +
geom_hline(yintercept=data.frame(o3$log)[nrow(o3$log),"par2"], color="darkRed") +
geom_segment(aes(xend=c(tail(par1, n=-1), NA), yend=c(tail(par2, n=-1), NA)),
arrow=arrow(length=unit(0.5,"cm"), type = "open", angle=30), size=.7,
color="darkBlue") +
geom_point(data=head(data.frame(o3$log),1), size =2, color="darkBlue")+
scale_color_gradientn(colours=col)+
scale_x_continuous(expand = c(0,0), limits=range(grid$par1), breaks=seq(0,10)) +
scale_y_continuous(expand = c(0,0), limits=range(grid$par2)) +
xlab(expression(mu)) + ylab(expression(sigma))+
theme(legend.position="none",
panel.grid.major = element_blank(), panel.grid.minor = element_blank())
dev.off()
o5 <- optimParallel(par = c(1, 1), fn = negll, x = x, lower = c(-Inf, 0.0001),
parallel = list(loginfo = TRUE, forward=TRUE))
o5$loginfo[17:19, ]
tail(o5$loginfo, n = 3)
o6 <- optimParallel(par = c(1, 1), fn = negll, x = x, lower = c(-Inf, 0.0001),
parallel = list(loginfo = TRUE, forward=TRUE),
control = list(factr=1e-6/.Machine$double.eps))
tail(o6$loginfo, n = 3)
## benchmark example
library("microbenchmark")
measure <- function(expr, times=50, unit="s"){
m <- microbenchmark(list=expr, times=times)
summary(m, unit="s")["mean"]
}
time_negll <- measure(expression(negll(par = c(1, 1), x=x)))
time_optimParallel <- measure(expression(
out <<- optimParallel(par=c(1,1), fn=negll, gr=NULL, x=x,
control=list(maxit=20), lower=c(-Inf, .001))))/out$counts[1]
time_optim <- measure(expression(
out <<- optim(par=c(1,1), fn=negll, gr=NULL, x=x,
method="L-BFGS-B",
control=list(maxit=20), lower=c(-Inf, .001))))/out$counts[1]
round(time_negll, 3)
round(time_optim, 3)
round(time_negll*5, 3)
round(time_optimParallel, 3)
round(100*(1 - time_optimParallel / time_optim), 3)
demo_generator <- function(fn, gr) {
par_last <- value <- grad <- NA
eval <- function(par) {
if(!identical(par, par_last)) {
message("--> evaluate fn() and gr()")
par_last <<- par
value <<- fn(par)
grad <<- gr(par)
} else
message("--> read stored value")
}
f <- function(par) {
eval(par = par)
value
}
g <- function(par) {
eval(par = par)
grad
}
list(fn = f, gr = g)
}
demo <- demo_generator(fn = sum, gr = prod)
demo$fn(1:5)
demo$gr(1:5)
## benchmark
fn <- function(par, sleep){
Sys.sleep(sleep)
sum(par^2)
}
gr <- function(par, sleep){
Sys.sleep(sleep)
2*par
}
## make Figure 2
PAR <- 100
FN <- function(par, sleep){
Sys.sleep(sleep)
......@@ -35,12 +164,10 @@ for(i in 1:nrow(grid)){
if(grid[i,"gr"]){
total <- measure(
expression(out <<- optimParallel(par=par, fn=FN, gr=GR, sleep=grid[i,"Tf"],
method=METHOD,
control=CONTROL)))
} else {
total <- measure(
expression(out <<- optimParallel(par=par, fn=FN, gr=NULL, sleep=grid[i,"Tf"],
method=METHOD,
control=CONTROL)))
}
grid[i, "To"] <- total/out$counts[1]
......@@ -61,8 +188,6 @@ for(i in 1:nrow(grid)){
print(grid[i,])
print(out$counts[1])
}
save(grid, file="benchmark.RData")
pdf("benchmark.pdf", width = 8*.9*.9, height = 5*.8*.9)
......
%\VignetteIndexEntry{Parallel versions of gradient-based optim() methods}
%\VignetteIndexEntry{A Parallel Version of the L-BFGS-B Optimization Method}
%\VignetteEngine{R.rsp::asis}
%\VignetteKeyword{parallel}
%\VignetteKeyword{optim}
......
rm(list=ls())
set.seed(11)
install.packages("optimParallel")
x <- rnorm(n=1000, mean=5, sd=2)
negll <- function(par, x) -sum(dnorm(x=x, mean=par[1], sd=par[2], log=TRUE))
o1 <- optim(par=c(1, 1), fn=negll, x=x, method="L-BFGS-B", lower=c(-Inf, 0.0001))
o1$par
install.packages("optimParallel")
library("optimParallel")
cl <- makeCluster(detectCores()); setDefaultCluster(cl=cl)
o2 <- optimParallel(par=c(1, 1), fn=negll, x=x, method="L-BFGS-B",
lower=c(-Inf, 0.0001))
identical(o1, o2)
o3 <- optimParallel(par=c(1, 1), fn=negll, x=x, method="L-BFGS-B",
lower=c(-Inf, 0.0001), parallel=list(loginfo=TRUE))
print(o3$loginfo[1:3,], digits=3)
## make fig
library(ggplot2); theme_set(theme_bw())
pdf("path.pdf", width = 8*.9*.9, height = 5*.8*.9)
grid <- expand.grid(par1=seq(.7, 7, length.out=100),
par2=seq(.7, 4, length.out=100),
z=NA)
for(i in 1:nrow(grid))
grid$z[i] <- negll(c(grid$par1[i], grid$par2[i]), x=x)
col <- alpha(colorRampPalette(c("gray"))(55), 1)
stroke <- 1.1
shape <- 1
ggplot(data=data.frame(o3$log), aes(x=par1, y=par2)) +
geom_contour(mapping=aes(x=par1, y=par2, z=z, color=..level..), data=grid,
bins=55) +
geom_vline(xintercept=data.frame(o3$log)[nrow(o3$log),"par1"], color="darkRed") +
geom_hline(yintercept=data.frame(o3$log)[nrow(o3$log),"par2"], color="darkRed") +
geom_segment(aes(xend=c(tail(par1, n=-1), NA), yend=c(tail(par2, n=-1), NA)),
arrow=arrow(length=unit(0.5,"cm"), type = "open", angle=30), size=.7,
color="darkBlue") +
geom_point(data=head(data.frame(o3$log),1), size =2, color="darkBlue")+
scale_color_gradientn(colours=col)+
scale_x_continuous(expand = c(0,0), limits=range(grid$par1)) +
scale_y_continuous(expand = c(0,0), limits=range(grid$par2)) +
xlab(expression(mu)) + ylab(expression(sigma))+
theme(legend.position="none",
panel.grid.major = element_blank(), panel.grid.minor = element_blank())
dev.off()
demo_generator <- function(fn, gr){
par_last <- value <- grad <- NA
eval <- function(par){
if(!identical(par, par_last)){
message("--> evaluate fn() and gr()")
par_last <<- par
value <<- fn(par)
grad <<- gr(par)
} else
message("--> read stored value")
}
f <- function(par){
eval(par=par)
value
}
g <- function(par){
eval(par=par)
grad
}
list(f=f, g=g)
}
demo <- demo_generator(fn=sum, gr=prod)
demo$f(1:5)
demo$g(1:5)
fn <- function(par, sleep){
Sys.sleep(sleep)
sum(par^2)
}
gr <- function(par, sleep){
Sys.sleep(sleep)
2*par
}