Repository navigation
Conversation
…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>
njtierney
commented
Oct 23, 2026
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()). |
Collaborator
Author
There was a problem hiding this comment.
Explain what "weakly" means here. And make this more concise.
njtierney
commented
Oct 23, 2026
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 | ||
| ) |
Collaborator
Author
There was a problem hiding this comment.
Why are you using py_run_string() when you could create the python code with reticulate?
njtierney
commented
Oct 23, 2026
| * `[<-` 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). |
Collaborator
Author
There was a problem hiding this comment.
re-write this for clarity, make more concise, keep benchmark
njtierney
commented
Oct 26, 2026
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) | ||
| }) |
Collaborator
Author
There was a problem hiding this comment.
this feels like an antipattern - using <<- and also reg.finalizer - very unusual function?
… 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:On main (ea4e23f):
On this branch (a98e889):
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):
mcmc()opt()withbfgs()opt()withadam()The table's code
Please check:
opt()with a Keras optimiser andmcmc()withslice()still leave a few graphs per call in TensorFlow's gradient registry, though not the model.clear_bijector_cache()uses TFP's private_cache.🤖 Generated with Claude Code