Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make sure deep cloning preserves state dict attributes #1129

Merged
merged 1 commit into from
Jan 24, 2024
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: 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
Loading