Repository navigation
Conversation
Modified unproxy_arg function to unproxy list elements in place, preserving changes made by callee functions.
|
Thanks for tracking this down, @hersh11. Copying Could we keep a small TrainCheck registry of which API arguments need list writeback, starting with 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.
|
Thanks for the careful review, and for running proxy mode on 2.13. You were right about the state keying; my wrapped- I've reworked the PR along the lines you suggested and rewritten the description with the details. In short:
While testing I noticed a few things outside this PR, listed under limitations in the description: subclass mode logs that it turns |
Fixes #176.
Problem
unproxy_argbuilds a new list for every list argument. The auto observer wrapstorch.optim.sgd.sgdwith unproxying (in both proxy and subclass model-tracker styles), andsgdreturns its newly created momentum buffers by storing them intomomentum_buffer_list[i];SGD.stepthen reads them back from its own list. Those writes went into the copy, so every buffer stayedNoneand 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
paramslist, sooptimizer.stategets keyed by the underlying tensors (8 entries for 4 parameters in proxy mode, andoptimizer.state_dict()raisesKeyError).Approach
unproxy_argcopies every list again, as onmain. Callers' lists keep their proxies.traincheck/instrumentor/proxy_wrapper/list_writeback.pyholds a registry,LIST_WRITEBACK_ARGUMENTS, mapping an API name (astypenameproduces it) to the names of its fixed-length list parameters whose replaced slots must reach the caller. It starts withtorch.optim.sgd.sgd: {"momentum_buffer_list"}.Nonebecoming 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.ListWritebackErrorinstead of losing or overwriting writes silently:ListWritebackErroris raisedfromthe original exception.proxy_basics.unproxy_func, used by the auto observer (which passes its precomputed API name) and bytorch_proxy.py(where the name is derived withtypename). Registered parameters are resolved when wrapping.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 asFUNC_CALL_POST_EXCEPTIONlike any other.core_wrapper_proxy_list_writebackchosen when wrapping, so unregistered functions keep the existingcore_wrapper_proxy.unproxy_funcis now annotated, and mypy then flagstorch_proxy.pypassingtokenize.__dict__.get("_tokenize")(Any | None)._tokenizeis 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
mainapart from one dict lookup.unproxy_funcon every call, so there it is per call, andfunction_wrapperdoes it per call in its unproxy branch. Registered functions also pay aninspect.signaturewhen wrapping, or per call infunction_wrapper, whichsgddoes 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) replacestests/test_unproxy_list_inplace.py:sgdcalled with proxied arguments;SGD.stepwith an unproxiedsgdmatches plainSGD.step;tracer.function_wrapper(normal, raising, unregistered, and a registry mismatch recorded asFUNC_CALL_POST_EXCEPTION), the dump-disabled wrapper (registered, unregistered), andtracer.wrapperrejecting a mismatch when wrapping.End to end, as requested in review:
tests/fixtures/sgd_momentum_probe.pytrains a small two-layer model for 4 SGD steps with momentum. It records the losses, momentum buffers and parameters (asfloat.hex), the number of optimizer state entries and whether every key is one of the model's parameters. It then savesoptimizer.state_dict(), loads it into a new optimizer and takes one more step. The test runs this plainly and underpython -m traincheck.collect_tracein proxy and subclass styles, and requires:PYTHONPATH, so an installed copy elsewhere would otherwise be tested silently);torch.optim.sgd.sgdobservations;Noneand the losses differ. This shows that each style really unproxiessgdand 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:
Environments:
main: 393 passed, 4 skipped, the same 6 failed (test_display_names1,test_loop_injection1,test_time_range_index4), so they predate this change.pre-commit run --fileson 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 onmainand 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
torch.optim.sgd.sgdonly. To check whether anything else needs an entry, I took the 184 functions the auto observer wraps with unproxying (depth 3 innn_func_level.logandoptim_func_level.log) and scanned the torch 2.13 sources oftorch.optimandtorch.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 aresgd's three implementations, all writingmomentum_buffer_list, which they receive from the registeredsgd. 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 functionalsgdnever dispatches through it. Looking up an API name there would add work to every operation on a proxy.mainalready gives the callee a separate copy in that case.observe_then_unproxytoFalse, but the generated script reads the runtime default (True), so the observer still unproxies. That is why subclass style lost momentum too.torch.backends.cuda.cufft_plan_cachetriggers lazy CUDA initialisation). The default-instrumentation test skips that case.SyntaxError, becausesource_file.pywrites the output directory into the generated script unescaped (os.environ['TRAINCHECK_OUTPUT_DIR'] = "{output_dir}", soC:\Usersbecomes a\Uescape). The GPU run above used{output_dir!r}locally; that change is not part of this PR.