Skip to content

Write back registered list slots after unproxying (fixes #176) - #177

Open
hersh11 wants to merge 5 commits into
OrderLab:mainfrom
hersh11:fix-unproxy-list-inplace
Open

hersh11 wants to merge 5 commits into
OrderLab:mainfrom
hersh11:fix-unproxy-list-inplace

Conversation

@hersh11

@hersh11 hersh11 commented Nov 25, 2026 •

Copy link
Copy Markdown

Fixes #176.

Problem

unproxy_arg builds a new list for every list argument. The auto observer wraps torch.optim.sgd.sgd with unproxying (in both proxy and subclass model-tracker styles), and sgd returns its newly created momentum buffers by storing them into momentum_buffer_list[i]; SGD.step then reads them back from its own list. Those writes went into the copy, so every buffer stayed None and momentum was reset on every step. Training silently ran as plain SGD.

The first version of this PR unproxied lists in place. As Essoz found, that also replaces the proxies in the caller's params list, so optimizer.state gets keyed by the underlying tensors (8 entries for 4 parameters in proxy mode, and optimizer.state_dict() raises KeyError).

Approach

  • unproxy_arg copies every list again, as on main. Callers' lists keep their proxies.
  • New traincheck/instrumentor/proxy_wrapper/list_writeback.py holds a registry, LIST_WRITEBACK_ARGUMENTS, mapping an API name (as typename produces it) to the names of its fixed-length list parameters whose replaced slots must reach the caller. It starts with torch.optim.sgd.sgd: {"momentum_buffer_list"}.
  • For a registered parameter passed as a list (positionally or by keyword), the callee still receives the unproxied copy. After the call, every slot that now holds a different object than the one passed in (compared by identity, so None becoming a tensor counts) is written into the caller's list. Slots the callee did not replace, including slots holding proxies, are left alone. Ordinary lists, tuples, and registered parameters passed as something other than a list are unproxied exactly as before.
  • The write-back also runs when the callee raises, and the original exception is re-raised unchanged.
  • Contract violations raise ListWritebackError instead of losing or overwriting writes silently:
    • when wrapping: a registry entry naming a parameter the function does not have (for example after a PyTorch rename), or a variadic parameter;
    • before the call: the same list passed to two registered parameters (unproxying gives each occurrence its own copy, so the callee could not see them as one list);
    • after the call: a registered list whose length changed, or a replaced slot that was also changed in the caller's list through another reference during the call. All lists are checked before any slot is written, so a failed write-back leaves the caller's lists as the callee left them. If this happens while the callee is raising, the ListWritebackError is raised from the original exception.
  • The same helpers are used at every site that unproxies arguments and then calls the function:
    • proxy_basics.unproxy_func, used by the auto observer (which passes its precomputed API name) and by torch_proxy.py (where the name is derived with typename). Registered parameters are resolved when wrapping.
    • The unproxy branch of tracer.function_wrapper. Unregistered functions keep the direct call. For registered ones, the write-back is prepared inside the traced call, so a failure is recorded as FUNC_CALL_POST_EXCEPTION like any other.
    • The dump-disabled path, which gets a separate core_wrapper_proxy_list_writeback chosen when wrapping, so unregistered functions keep the existing core_wrapper_proxy.
  • Separate commit: unproxy_func is now annotated, and mypy then flags torch_proxy.py passing tokenize.__dict__.get("_tokenize") (Any | None). _tokenize is now wrapped only when it exists. It exists on every Python I checked (3.11, 3.12, 3.13), so behaviour there is unchanged.

Behaviour and contracts

  • Preserved: callers' lists and their proxies, return values, exceptions and their tracebacks, and the tracer's trace records. For unregistered functions the call path is the one on main apart from one dict lookup.
  • Changed: for registered APIs, the slots the callee replaced reach the caller. That is the fix.
  • Added work: unregistered functions pay one dict lookup when the wrapper is built. The observer builds unproxy_func on every call, so there it is per call, and function_wrapper does it per call in its unproxy branch. Registered functions also pay an inspect.signature when wrapping, or per call in function_wrapper, which sgd does not go through. Each registered call also copies the registered lists' references once. No timing was measured; this is a correctness change.

Validation

tests/test_unproxy_list_writeback.py (27 tests) replaces tests/test_unproxy_list_inplace.py:

  • write-back unit tests: lists are copied and the caller keeps its proxies; positional, keyword and keyword-only write-back; unreplaced slots keep their proxies; write-back before re-raising; a registered parameter passed as a tuple or omitted;
  • contract tests: length change; length change while raising; no slot written when any check fails; unknown and variadic registry parameters (rejected when wrapping); the same list for two registered parameters; a slot changed through another reference, and the same object written through both references;
  • the registry matches the installed PyTorch (name and signature); functional sgd called with proxied arguments; SGD.step with an unproxied sgd matches plain SGD.step;
  • tracer.function_wrapper (normal, raising, unregistered, and a registry mismatch recorded as FUNC_CALL_POST_EXCEPTION), the dump-disabled wrapper (registered, unregistered), and tracer.wrapper rejecting a mismatch when wrapping.

End to end, as requested in review: tests/fixtures/sgd_momentum_probe.py trains a small two-layer model for 4 SGD steps with momentum. It records the losses, momentum buffers and parameters (as float.hex), the number of optimizer state entries and whether every key is one of the model's parameters. It then saves optimizer.state_dict(), loads it into a new optimizer and takes one more step. The test runs this plainly and under python -m traincheck.collect_trace in proxy and subclass styles, and requires:

  • identical reports;
  • that the training process imported this checkout (the runner overwrites PYTHONPATH, so an installed copy elsewhere would otherwise be tested silently);
  • that the trace contains torch.optim.sgd.sgd observations;
  • a control run per style, with the registry emptied inside the training process, in which every momentum buffer is None and the losses differ. This shows that each style really unproxies sgd and that the registry entry is what restores momentum.

It runs in two configurations: --modules-to-instr torch.nn torch.optim, and the default instrumentation (skipped when torch is built with CUDA but no driver is present; see limitations).

Fails before, passes after:

test main (7a62cbb) PR head before this change (d06cc5f) this change
copy-semantics unit tests (2) pass fail pass
SGD.step with unproxied sgd fail (buffers None) pass pass
collector, -t torch.nn torch.optim, proxy fail (losses differ from step 3, all 4 buffers None) fail (state_dict() KeyError) pass
collector, -t torch.nn torch.optim, subclass fail (same as proxy) pass pass
collector, default instrumentation, proxy / subclass (GPU) fail / fail not run pass / pass

Environments:

  • Linux, CPU only (Python 3.11.18, torch 2.13.0+cu130 without a GPU, pandas 3.0.5, numpy 2.5.3). Full suite on this branch: 419 passed, 5 skipped, 6 failed. On main: 393 passed, 4 skipped, the same 6 failed (test_display_names 1, test_loop_injection 1, test_time_range_index 4), so they predate this change.
  • Windows 11, RTX 3050 Laptop GPU (Python 3.11.16, torch 2.13.0+cu126): the new test file passes 27 of 27 with nothing skipped. This run needed a local workaround for the Windows bug below.
  • pre-commit run --files on all changed files (ruff v0.3.3, mypy v1.9.0, black 24.3.0, isort 5.10.1) passes. mypy traincheck --ignore-missing-imports (the CI command) is clean on main and on this branch. The new module is also clean with --check-untyped-defs --disallow-untyped-defs --disallow-any-generics --warn-return-any --strict-equality.

Limitations

  • The registry covers torch.optim.sgd.sgd only. To check whether anything else needs an entry, I took the 184 functions the auto observer wraps with unproxying (depth 3 in nn_func_level.log and optim_func_level.log) and scanned the torch 2.13 sources of torch.optim and torch.nn, private helpers included, for assignments into a slot of a list parameter and for list-mutating calls on parameters. The only hits whose callers read the list afterwards are sgd's three implementations, all writing momentum_buffer_list, which they receive from the registered sgd. The other hits write into tensors or dicts (not copied by unproxying) or swap in local views (_view_as_real, Adam's complex-parameter path) that the caller does not read. The scan does not follow aliasing or code outside those two packages, and 5 nested closures could not be resolved.
  • Proxy.__torch_function__ still unproxies without consulting the registry. It handles PyTorch's overridable operators, and functional sgd never dispatches through it. Looking up an API name there would add work to every operation on a proxy.
  • A registered list that is also reachable through another argument is only caught when a replaced slot was changed through that other reference; an alias that the callee only reads is not detected. Unproxying on main already gives the callee a separate copy in that case.
  • Registered lists must keep their length.
  • Seen while testing, not changed here: in subclass style the collector logs that it overrides observe_then_unproxy to False, but the generated script reads the runtime default (True), so the observer still unproxies. That is why subclass style lost momentum too.
  • Separate from this PR: with the default instrumentation on a CUDA-built torch and no NVIDIA driver, the collector crashes while instrumenting CUDA state (torch.backends.cuda.cufft_plan_cache triggers lazy CUDA initialisation). The default-instrumentation test skips that case.
  • Separate from this PR: on Windows every collector run fails with SyntaxError, because source_file.py writes the output directory into the generated script unescaped (os.environ['TRAINCHECK_OUTPUT_DIR'] = "{output_dir}", so C:\Users becomes a \U escape). The GPU run above used {output_dir!r} locally; that change is not part of this PR.

