Skip to content

Free models once nothing refers to them (#279) - #865

Draft
njtierney wants to merge 9 commits into
mainfrom
i279-free-models
Draft

njtierney wants to merge 9 commits into
mainfrom
i279-free-models

Conversation

@njtierney

@njtierney njtierney commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #279.

A model, and every graph traced for it, stayed in memory after nothing in R referred to it. reticulate keeps the R function behind a traced TensorFlow function alive, and greta keeps each traced function on the object whose method it traces, so each kept the other alive. TFP's bijector cache also held graphs. The new tf_function_weakly() reaches each traced R function through a weak reference, and clears that cache after each trace.

Graphs left by five fresh mcmc() fits:

library(greta)
reticulate::py_run_string("
def count_graphs():
    import gc
    import tensorflow as tf
    gc.collect()
    return sum(isinstance(o, tf.Graph) for o in gc.get_objects())
")

# R's garbage collector then Python's, twice: freeing an R object can free a
# Python object, and freeing that can free R objects
collect_garbage <- function() {
  for (pass in 1:2) {
    gc()
    reticulate::import("gc")$collect()
  }
}

fit_fresh_model <- function() {
  x <- normal(0, 1, dim = 2)
  draws <- mcmc(model(x), warmup = 100, n_samples = 100, verbose = FALSE)
  invisible()
}

fit_fresh_model()
collect_garbage()
before <- reticulate::py$count_graphs()
for (i in 1:5) {
  fit_fresh_model()
}
collect_garbage()
reticulate::py$count_graphs() - before

On main (ea4e23f):

#> [1] 70

On this branch (a98e889):

#> [1] 0

Memory footprint and graphs added per call on a fresh model, after the first 5 of 20, mean of 3 sessions (benchmark post, not yet published):

Call greta 0.6.0 main (2e769b0) this PR (e704e4a)
mcmc() 41 MB, 13 graphs 26.5 MB, 14 graphs 1.52 MB, 0 graphs
opt() with bfgs() 9.56 MB, 4 graphs 9.34 MB, 3 graphs none, 0 graphs
opt() with adam() 15 MB, 5 graphs 14.3 MB, 6 graphs 10.3 MB, 5 graphs
The table's code
library(dplyr)

# the post's raw results, from its branch of greta.benchmarks
benchmarks_repo <- path.expand("~/github/greta-dev/greta.benchmarks")
post_branch <- "free-models-i279"
post_path <- "posts/2026-10-22-free-models-i279"
git_benchmarks <- function(..., stdout = "|") {
  processx::run("git", c("-C", benchmarks_repo, ...), stdout = stdout)
}
read_session <- function(path) {
  file <- tempfile(fileext = ".rds")
  git_benchmarks("show", paste0(post_branch, ":", path), stdout = file)
  readRDS(file)
}
session_paths <- git_benchmarks(
  "ls-tree",
  "--name-only",
  post_branch,
  paste0(post_path, "/results/")
)$stdout |>
  strsplit("\n") |>
  unlist() |>
  grep(pattern = "session-[0-9]+[.]rds$", value = TRUE)
sessions <- lapply(session_paths, read_session)
n_calls <- sessions[[1]]$results[[1]]$settings$n_calls

# from here to `growth`, the post's code: every measurement, one row per
# session, version, loop and call, call 0 being before the loop's first call
measures <- c("footprint_mb", "graphs")
measurements <- lapply(sessions, function(session_file) {
  lapply(names(session_file$results), function(version) {
    loops <- session_file$results[[version]]$loops
    lapply(names(loops), function(loop) {
      loops[[loop]] |>
        mutate(session = session_file$session, version = version, loop = loop)
    }) |>
      bind_rows()
  }) |>
    bind_rows()
}) |>
  bind_rows()

# the first calls in a session make objects TensorFlow keeps for the rest of
# it, whatever the version
first_calls <- 5

increases <- measurements |>
  arrange(session, version, loop, call) |>
  group_by(session, version, loop) |>
  mutate(across(all_of(measures), \(x) x - lag(x))) |>
  ungroup() |>
  filter(call > first_calls)

growth <- increases |>
  group_by(loop, version) |>
  summarise(across(all_of(measures), mean), .groups = "drop")

# the post's rounding
format_number <- function(x) {
  trimws(formatC(signif(x, 3), format = "fg", digits = 3, big.mark = ","))
}

# "1.52 MB, 0 graphs"; a mean below zero is the footprint moving up and down
# from call to call, so it reads "none"
added_text <- function(footprint_mb, graphs) {
  footprint_grew <- footprint_mb > 0
  memory <- if_else(
    footprint_grew,
    paste(format_number(footprint_mb), "MB"),
    "none"
  )
  graph_word <- if_else(graphs == 1, "graph", "graphs")
  paste0(memory, ", ", format_number(graphs), " ", graph_word)
}

# "greta 0.6.0", and main and this PR at the commits the post ran
versions_run <- sessions[[1]]$versions
cran_version <- sessions[[1]]$results$CRAN$provenance$greta_version
commit_of <- \(version) substr(sub(".*@", "", versions_run[[version]]), 1, 7)
version_labels <- c(
  CRAN = paste("greta", cran_version),
  main = paste0("main (", commit_of("main"), ")"),
  `i279-free-models` = paste0("this PR (", commit_of("i279-free-models"), ")")
)
loop_labels <- c(
  mcmc = "`mcmc()`",
  opt = "`opt()` with `bfgs()`",
  opt_adam = "`opt()` with `adam()`"
)
per_call <- growth |>
  filter(loop %in% names(loop_labels)) |>
  arrange(factor(loop, levels = names(loop_labels))) |>
  mutate(
    Call = loop_labels[loop],
    version = version_labels[version],
    added = added_text(footprint_mb, graphs)
  ) |>
  select(Call, version, added) |>
  tidyr::pivot_wider(names_from = version, values_from = added) |>
  select(Call, all_of(unname(version_labels)))

Please check:

  • opt() with a Keras optimiser and mcmc() with slice() still leave a few graphs per call in TensorFlow's gradient registry, though not the model.
  • clear_bijector_cache() uses TFP's private _cache.
  • NEWS links the post, so publish it before merging.

🤖 Generated with Claude Code

njtierney and others added 5 commits October 22, 2026 19:00
…ing greta's functions through weak references and clearing TFP's bijector cache after each trace (#279)

- DESCRIPTION: tfautograph in Imports, which tensorflow::tf_function() needs to autograph and greta used undeclared
- R/utils.R: tf_function_weakly() traces a wrapper that finds greta's autographed function through a weak reference keyed on the traced function's R handle, so reticulate's hold on the wrapper no longer keeps the function and its model alive
- R/utils.R: the wrapper gives an internal error if its function was freed, and clears TFP's session-wide bijector cache once each trace ends, as its entries keep each traced graph alive
- R/dag_class.R, R/sampler_class.R, R/optimiser_class.R: greta's traced functions use tf_function_weakly()
- tests/testthat/helpers.R: collect_garbage(), count_live_instances() and dag_freed_after()
- tests/testthat/test-utils.R: tf_function_weakly() autographs, and a freed function gives the internal error
- tests/testthat/test_inference.R: a model mcmc() has sampled is freed, and fitting fresh models in a loop keeps no Python objects alive
- tests/testthat/test_opt.R: a model whose opt() loop is kept on it is freed; the uncached-loop test uses count_live_instances()
- tests/testthat/test-dag_class.R: a dropped model's traced log density leaves no extra graphs
- NEWS.md: bullet for #279

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… frees f once its handle is dropped and that opt() leaves no graph (#279)

- R/utils.R: call_weakly_held() passes no arguments to a function that takes none, where mget() rejected the NULL names() of no arguments
- R/utils.R: the comments say to keep and call through the handle, why the wrapper clears the bijector cache, and that a nested trace clears it partway through the outer one
- tests/testthat/test-utils.R: a function with no arguments traces, and f lives as long as its handle and no longer, even when f reaches the handle
- tests/testthat/test_opt.R: opt() with bfgs() leaves no graph once its model is dropped
- tests/testthat/test_inference.R: the mcmc() helper is fit_mcmc() and the collection loop's variable is pass, so neither shadows base R

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nd say in one place why f is autographed on its own (#279)

- tests/testthat/helpers.R: live_instance_growth() counts the instances a Python class gains over three more calls, fit_fresh_model() fits and drops a new model, and collect_garbage() runs R's then Python's collector twice, so count_live_instances() no longer collects again itself
- tests/testthat/test-dag_class.R, tests/testthat/test_calculate.R, tests/testthat/test_opt.R: the graph and traced-function tests use live_instance_growth()
- tests/testthat/test-utils.R: f is a one-line function, which reaches the handle through its enclosure without naming it
- R/utils.R: one comment explains why f is autographed rather than the wrapper, and the header says each trace clears the bijector cache

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…easured in greta.benchmarks and the two exceptions TensorFlow causes (#279)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread R/utils.R Outdated
Comment on lines +50 to +59
# tensorflow::tf_function(), holding f weakly. reticulate keeps the R function
# a Python function wraps alive for as long as the Python function, by a
# reference R's garbage collector cannot see past, so a dag or sampler method
# whose object keeps the traced function would keep both, and the model,
# alive for the rest of the session (greta-dev/greta#279). The Python function
# wraps one that finds f through a weak reference keyed on the R handle to the
# traced function instead, so f lives as long as that handle. Keep the handle
# this returns and call through it: a handle reticulate makes afresh from the
# same Python function does not keep f alive. Each trace also clears TFP's
# bijector cache, which would otherwise keep the graph (clear_bijector_cache()).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Explain what "weakly" means here. And make this more concise.

Comment thread tests/testthat/helpers.R Outdated
Comment on lines +1341 to +1348
python <- reticulate::py_run_string(
"
def count_instances(python_class):
import gc
return sum(isinstance(o, python_class) for o in gc.get_objects())
",
local = TRUE
)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are you using py_run_string() when you could create the python code with reticulate?

Comment thread NEWS.md Outdated
* `[<-` on a greta array fills a matrix or array replacement column by column, as R does (#844).
* `mcmc()` and `extra_samples()` keep `n_samples %/% thin` draws, regardless of values of `pb_update` and `one_by_one`. A burst shorter than `thin` used to error, as in a final partial burst, `one_by_one = TRUE` with `thin` above 1, or `extra_samples()` with `pb_update` at or below `thin`. They run all `n_samples` iterations even when `thin` does not divide it, `one_by_one = TRUE` rejects only the proposal that caused a numerical error, and a `thin` larger than `n_samples` is an informative error (#241, #318, #567, #609).
* `mcmc()`'s progress bar reaches its total when `pb_update` does not divide the number of iterations, and fills in step with the iterations run; a bar could read 1010/1010 while still empty (#318).
* `model()` no longer keeps every model in memory for the rest of the session, with the TensorFlow graphs traced for it, so fitting fresh models in a loop with `mcmc()`, `opt()` or `calculate()`, as in a simulation study, no longer piles them up. On greta's `linear` example, each fresh `mcmc()` call added 41 MB to the session in greta 0.6.0 and adds 1.5 MB now, and each `opt()` call added 9.6 MB and adds none ([benchmarks](https://greta-dev.github.io/greta.benchmarks/posts/2026-10-22-free-models-i279/)). `opt()` with a Keras optimiser such as `adam()`, and `mcmc()` with `slice()`, still keep a few graphs with each call, though not the model, as TensorFlow keeps every custom gradient it traces (#279).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re-write this for clarity, make more concise, keep benchmark

Comment thread tests/testthat/test-utils.R Outdated
Comment on lines +24 to +29
traced <- local({
held_by_f <- new.env()
reg.finalizer(held_by_f, \(env) freed <<- TRUE)
twice <- \(x) x * 2
held_by_f$traced <- tf_function_weakly(twice)
})

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this feels like an antipattern - using <<- and also reg.finalizer - very unusual function?

njtierney and others added 4 commits October 29, 2026 11:54
… fewer lines (#279)

- The traced function reaches f through a weak reference, which keeps f alive only while the returned handle is kept

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…finaliser and <<- (#279)

- tests/testthat/test-utils.R: the handle-lifetime test keeps a weak reference to a stand-in dag and checks it is emptied once the dag is dropped
- tests/testthat/helpers.R: dag_freed_after() does the same, and fit_fresh_model() returns what fit() returns, so dag_freed_after() can hand the weak reference back

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…g() (#279)

- count_live_instances() maps the class's __instancecheck__ over gc.get_objects() with Python's map() and sum(), so no object is converted to R

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The benchmark post's opt() figure on this branch is a mean pulled below zero by one call, so it is left out until the post summarises it better

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Possible memory leak in mcmc function

1 participant