% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/backends.R
\name{threading}
\alias{threading}
\title{Threading in Stan}
\usage{
threading(threads = NULL, grainsize = NULL, static = FALSE, force = FALSE)
}
\arguments{
\item{threads}{Number of threads to use in within-chain parallelization.}

\item{grainsize}{Number of observations evaluated together in one chunk on
one of the CPUs used for threading. If \code{NULL} (the default),
\code{grainsize} is currently chosen as \code{max(100, N / (2 *
threads))}, where \code{N} is the number of observations in the data. This
default is experimental and may change in the future without prior notice.}

\item{static}{Logical. Apply the static (non-adaptive) version of
\code{reduce_sum}? Defaults to \code{FALSE}. Setting it to \code{TRUE}
is required to achieve exact reproducibility of the model results
(if the random seed is set as well).}

\item{force}{Logical. Defaults to \code{FALSE}. If \code{TRUE}, this will
force the Stan model to compile with threading enabled without altering the
Stan code generated by brms. This can be useful if your own custom Stan
functions use threading internally.}
}
\value{
A \code{brmsthreads} object which can be passed to the
  \code{threads} argument of \code{brm} and related functions.
}
\description{
Use threads for within-chain parallelization in \pkg{Stan} via the \pkg{brms}
interface. Within-chain parallelization is experimental! We recommend its use
only if you are experienced with Stan's \code{reduce_sum} function and have a
slow running model that cannot be sped up by any other means.
}
\details{
The adaptive scheduling procedure used by \code{reduce_sum} will
  prevent the results to be exactly reproducible even if you set the random
  seed. If you need exact reproducibility, you have to set argument
  \code{static = TRUE} which may reduce efficiency a bit.

  To ensure that chunks (whose size is defined by \code{grainsize}) require
  roughly the same amount of computing time, we recommend storing
  observations in random order in the data. At least, please avoid sorting
  observations after the response values. This is because the latter often
  cause variations in the computing time of the pointwise log-likelihood,
  which makes up a big part of the parallelized code.
}
\examples{
\dontrun{
# this model just serves as an illustration
# threading may not actually speed things up here
fit <- brm(count ~ zAge + zBase * Trt + (1|patient),
           data = epilepsy, family = negbinomial(),
           chains = 1, threads = threading(2, grainsize = 100),
           backend = "cmdstanr")
summary(fit)
}

}