Modified unproxy_arg function to unproxy list elements in place, preserving changes made by callee functions.
@Essoz

Essoz commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Thanks for tracking this down, @hersh11. Copying momentum_buffer_list does lose SGD’s writes. I reproduced a second issue with the current fix in proxy mode on PyTorch 2.13.0 CPU: unwrapping params in place makes SGD.step() read state under the proxy parameter and write it under the underlying tensor. The optimizer ended up with eight state entries for four parameters, and momentum still didn’t carry over between steps.

Could we keep a small TrainCheck registry of which API arguments need list writeback, starting with torch.optim.sgd.sgd’s momentum_buffer_list? For a fixed-length list marked in that registry, unwrap into a copy and write back only the slots the callee replaces, including None becoming a tensor. Leave ordinary input lists and existing proxies alone, and share the writeback logic with any future API that needs it.

For the regression test, could you run the actual collector in both proxy and subclass modes and compare several steps against an uninstrumented run? Matching losses and momentum buffers, checking that the optimizer has exactly one state entry per parameter, and saving and restoring the optimizer state would catch the regression that the wrapped-SGD test misses.

torch_proxy.py passed tokenize.__dict__.get("_tokenize") straight to
unproxy_func, so a Python without the private helper would get a wrapper
around None. The helper exists on Python 3.11, 3.12 and 3.13, so behaviour
there is unchanged. This also lets unproxy_func take a typed callable.
…OrderLab#176)

