% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/callbacks.R
\name{luz_callback}
\alias{luz_callback}
\title{Create a new callback}
\usage{
luz_callback(
  name = NULL,
  ...,
  private = NULL,
  active = NULL,
  parent_env = parent.frame(),
  inherit = NULL
)
}
\arguments{
\item{name}{name of the callback}

\item{...}{Public methods of the callback. The name of the methods is used
to know how they should be called. See the details section.}

\item{private}{An optional list of private members, which can be functions
and non-functions.}

\item{active}{An optional list of active binding functions.}

\item{parent_env}{An environment to use as the parent of newly-created
objects.}

\item{inherit}{A R6ClassGenerator object to inherit from; in other words, a
superclass. This is captured as an unevaluated expression which is
evaluated in \code{parent_env} each time an object is instantiated.}
}
\value{
A \code{luz_callback} that can be passed to \code{\link[=fit.luz_module_generator]{fit.luz_module_generator()}}.
}
\description{
Create a new callback
}
\details{
Let’s implement a callback that prints ‘Iteration \code{n}’ (where \code{n} is the
iteration number) for every batch in the training set and ‘Done’ when an
epoch is finished. For that task we use the \code{luz_callback} function:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{print_callback <- luz_callback(
  name = "print_callback",
  initialize = function(message) \{
    self$message <- message
  \},
  on_train_batch_end = function() \{
    cat("Iteration ", ctx$iter, "\n")
  \},
  on_epoch_end = function() \{
    cat(self$message, "\n")
  \}
)
}\if{html}{\out{</div>}}

\code{luz_callback()} takes named functions as \code{...} arguments, where the
name indicates the moment at which the callback should be called. For
instance \code{on_train_batch_end()} is called for every batch at the end of
the training procedure, and \code{on_epoch_end()} is called at the end of
every epoch.

The returned value of \code{luz_callback()} is a function that initializes an
instance of the callback. Callbacks can have initialization parameters,
like the name of a file where you want to log the results. In that case,
you can pass an \code{initialize} method when creating the callback
definition, and save these parameters to the \code{self} object. In the above
example, the callback has a \code{message} parameter that is printed at the
end of each epoch.

Once a callback is defined it can be passed to the \code{fit} function via
the \code{callbacks} parameter:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{fitted <- net \%>\%
  setup(...) \%>\%
  fit(..., callbacks = list(
    print_callback(message = "Done!")
  ))
}\if{html}{\out{</div>}}

Callbacks can be called in many different positions of the training
loop, including combinations of them. Here’s an overview of possible
callback \emph{breakpoints}:

\if{html}{\out{<div class="sourceCode">}}\preformatted{Start Fit
   - on_fit_begin
  Start Epoch Loop
     - on_epoch_begin
    Start Train
       - on_train_begin
      Start Batch Loop
         - on_train_batch_begin
          Start Default Training Step
            - on_train_batch_after_pred
            - on_train_batch_after_loss
            - on_train_batch_before_backward
            - on_train_batch_before_step
            - on_train_batch_after_step
          End Default Training Step:
         - on_train_batch_end
      End Batch Loop
       - on_train_end
    End Train
    Start Valid
       - on_valid_begin
      Start Batch Loop
         - on_valid_batch_begin
          Start Default Validation Step
            - on_valid_batch_after_pred
            - on_valid_batch_after_loss
          End Default Validation Step
         - on_valid_batch_end
      End Batch Loop
       - on_valid_end
    End Valid
      - on_epoch_end
  End Epoch Loop
   - on_fit_end
End Fit
}\if{html}{\out{</div>}}

Every step marked with \verb{on_*} is a point in the training procedure that
is available for callbacks to be called.

The other important part of callbacks is the \code{ctx} (context) object. See
\code{help("ctx")} for details.

By default, callbacks are called in the same order as they were passed
to \code{fit} (or \code{predict} or \code{evaluate}), but you can provide a \code{weight}
attribute that will control the order in which it will be called. For
example, if one callback has \code{weight = 10} and another has \code{weight = 1},
then the first one is called after the second one. Callbacks that don’t
specify a \code{weight} attribute are considered \code{weight = 0}. A few built-in
callbacks in luz already provide a weight value. For example, the
\code{?luz_callback_early_stopping} has a weight of \code{Inf}, since in general
we want to run it as the last thing in the loop.
}
\section{Prediction callbacks}{


You can also use callbacks when using \code{\link[=predict]{predict()}}. In this case the supported
callback methods are detailed below:

\if{html}{\out{<div class="sourceCode">}}\preformatted{Start predict
 - on_predict_begin
 Start prediction loop
  - on_predict_batch_begin
  - on_predict_batch_end
 End prediction loop
 - on_predict_end
End predict
}\if{html}{\out{</div>}}
}

\section{Evaluate callbacks}{


Callbacks can also be used with \code{\link[=evaluate]{evaluate()}}, in this case, the callbacks that
are used are equivalent to those of the validation loop when using \code{\link[=fit]{fit()}}:

\if{html}{\out{<div class="sourceCode">}}\preformatted{Start Valid
 - on_valid_begin
 Start Batch Loop
  - on_valid_batch_begin
  Start Default Validation Step
   - on_valid_batch_after_pred
   - on_valid_batch_after_loss
  End Default Validation Step
  - on_valid_batch_end
 End Batch Loop
 - on_valid_end
End Valid
}\if{html}{\out{</div>}}
}

\examples{
print_callback <- luz_callback(
 name = "print_callback",
 on_train_batch_end = function() {
   cat("Iteration ", ctx$iter, "\n")
 },
 on_epoch_end = function() {
   cat("Done!\n")
 }
)
}
\seealso{
Other luz_callbacks: 
\code{\link{luz_callback_auto_resume}()},
\code{\link{luz_callback_csv_logger}()},
\code{\link{luz_callback_early_stopping}()},
\code{\link{luz_callback_interrupt}()},
\code{\link{luz_callback_keep_best_model}()},
\code{\link{luz_callback_lr_scheduler}()},
\code{\link{luz_callback_metrics}()},
\code{\link{luz_callback_mixed_precision}()},
\code{\link{luz_callback_mixup}()},
\code{\link{luz_callback_model_checkpoint}()},
\code{\link{luz_callback_profile}()},
\code{\link{luz_callback_progress}()},
\code{\link{luz_callback_resume_from_checkpoint}()},
\code{\link{luz_callback_train_valid}()}
}
\concept{luz_callbacks}
