Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions R/module.R
Original file line number Diff line number Diff line change
Expand Up @@ -396,10 +396,12 @@ predict.luz_module_fitted <- function(object, newdata, ..., callbacks = list(),
)

pars <- rlang::list2(...)
if (is.null(pars$stack))
if (is.null(pars$stack)) {
stack <- TRUE
else
} else {
stack <- pars$stack
pars$stack <- NULL # pop from this list
}

predict_fn <- if (is.null(ctx$model$predict)) ctx$model else ctx$model$predict

Expand All @@ -416,7 +418,7 @@ predict.luz_module_fitted <- function(object, newdata, ..., callbacks = list(),
coro::loop(for(batch in ctx$data) {
ctx$batch <- batch
ctx$call_callbacks("on_predict_batch_begin")
ctx$pred[[length(ctx$pred) + 1]] <- do.call(predict_fn, list(ctx$input))
ctx$pred[[length(ctx$pred) + 1]] <- do.call(predict_fn, rlang::list2(ctx$input, !!!pars))
ctx$call_callbacks("on_predict_batch_end")
})
}
Expand Down
28 changes: 28 additions & 0 deletions tests/testthat/test-module.R
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,34 @@ test_that("predict works for modules", {

})

test_that("predict passes additional arguments", {

base_model <- get_model()
model <- torch::nn_module(
inherit = base_model,
predict = function(x, scale = 1) {
self$forward(x) * scale
}
)
dl <- get_dl()

fitted <- model %>%
setup(
loss = torch::nn_mse_loss(),
optimizer = torch::optim_adam
) %>%
set_hparams(input_size = 10, output_size = 1) %>%
fit(dl, verbose = FALSE)

pred <- predict(fitted, dl)
pred_scaled <- predict(fitted, dl, scale = 2)

expect_equal(
as.array(pred_scaled$to(device = "cpu")),
2 * as.array(pred$to(device = "cpu"))
)
})

test_that("predict can use a progress bar", {

model <- get_model()
Expand Down
Loading