Unproxying lists in place fixed SGD momentum but also replaced the proxies
in the caller's params list, so optimizer.state was keyed by the underlying
tensors in proxy mode. unproxy_arg copies lists again, and a registry of
(API, list parameter) pairs, starting with torch.optim.sgd.sgd and
momentum_buffer_list, names the arguments whose replaced slots must reach
the caller.

For a registered argument, the callee still receives the unproxied copy.
Afterwards every slot it replaced, compared by identity, is written into
the caller's list, also when the callee raises; other slots, including
proxies, are left alone. A length change, the same list passed to two
registered parameters, a replaced slot that was also changed through
another reference, or a registry entry that does not match the function's
signature raise ListWritebackError instead of losing or overwriting writes.

unproxy_func (used by the auto observer), the unproxy branch of
function_wrapper and the dump-disabled wrapper share the helpers.
Unregistered functions keep their existing call paths, and registry
mismatches fail when wrapping or are recorded as the call's exception.

The tests replace the in-place ones. An end-to-end test runs the collector
in proxy and subclass modes against plain training and compares losses,
momentum buffers, parameters, the optimizer state entries and a state_dict
round trip, with a control run that empties the registry and must lose
momentum.
@hersh11 hersh11 changed the title Unproxy list arguments in place so callees can write results back (fixes #176) Write back registered list slots after unproxying (fixes #176) Nov 28, 2026
@hersh11

hersh11 commented Nov 28, 2026

Copy link
Copy Markdown
Author

Thanks for the careful review, and for running proxy mode on 2.13. You were right about the state keying; my wrapped-sgd test could not have caught it, because it never put a proxy in the caller's params list.

I've reworked the PR along the lines you suggested and rewritten the description with the details. In short:

  • unproxy_arg copies lists again, as on main.
  • A new list_writeback.py holds the registry, starting with torch.optim.sgd.sgd and momentum_buffer_list. The callee gets the unproxied copy; afterwards only the slots it replaced (by identity, so None becoming a tensor counts) are written into the caller's list, also when the callee raises. Proxies the callee didn't replace stay where they are.
  • Anything the write-back cannot do faithfully raises ListWritebackError rather than dropping or overwriting writes: a length change, the same list passed to two registered parameters, a replaced slot that was also changed through another reference, or a registry entry that doesn't match the installed signature (caught when wrapping).
  • unproxy_func, the tracer's function_wrapper and the dump-disabled path share the same helpers.
  • The new end-to-end test runs the collector in proxy and subclass modes against an uninstrumented run. It compares losses, momentum buffers and parameters over four steps, checks that there is exactly one state entry per parameter, and saves and restores state_dict(). It fails on main in both modes and on the previous head of this branch in proxy mode, and passes now, also with the default instrumentation on a GPU. A control run with the registry emptied inside the training process loses momentum in both modes, so the test cannot pass just because sgd was never unproxied.

While testing I noticed a few things outside this PR, listed under limitations in the description: subclass mode logs that it turns observe_then_unproxy off, but the generated script still uses the default (which is why subclass mode lost momentum as well); the default instrumentation crashes on a CUDA build of torch without a driver; and on Windows the generated script writes the output path unescaped, so every run fails with a SyntaxError. I'm happy to open separate issues for any of them if that's useful.

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.

Model tracking (proxy, and subclass in 0.2.0) silently turns off SGD momentum: unproxy_arg copies momentum_buffer_list

2 participants