Skip to content

Commit

Permalink
make sure deep cloning preserves state dict attributes (#1129)
Browse files Browse the repository at this point in the history
  • Loading branch information
dfalbel committed Jan 24, 2024
1 parent a182f76 commit 68cc891
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
8 changes: 6 additions & 2 deletions R/nn.R
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ nn_Module <- R6::R6Class(
par <- private$parameters_[[i]]
# par or buf might not be available in `table` if, for some reason they
# have already been replaced. This happens for example, when a module
# has the same layer twice. this also applies for modules, they might be duplicated
# has the same layer twice. this also applies for modules, they might be duplicated
private$parameters_[[i]] <- table[[xptr_address(par)]] %||% par
}
for (i in seq_along(private$buffers_)) {
Expand Down Expand Up @@ -527,7 +527,11 @@ create_nn_module_callable <- function(instance) {
names(state_dict) <- sapply(state_dict, xptr_address)

state_dict <- state_dict[!duplicated(names(state_dict))]
state_dict <- lapply(state_dict, function(x) x$detach()$clone())
state_dict <- lapply(state_dict, function(x) {
out <- x$detach()$clone()
attributes(out) <- attributes(x)
out
})

# also need to append a clone of the modules to this list.
# child modules can be duplicated - and have the same name
Expand Down
9 changes: 9 additions & 0 deletions tests/testthat/test-nn.R
Original file line number Diff line number Diff line change
Expand Up @@ -706,6 +706,15 @@ test_that("deep cloning", {

# make sure we re-lock binding
expect_true(bindingIsLocked("clone", attr(x, "module")))

# make sure the class of parameters remains
a <- nn_linear(1, 1)
b <- a$clone(deep = TRUE)

expect_equal(
attributes(b$parameters$weight),
attributes(a$parameters$weight)
)
})

test_that("Can initialize a model in the meta device and copy parameters to it", {
Expand Down

0 comments on commit 68cc891

Please sign in to comment.