From 91aed1870f42e80a41d74df8637de10d782fcbb1 Mon Sep 17 00:00:00 2001 From: Harsh Narain <72140506+hersh11@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:59:10 +0530 Subject: [PATCH 1/5] Unproxy list arguments in place (fixes #176) Modified unproxy_arg function to unproxy list elements in place, preserving changes made by callee functions. --- traincheck/instrumentor/proxy_wrapper/proxy_basics.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/traincheck/instrumentor/proxy_wrapper/proxy_basics.py b/traincheck/instrumentor/proxy_wrapper/proxy_basics.py index a1cc1aab..cd23d665 100644 --- a/traincheck/instrumentor/proxy_wrapper/proxy_basics.py +++ b/traincheck/instrumentor/proxy_wrapper/proxy_basics.py @@ -73,7 +73,13 @@ def unproxy_arg(arg, inspect_torch_module=False): if is_proxied(arg): return unproxy_arg(arg._obj, inspect_torch_module) elif type(arg) in [list]: - return [unproxy_arg(element, inspect_torch_module) for element in arg] + # Unproxy in place. Callees such as torch.optim's functional sgd write + # results back into list arguments (e.g. momentum_buffer_list), and the + # caller reads them from the same list afterwards, so a copy would + # silently drop those writes (issue #176). + for index, element in enumerate(arg): + arg[index] = unproxy_arg(element, inspect_torch_module) + return arg elif type(arg) in [tuple]: return tuple(unproxy_arg(element, inspect_torch_module) for element in arg) # if it is a torch module, unproxy all its named children From 6461e91aba48d02da35be24c374d5bbe16e22b50 Mon Sep 17 00:00:00 2001 From: Harsh Narain <72140506+hersh11@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:01:00 +0530 Subject: [PATCH 2/5] Add regression tests for #176 --- tests/test_unproxy_list_inplace.py | 70 ++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 tests/test_unproxy_list_inplace.py diff --git a/tests/test_unproxy_list_inplace.py b/tests/test_unproxy_list_inplace.py new file mode 100644 index 00000000..8df04b57 --- /dev/null +++ b/tests/test_unproxy_list_inplace.py @@ -0,0 +1,70 @@ +"""Regression tests for issue #176: unproxy_arg must not copy list arguments. + +torch.optim.SGD.step builds ``momentum_buffer_list``, passes it to the functional +``sgd``, which stores newly created buffers into that list, and then copies them +into ``optimizer.state``. When a wrapper unproxied the arguments by building a +new list, those writes went into the copy and SGD momentum was silently reset +every step. +""" + +import importlib +import os +import sys +import unittest +from unittest.mock import patch + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +import torch + +from traincheck.instrumentor.proxy_wrapper.proxy_basics import ( + unproxy_arg, + unproxy_args_kwargs, + unproxy_func, +) + + +class TestUnproxyListInPlace(unittest.TestCase): + def test_list_identity_is_preserved(self): + values = [torch.zeros(2), None] + self.assertIs(unproxy_arg(values), values) + + def test_nested_list_identity_is_preserved(self): + inner = [None] + outer = [inner] + self.assertIs(unproxy_arg(outer)[0], inner) + + def test_positional_list_write_back_reaches_caller(self): + buffers = [None, None] + args, _ = unproxy_args_kwargs((buffers,), {}) + args[0][1] = torch.ones(1) + self.assertIsNotNone(buffers[1]) + + def test_keyword_list_write_back_reaches_caller(self): + buffers = [None] + _, kwargs = unproxy_args_kwargs((), {"momentum_buffer_list": buffers}) + kwargs["momentum_buffer_list"][0] = torch.ones(1) + self.assertIsNotNone(buffers[0]) + + def test_tuples_are_still_unwrapped(self): + values = (torch.zeros(1), [None]) + out = unproxy_arg(values) + self.assertIsInstance(out, tuple) + self.assertIs(out[1], values[1]) + + def test_sgd_momentum_survives_a_wrapped_functional_sgd(self): + torch.manual_seed(0) + model = torch.nn.Linear(3, 1) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9) + sgd_module = importlib.import_module("torch.optim.sgd") + with patch.object(sgd_module, "sgd", unproxy_func(sgd_module.sgd)): + for _ in range(2): + optimizer.zero_grad() + model(torch.randn(4, 3)).sum().backward() + optimizer.step() + for param in model.parameters(): + self.assertIsNotNone(optimizer.state[param].get("momentum_buffer")) + + +if __name__ == "__main__": + unittest.main() From d06cc5f426eeaba44f3fd6eece1411c2a23d2036 Mon Sep 17 00:00:00 2001 From: Harsh Narain <72140506+hersh11@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:12:32 +0530 Subject: [PATCH 3/5] Fix indentation --- traincheck/instrumentor/proxy_wrapper/proxy_basics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/traincheck/instrumentor/proxy_wrapper/proxy_basics.py b/traincheck/instrumentor/proxy_wrapper/proxy_basics.py index cd23d665..d765dd76 100644 --- a/traincheck/instrumentor/proxy_wrapper/proxy_basics.py +++ b/traincheck/instrumentor/proxy_wrapper/proxy_basics.py @@ -78,7 +78,7 @@ def unproxy_arg(arg, inspect_torch_module=False): # caller reads them from the same list afterwards, so a copy would # silently drop those writes (issue #176). for index, element in enumerate(arg): - arg[index] = unproxy_arg(element, inspect_torch_module) + arg[index] = unproxy_arg(element, inspect_torch_module) return arg elif type(arg) in [tuple]: return tuple(unproxy_arg(element, inspect_torch_module) for element in arg) From 35ea1cf1b66660d4e1a75a4f10d53229f5c14945 Mon Sep 17 00:00:00 2001 From: Harsh Narain <72140506+hersh11@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:14:53 +0530 Subject: [PATCH 4/5] Wrap tokenize._tokenize only when it exists 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. --- traincheck/instrumentor/proxy_wrapper/torch_proxy.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/traincheck/instrumentor/proxy_wrapper/torch_proxy.py b/traincheck/instrumentor/proxy_wrapper/torch_proxy.py index 241c6800..3dcdaa3b 100644 --- a/traincheck/instrumentor/proxy_wrapper/torch_proxy.py +++ b/traincheck/instrumentor/proxy_wrapper/torch_proxy.py @@ -16,7 +16,10 @@ setattr(ProcessGroup, "allreduce", unproxy_func(ProcessGroup.__dict__.get("allreduce"))) setattr(ProcessGroup, "allgather", unproxy_func(ProcessGroup.__dict__.get("allgather"))) -setattr(tokenize, "_tokenize", unproxy_func(tokenize.__dict__.get("_tokenize"))) +# A private helper: present in every supported Python, but nothing to wrap if absent. +_original_tokenize = tokenize.__dict__.get("_tokenize") +if _original_tokenize is not None: + setattr(tokenize, "_tokenize", unproxy_func(_original_tokenize)) if "BF16_Optimizer" in globals(): BF16_Optimizer._flatten_dense_tensors_aligned = unproxy_func( BF16_Optimizer.__dict__.get("_flatten_dense_tensors_aligned") From 07cb1952f189e2a48e74da62c5784c6ded024838 Mon Sep 17 00:00:00 2001 From: Harsh Narain <72140506+hersh11@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:14:54 +0530 Subject: [PATCH 5/5] Write back registered list slots instead of unproxying lists in place (#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. --- tests/fixtures/sgd_momentum_probe.py | 90 +++ tests/test_unproxy_list_inplace.py | 70 --- tests/test_unproxy_list_writeback.py | 545 ++++++++++++++++++ .../proxy_wrapper/list_writeback.py | 218 +++++++ .../proxy_wrapper/proxy_basics.py | 51 +- .../proxy_wrapper/proxy_observer.py | 4 +- traincheck/instrumentor/tracer.py | 98 +++- 7 files changed, 992 insertions(+), 84 deletions(-) create mode 100644 tests/fixtures/sgd_momentum_probe.py delete mode 100644 tests/test_unproxy_list_inplace.py create mode 100644 tests/test_unproxy_list_writeback.py create mode 100644 traincheck/instrumentor/proxy_wrapper/list_writeback.py diff --git a/tests/fixtures/sgd_momentum_probe.py b/tests/fixtures/sgd_momentum_probe.py new file mode 100644 index 00000000..f4dcc8de --- /dev/null +++ b/tests/fixtures/sgd_momentum_probe.py @@ -0,0 +1,90 @@ +"""Train a small model with SGD momentum and record the optimizer state (issue #176). + +Run plainly and under ``traincheck.collect_trace``; the two JSON reports must be +identical. Floats are recorded with ``float.hex`` so that equality is exact. +The report path is read from the ``TRAINCHECK_SGD_PROBE_OUT`` environment variable. +``traincheck_file`` names the traincheck installation that the run imported. +With ``TRAINCHECK_SGD_PROBE_WITHOUT_WRITEBACK=1`` the list write-back registry +is emptied first, as a control. +""" + +import io +import json +import os +import sys + +import torch + + +def hex_values(tensor: torch.Tensor) -> list[str]: + return [float(value).hex() for value in tensor.detach().reshape(-1).tolist()] + + +def main() -> None: + if os.environ.get("TRAINCHECK_SGD_PROBE_WITHOUT_WRITEBACK") == "1": + # Control run under the collector: empty the list write-back registry + # so that unproxied calls fall back to plain copying. + from traincheck.instrumentor.proxy_wrapper import list_writeback + + dict.clear(list_writeback.LIST_WRITEBACK_ARGUMENTS) + torch.set_num_threads(1) + torch.manual_seed(0) + model = torch.nn.Sequential( + torch.nn.Linear(4, 3), torch.nn.Tanh(), torch.nn.Linear(3, 1) + ) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9) + inputs = torch.randn(8, 4) + targets = torch.randn(8, 1) + + losses = [] + for _ in range(4): + optimizer.zero_grad() + loss = torch.nn.functional.mse_loss(model(inputs), targets) + loss.backward() + optimizer.step() + losses.append(float(loss.item()).hex()) + + parameters = list(model.parameters()) + buffers: list[list[str] | None] = [] + for parameter in parameters: + state = optimizer.state.get(parameter) + buffer = None if state is None else state.get("momentum_buffer") + buffers.append(None if buffer is None else hex_values(buffer)) + + report: dict[str, object] = { + "losses": losses, + "parameter_count": len(parameters), + "state_count": len(optimizer.state), + "state_keys_are_parameters": all( + any(key is parameter for parameter in parameters) for key in optimizer.state + ), + "momentum_buffers": buffers, + "parameters": [hex_values(parameter) for parameter in parameters], + } + + checkpoint = io.BytesIO() + torch.save(optimizer.state_dict(), checkpoint) + checkpoint.seek(0) + restored = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9) + restored.load_state_dict(torch.load(checkpoint)) + restored.zero_grad() + loss = torch.nn.functional.mse_loss(model(inputs), targets) + loss.backward() + restored.step() + report["restored_loss"] = float(loss.item()).hex() + report["restored_state_count"] = len(restored.state) + report["restored_parameters"] = [ + hex_values(parameter) for parameter in model.parameters() + ] + + # Under the collector, the instrumented copy of this script imports + # traincheck; record which installation it used. + traincheck = sys.modules.get("traincheck") + report["traincheck_file"] = None if traincheck is None else traincheck.__file__ + + with open(os.environ["TRAINCHECK_SGD_PROBE_OUT"], "w", encoding="utf-8") as file: + json.dump(report, file) + + +if __name__ == "__main__": + main() diff --git a/tests/test_unproxy_list_inplace.py b/tests/test_unproxy_list_inplace.py deleted file mode 100644 index 8df04b57..00000000 --- a/tests/test_unproxy_list_inplace.py +++ /dev/null @@ -1,70 +0,0 @@ -"""Regression tests for issue #176: unproxy_arg must not copy list arguments. - -torch.optim.SGD.step builds ``momentum_buffer_list``, passes it to the functional -``sgd``, which stores newly created buffers into that list, and then copies them -into ``optimizer.state``. When a wrapper unproxied the arguments by building a -new list, those writes went into the copy and SGD momentum was silently reset -every step. -""" - -import importlib -import os -import sys -import unittest -from unittest.mock import patch - -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) - -import torch - -from traincheck.instrumentor.proxy_wrapper.proxy_basics import ( - unproxy_arg, - unproxy_args_kwargs, - unproxy_func, -) - - -class TestUnproxyListInPlace(unittest.TestCase): - def test_list_identity_is_preserved(self): - values = [torch.zeros(2), None] - self.assertIs(unproxy_arg(values), values) - - def test_nested_list_identity_is_preserved(self): - inner = [None] - outer = [inner] - self.assertIs(unproxy_arg(outer)[0], inner) - - def test_positional_list_write_back_reaches_caller(self): - buffers = [None, None] - args, _ = unproxy_args_kwargs((buffers,), {}) - args[0][1] = torch.ones(1) - self.assertIsNotNone(buffers[1]) - - def test_keyword_list_write_back_reaches_caller(self): - buffers = [None] - _, kwargs = unproxy_args_kwargs((), {"momentum_buffer_list": buffers}) - kwargs["momentum_buffer_list"][0] = torch.ones(1) - self.assertIsNotNone(buffers[0]) - - def test_tuples_are_still_unwrapped(self): - values = (torch.zeros(1), [None]) - out = unproxy_arg(values) - self.assertIsInstance(out, tuple) - self.assertIs(out[1], values[1]) - - def test_sgd_momentum_survives_a_wrapped_functional_sgd(self): - torch.manual_seed(0) - model = torch.nn.Linear(3, 1) - optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9) - sgd_module = importlib.import_module("torch.optim.sgd") - with patch.object(sgd_module, "sgd", unproxy_func(sgd_module.sgd)): - for _ in range(2): - optimizer.zero_grad() - model(torch.randn(4, 3)).sum().backward() - optimizer.step() - for param in model.parameters(): - self.assertIsNotNone(optimizer.state[param].get("momentum_buffer")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_unproxy_list_writeback.py b/tests/test_unproxy_list_writeback.py new file mode 100644 index 00000000..b6fab7d9 --- /dev/null +++ b/tests/test_unproxy_list_writeback.py @@ -0,0 +1,545 @@ +"""Regression tests for issue #176: list arguments under unproxying. + +``torch.optim.SGD.step`` builds ``momentum_buffer_list``, passes it to the +functional ``sgd``, which stores each newly created buffer into that list, and +then copies the buffers into ``optimizer.state``. Unproxying copied the list, so +the writes went into the copy and momentum was silently reset every step. +Unproxying in place instead also replaced the proxies in the caller's ``params`` +list, so ``optimizer.state`` became keyed by unproxied tensors. + +The contract tested here: unproxying copies every list, and only list slots of +registered APIs that the callee replaced are written back to the caller. +""" + +import importlib +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from collections.abc import Callable +from pathlib import Path +from unittest.mock import patch + +import torch + +from traincheck.instrumentor import tracer +from traincheck.instrumentor.proxy_wrapper import list_writeback +from traincheck.instrumentor.proxy_wrapper.list_writeback import ListWritebackError +from traincheck.instrumentor.proxy_wrapper.proxy_basics import ( + is_proxied, + unproxy_arg, + unproxy_func, +) +from traincheck.utils import typename + +ROOT = Path(__file__).resolve().parents[1] +PROBE = Path(__file__).parent / "fixtures" / "sgd_momentum_probe.py" + + +class MarkerProxy: + """Carries the attributes ``is_proxied`` and ``unproxy_arg`` rely on.""" + + def __init__(self, obj: object) -> None: + self.__dict__["is_traincheck_proxied_obj"] = True + self.__dict__["_obj"] = obj + + +def assert_no_proxies(*values: object) -> None: + for value in values: + if type(value) in (list, tuple): + assert_no_proxies(*value) # type: ignore[arg-type] + elif is_proxied(value): + raise AssertionError(f"callee received a proxy: {value!r}") + + +def fill_missing(params: list[object], buffers: list[object]) -> int: + assert_no_proxies(params, buffers) + for index, buffer in enumerate(buffers): + if buffer is None: + buffers[index] = torch.full((1,), float(index)) + return len(params) + + +def fill_keyword_only(params: list[object], *, buffers: list[object]) -> None: + buffers[0] = torch.zeros(1) + + +def fill_optional(params: list[object], buffers: list[object] | None = None) -> None: + if buffers is not None: + buffers[0] = torch.zeros(1) + + +def fill_variadic(params: list[object], *buffers: object) -> None: + pass + + +def grow(params: list[object], buffers: list[object]) -> None: + buffers.append(torch.zeros(1)) + + +def grow_then_raise(params: list[object], buffers: list[object]) -> None: + buffers.append(torch.zeros(1)) + raise ValueError("callee failed") + + +CALLS: list[str] = [] + + +def fill_two(first: list[object], second: list[object]) -> None: + CALLS.append("fill_two") + first[0] = torch.zeros(1) + + +def fill_first_grow_second(first: list[object], second: list[object]) -> None: + first[0] = torch.zeros(1) + second.append(torch.zeros(1)) + + +def fill_and_alias( + params: list[object], buffers: list[object], box: dict[str, list[object]] +) -> None: + buffers[0] = torch.zeros(1) + box["buffers"][0] = torch.ones(1) + + +def fill_both_references( + params: list[object], buffers: list[object], box: dict[str, list[object]] +) -> None: + value = torch.zeros(1) + buffers[0] = value + box["buffers"][0] = value + + +class CalleeError(Exception): + pass + + +def fill_then_raise(params: list[object], buffers: list[object]) -> None: + buffers[0] = torch.zeros(1) + raise CalleeError("callee failed after replacing a slot") + + +class WritebackTestCase(unittest.TestCase): + def register(self, function: Callable[..., object], *parameters: str) -> None: + patcher = patch.dict( + list_writeback.LIST_WRITEBACK_ARGUMENTS, # type: ignore[arg-type] + {typename(function): frozenset(parameters)}, + ) + patcher.start() + self.addCleanup(patcher.stop) + + +class UnproxyCopiesListsTests(WritebackTestCase): + def test_list_argument_is_copied_and_caller_keeps_proxies(self) -> None: + tensor = torch.zeros(1) + proxy = MarkerProxy(tensor) + values = [proxy, [MarkerProxy(tensor)]] + unproxied = unproxy_arg(values) + self.assertIsNot(unproxied, values) + self.assertIs(unproxied[0], tensor) + self.assertIs(unproxied[1][0], tensor) + self.assertIs(values[0], proxy) + self.assertTrue(is_proxied(values[1][0])) + + def test_unregistered_api_does_not_write_back(self) -> None: + proxy = MarkerProxy(torch.zeros(1)) + params: list[object] = [proxy] + buffers: list[object] = [None] + unproxy_func(fill_missing)(params, buffers) + self.assertEqual(buffers, [None]) + self.assertIs(params[0], proxy) + + +class RegisteredListWritebackTests(WritebackTestCase): + def setUp(self) -> None: + self.param = MarkerProxy(torch.zeros(1)) + self.kept = MarkerProxy(torch.ones(1)) + self.params: list[object] = [self.param] + self.buffers: list[object] = [None, self.kept] + + def assert_written_back(self) -> None: + self.assertIsInstance(self.buffers[0], torch.Tensor) + self.assertIs(self.buffers[1], self.kept) + self.assertIs(self.params[0], self.param) + + def test_positional_list_slots_are_written_back(self) -> None: + self.register(fill_missing, "buffers") + wrapped = unproxy_func(fill_missing, api_name=typename(fill_missing)) + self.assertEqual(wrapped(self.params, self.buffers), 1) + self.assert_written_back() + + def test_keyword_list_slots_are_written_back(self) -> None: + self.register(fill_missing, "buffers") + unproxy_func(fill_missing)(self.params, buffers=self.buffers) + self.assert_written_back() + + def test_keyword_only_parameter_is_written_back(self) -> None: + self.register(fill_keyword_only, "buffers") + unproxy_func(fill_keyword_only)(self.params, buffers=self.buffers) + self.assert_written_back() + + def test_slots_replaced_before_an_exception_are_written_back(self) -> None: + self.register(fill_then_raise, "buffers") + with self.assertRaises(CalleeError) as raised: + unproxy_func(fill_then_raise)(self.params, self.buffers) + self.assertEqual(str(raised.exception), "callee failed after replacing a slot") + self.assert_written_back() + + def test_length_change_is_an_error(self) -> None: + self.register(grow, "buffers") + with self.assertRaisesRegex(ListWritebackError, "'buffers'"): + unproxy_func(grow)(self.params, self.buffers) + self.assertEqual(self.buffers, [None, self.kept]) + + def test_length_change_during_an_exception_keeps_the_original(self) -> None: + self.register(grow_then_raise, "buffers") + with self.assertRaises(ListWritebackError) as raised: + unproxy_func(grow_then_raise)(self.params, self.buffers) + self.assertIsInstance(raised.exception.__cause__, ValueError) + + def test_unknown_registered_parameter_fails_when_wrapping(self) -> None: + self.register(fill_missing, "momentum_buffer_list") + with self.assertRaisesRegex(ListWritebackError, "no parameter"): + unproxy_func(fill_missing) + + def test_variadic_registered_parameter_fails_when_wrapping(self) -> None: + self.register(fill_variadic, "buffers") + with self.assertRaisesRegex(ListWritebackError, "variadic"): + unproxy_func(fill_variadic) + + def test_same_list_for_two_registered_parameters_is_an_error(self) -> None: + self.register(fill_two, "first", "second") + CALLS.clear() + with self.assertRaisesRegex(ListWritebackError, "same list"): + unproxy_func(fill_two)(self.buffers, self.buffers) + self.assertEqual(CALLS, []) + self.assertEqual(self.buffers, [None, self.kept]) + + def test_failed_write_back_writes_no_slot(self) -> None: + self.register(fill_first_grow_second, "first", "second") + first: list[object] = [None] + with self.assertRaisesRegex(ListWritebackError, "'second'"): + unproxy_func(fill_first_grow_second)(first, [None]) + self.assertEqual(first, [None]) + + def test_slot_changed_through_another_reference_is_an_error(self) -> None: + self.register(fill_and_alias, "buffers") + box = {"buffers": self.buffers} + with self.assertRaisesRegex(ListWritebackError, "another reference"): + unproxy_func(fill_and_alias)(self.params, self.buffers, box) + # The caller's list is as the callee left it through the alias. + written = self.buffers[0] + assert isinstance(written, torch.Tensor) + self.assertTrue(torch.equal(written, torch.ones(1))) + + def test_same_object_through_both_references_is_written_back(self) -> None: + self.register(fill_both_references, "buffers") + box = {"buffers": self.buffers} + unproxy_func(fill_both_references)(self.params, self.buffers, box) + self.assert_written_back() + + def test_registered_argument_that_is_not_a_list_is_unproxied_normally( + self, + ) -> None: + self.register(fill_optional, "buffers") + unproxy_func(fill_optional)(self.params) + tensor = torch.ones(1) + with self.assertRaises(TypeError): + # The callee receives the unproxied tuple and cannot assign into it. + unproxy_func(fill_optional)(self.params, (MarkerProxy(tensor),)) + + +class InstalledTorchTests(unittest.TestCase): + def test_registry_matches_the_installed_library(self) -> None: + for api_name, parameters in list_writeback.LIST_WRITEBACK_ARGUMENTS.items(): + with self.subTest(api_name=api_name): + module_name, attribute = api_name.rsplit(".", 1) + function = getattr(importlib.import_module(module_name), attribute) + self.assertEqual(typename(function), api_name) + positions = list_writeback.list_writeback_positions(function, api_name) + assert positions is not None + self.assertEqual(set(positions), set(parameters)) + + def test_functional_sgd_buffers_reach_the_caller(self) -> None: + sgd = importlib.import_module("torch.optim.sgd").sgd + wrapped = unproxy_func(sgd) + parameter = torch.nn.Parameter(torch.zeros(3)) + gradient = torch.tensor([1.0, 2.0, 3.0]) + parameter_proxy = MarkerProxy(parameter) + params: list[object] = [parameter_proxy] + buffers: list[object] = [None] + options = dict( + weight_decay=0.0, + momentum=0.9, + lr=0.1, + dampening=0.0, + nesterov=False, + maximize=False, + foreach=False, + ) + with torch.no_grad(): + wrapped(params, [MarkerProxy(gradient)], buffers, **options) + first = buffers[0] + assert isinstance(first, torch.Tensor) + self.assertTrue(torch.equal(first, gradient)) + self.assertIs(params[0], parameter_proxy) + + with torch.no_grad(): + wrapped(params, [MarkerProxy(gradient)], buffers, **options) + self.assertIs(buffers[0], first) + self.assertTrue(torch.allclose(first, gradient * 1.9)) + + def test_sgd_momentum_survives_an_unproxied_functional_sgd(self) -> None: + def train(wrap: bool) -> list[torch.Tensor]: + torch.manual_seed(0) + model = torch.nn.Linear(3, 1) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9) + sgd_module = importlib.import_module("torch.optim.sgd") + replacement = unproxy_func(sgd_module.sgd) if wrap else sgd_module.sgd + with patch.object(sgd_module, "sgd", replacement): + for _ in range(3): + optimizer.zero_grad() + model(torch.randn(4, 3)).sum().backward() + optimizer.step() + self.assertEqual(len(optimizer.state), 2) + return [optimizer.state[p]["momentum_buffer"] for p in model.parameters()] + + for wrapped, plain in zip(train(True), train(False)): + self.assertTrue(torch.equal(wrapped, plain)) + + +class TracerWritebackTests(WritebackTestCase): + def setUp(self) -> None: + self.records: list[dict[str, object]] = [] + for patcher in ( + patch.object(tracer.config, "DISABLE_WRAPPER", False), + patch.object(tracer, "dump_trace_API", side_effect=self.records.append), + ): + patcher.start() + self.addCleanup(patcher.stop) + self.param = MarkerProxy(torch.zeros(1)) + self.params: list[object] = [self.param] + self.buffers: list[object] = [None] + + def call_function_wrapper(self, function: Callable[..., object]) -> object: + return tracer.function_wrapper( + function, + typename(function), + False, + False, + False, + False, + None, + False, + None, + False, + None, + True, + False, + None, + self.params, + self.buffers, + ) + + def test_function_wrapper_writes_back_registered_slots(self) -> None: + self.register(fill_missing, "buffers") + self.assertEqual(self.call_function_wrapper(fill_missing), 1) + self.assertIsInstance(self.buffers[0], torch.Tensor) + self.assertIs(self.params[0], self.param) + self.assertEqual(len(self.records), 2) + + def test_function_wrapper_writes_back_before_reraising(self) -> None: + self.register(fill_then_raise, "buffers") + with self.assertRaises(CalleeError): + self.call_function_wrapper(fill_then_raise) + self.assertIsInstance(self.buffers[0], torch.Tensor) + self.assertEqual( + self.records[-1]["exception_msg"], "callee failed after replacing a slot" + ) + + def test_function_wrapper_copies_unregistered_lists(self) -> None: + self.call_function_wrapper(fill_missing) + self.assertEqual(self.buffers, [None]) + self.assertIs(self.params[0], self.param) + + def test_function_wrapper_records_a_registry_mismatch_as_the_exception( + self, + ) -> None: + self.register(fill_missing, "momentum_buffer_list") + with self.assertRaises(ListWritebackError): + self.call_function_wrapper(fill_missing) + self.assertEqual( + [record["type"] for record in self.records], + [ + tracer.TraceLineType.FUNC_CALL_PRE, + tracer.TraceLineType.FUNC_CALL_POST_EXCEPTION, + ], + ) + self.assertEqual(self.buffers, [None]) + + def test_wrapper_rejects_a_registry_mismatch_when_wrapping(self) -> None: + self.register(fill_missing, "momentum_buffer_list") + for disable_dump in (False, True): + with self.subTest(disable_dump=disable_dump): + with patch.object( + tracer, "is_funcs_to_be_unproxied", return_value=True + ): + with self.assertRaisesRegex(ListWritebackError, "no parameter"): + tracer.wrapper( + fill_missing, False, False, False, disable_dump=disable_dump + ) + + def wrap_without_dumping( + self, function: Callable[..., object] + ) -> Callable[..., object]: + with patch.object(tracer, "is_funcs_to_be_unproxied", return_value=True): + return tracer.wrapper(function, False, False, False, disable_dump=True) + + def test_dump_disabled_wrapper_writes_back_registered_slots(self) -> None: + self.register(fill_missing, "buffers") + self.assertEqual( + self.wrap_without_dumping(fill_missing)(self.params, self.buffers), 1 + ) + self.assertIsInstance(self.buffers[0], torch.Tensor) + self.assertIs(self.params[0], self.param) + + def test_dump_disabled_wrapper_copies_unregistered_lists(self) -> None: + self.wrap_without_dumping(fill_missing)(self.params, self.buffers) + self.assertEqual(self.buffers, [None]) + self.assertEqual(self.records, []) + + +def needs_cuda_probe_workaround() -> bool: + """Default instrumentation probes CUDA state, which fails without a driver.""" + return torch.backends.cuda.is_built() and not torch.cuda.is_available() + + +class CollectedTrainingMatchesPlainTraining(unittest.TestCase): + """SGD momentum, optimizer state and checkpoints under model tracking.""" + + def run_probe( + self, + directory: Path, + collector_arguments: list[str] | None, + without_writeback: bool = False, + ) -> dict[str, object]: + # The runner writes a copy of the script next to the original and sets + # PYTHONPATH to that directory, so run a copy outside the source tree. + script = directory / PROBE.name + shutil.copyfile(PROBE, script) + report = directory / "report.json" + env = { + **os.environ, + "PYTHONPATH": str(ROOT), + "TRAINCHECK_SGD_PROBE_OUT": str(report), + } + if without_writeback: + env["TRAINCHECK_SGD_PROBE_WITHOUT_WRITEBACK"] = "1" + if collector_arguments is None: + command = [sys.executable, str(script)] + else: + command = [ + sys.executable, + "-m", + "traincheck.collect_trace", + "--pyscript", + str(script), + "--output-dir", + str(directory / "trace"), + *collector_arguments, + ] + result = subprocess.run( + command, + cwd=directory, + env=env, + text=True, + capture_output=True, + timeout=600, + check=False, + ) + output = result.stdout + result.stderr + program_output = directory / "trace" / "program_output.txt" + if program_output.exists(): + output += program_output.read_text(encoding="utf-8", errors="replace") + self.assertEqual(result.returncode, 0, output[-4000:]) + self.assertTrue(report.exists(), output[-4000:]) + loaded = json.loads(report.read_text(encoding="utf-8")) + assert isinstance(loaded, dict) + return loaded + + def sgd_observations(self, trace_directory: Path) -> int: + pattern = re.compile(r'"dump_loc":\s*"torch\.optim\.sgd\.sgd"') + return sum( + len(pattern.findall(path.read_text(encoding="utf-8", errors="replace"))) + for path in trace_directory.iterdir() + if path.suffix in (".json", ".log") + ) + + def check(self, extra_arguments: list[str]) -> None: + with tempfile.TemporaryDirectory() as plain_directory: + plain = self.run_probe(Path(plain_directory), None) + self.assertIsNone(plain.pop("traincheck_file")) + self.assertEqual(plain["state_count"], plain["parameter_count"]) + self.assertNotIn(None, plain["momentum_buffers"]) # type: ignore[operator] + for style in ("proxy", "subclass"): + with self.subTest(style=style), tempfile.TemporaryDirectory() as directory: + collected = self.run_probe( + Path(directory), + [ + "--models-to-track", + "model", + "--model-tracker-style", + style, + *extra_arguments, + ], + ) + # The training process must have used this checkout, which the + # runner's PYTHONPATH does not ensure; and the observer around + # functional sgd must have run, or the comparison would not + # exercise the unproxying path at all. + traincheck_file = collected.pop("traincheck_file") + assert isinstance(traincheck_file, str) + self.assertTrue( + Path(traincheck_file).resolve().is_relative_to(ROOT), + f"{traincheck_file} is not in {ROOT}; install this checkout", + ) + self.assertGreater(self.sgd_observations(Path(directory) / "trace"), 0) + self.assertEqual(collected, plain) + # Control: with the registry emptied inside the training process the + # same run must lose momentum, which shows that this style unproxies + # functional sgd and that the registry entry is what restores it. + with self.subTest(style=style, control="without write-back"): + with tempfile.TemporaryDirectory() as directory: + control = self.run_probe( + Path(directory), + [ + "--models-to-track", + "model", + "--model-tracker-style", + style, + *extra_arguments, + ], + without_writeback=True, + ) + self.assertEqual( + control["momentum_buffers"], [None] * len(plain["parameters"]) # type: ignore[arg-type] + ) + self.assertNotEqual(control["losses"], plain["losses"]) + + def test_model_tracking_without_api_instrumentation(self) -> None: + self.check(["--modules-to-instr", "torch.nn", "torch.optim"]) + + @unittest.skipIf( + needs_cuda_probe_workaround(), + "default instrumentation initializes CUDA, which needs a driver", + ) + def test_model_tracking_with_default_instrumentation(self) -> None: + self.check([]) + + +if __name__ == "__main__": + unittest.main() diff --git a/traincheck/instrumentor/proxy_wrapper/list_writeback.py b/traincheck/instrumentor/proxy_wrapper/list_writeback.py new file mode 100644 index 00000000..465dade8 --- /dev/null +++ b/traincheck/instrumentor/proxy_wrapper/list_writeback.py @@ -0,0 +1,218 @@ +"""Write back list slots that an unproxied callee replaces (issue #176). + +Unproxying copies list arguments, so the caller's lists keep their own elements: +an optimizer's ``params`` list must keep the proxied parameters, because +``optimizer.state`` is keyed by them. A few APIs instead return results by +replacing slots of a list argument. ``torch.optim.sgd.sgd`` stores each newly +created momentum buffer into ``momentum_buffer_list[i]``, and ``SGD.step`` +reads the buffers back from its own list after the call. With the copy, those +writes were lost and SGD momentum was silently reset every step. + +The registry below names such arguments. For a registered argument passed as a +list, the callee receives the unproxied copy as before; after the call, every +slot the callee replaced (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 untouched. The write-back also runs +when the callee raises, so the caller sees the same partial updates it would +see without instrumentation. Registered lists must keep their length, must not +be passed to two registered parameters at once, and must not have a replaced +slot changed through another reference during the call; each of these is +reported as an error instead of losing or overwriting writes silently. +""" + +import inspect +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass + +# Fully qualified API name, as produced by ``traincheck.utils.typename``, mapped +# to the names of its fixed-length list parameters whose replaced slots must be +# written back to the caller. +LIST_WRITEBACK_ARGUMENTS: Mapping[str, frozenset[str]] = { + "torch.optim.sgd.sgd": frozenset({"momentum_buffer_list"}), +} + + +class ListWritebackError(RuntimeError): + """A registered list argument cannot be written back as registered.""" + + +# Registered parameter name mapped to its positional index, or ``None`` when it +# can only be passed by keyword. +ListWritebackPositions = Mapping[str, int | None] + + +@dataclass(frozen=True) +class PendingListWriteback: + """One registered list argument of one call, paired with the copy the callee gets.""" + + api_name: str + parameter: str + caller_list: list[object] + caller_before: tuple[object, ...] + callee_list: list[object] + passed: tuple[object, ...] + + +def has_list_writeback(api_name: str) -> bool: + """Whether calls to ``api_name`` have registered list arguments.""" + return api_name in LIST_WRITEBACK_ARGUMENTS + + +def list_writeback_positions( + function: Callable[..., object], api_name: str +) -> ListWritebackPositions | None: + """Resolve the registered parameters of ``function``; ``None`` if it has none. + + Call this once when wrapping ``function``. Raises ``ListWritebackError`` + when the registry and the installed library disagree, so a renamed + parameter cannot silently disable the write-back. + """ + parameters = LIST_WRITEBACK_ARGUMENTS.get(api_name) + if parameters is None: + return None + return _parameter_positions(function, api_name, parameters) + + +def _parameter_positions( + function: Callable[..., object], api_name: str, parameters: frozenset[str] +) -> dict[str, int | None]: + """Positional index of each registered parameter, ``None`` if keyword-only.""" + try: + signature = inspect.signature(function) + except (TypeError, ValueError) as error: + raise ListWritebackError( + f"{api_name} has registered list arguments but no inspectable signature" + ) from error + names = list(signature.parameters) + positions: dict[str, int | None] = {} + for parameter in sorted(parameters): + if parameter not in signature.parameters: + raise ListWritebackError( + f"{api_name} has no parameter {parameter!r} registered for list write-back" + ) + kind = signature.parameters[parameter].kind + if kind in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ): + positions[parameter] = names.index(parameter) + elif kind is inspect.Parameter.KEYWORD_ONLY: + positions[parameter] = None + else: + raise ListWritebackError( + f"{api_name} parameter {parameter!r} is variadic and cannot be registered " + "for list write-back" + ) + return positions + + +def prepare_list_writebacks( + api_name: str, + positions: ListWritebackPositions, + caller_args: Sequence[object], + caller_kwargs: Mapping[str, object], + callee_args: Sequence[object], + callee_kwargs: Mapping[str, object], +) -> list[PendingListWriteback]: + """Pair each registered list argument of this call with its unproxied copy. + + ``positions`` comes from ``list_writeback_positions``. + ``caller_args``/``caller_kwargs`` are the arguments the caller passed and + ``callee_args``/``callee_kwargs`` the unproxied ones the callee will + receive, in the same positions. A registered argument that was not passed, + or was not passed as a list, needs no write-back: the callee cannot replace + slots of the caller's object through it, so ordinary unproxying stays in + effect. + """ + pending: list[PendingListWriteback] = [] + for parameter in sorted(positions): + position = positions[parameter] + if parameter in caller_kwargs: + caller_value = caller_kwargs[parameter] + callee_value = callee_kwargs[parameter] + elif position is not None and position < len(caller_args): + caller_value = caller_args[position] + callee_value = callee_args[position] + else: + continue + # The same exact-type test as unproxy_arg, which copies exact lists + # only; any other object, list subclasses included, reaches the callee + # as the caller's own. isinstance narrows the type for the checker. + if not isinstance(caller_value, list) or type(caller_value) not in [list]: + continue + assert ( + isinstance(callee_value, list) and callee_value is not caller_value + ), f"{api_name}: argument {parameter!r} was not copied by unproxying" + for other in pending: + if other.caller_list is caller_value: + # Unproxying gives each occurrence its own copy, so the callee + # cannot see the two parameters as one list. + raise ListWritebackError( + f"{api_name} received the same list as {other.parameter!r} and " + f"{parameter!r}; aliased registered lists cannot be written back" + ) + pending.append( + PendingListWriteback( + api_name=api_name, + parameter=parameter, + caller_list=caller_value, + caller_before=tuple(caller_value), + callee_list=callee_value, + passed=tuple(callee_value), + ) + ) + return pending + + +def apply_list_writebacks(pending: Sequence[PendingListWriteback]) -> None: + """Write every slot the callee replaced back into the caller's list. + + Every list is checked before any slot is written, so an error leaves the + caller's lists as the callee left them. + """ + replaced: list[tuple[PendingListWriteback, int, object]] = [] + for item in pending: + expected = len(item.passed) + if len(item.callee_list) != expected or len(item.caller_list) != expected: + raise ListWritebackError( + f"{item.api_name} changed the length of its list argument " + f"{item.parameter!r} (passed {expected} elements, callee now has " + f"{len(item.callee_list)}, caller now has {len(item.caller_list)}); " + "the replaced slots cannot be written back" + ) + for index, (before, after) in enumerate(zip(item.passed, item.callee_list)): + if after is before: + continue + current = item.caller_list[index] + if current is not item.caller_before[index] and current is not after: + raise ListWritebackError( + f"{item.api_name} replaced slot {index} of {item.parameter!r}, " + "and the caller's list was changed at that slot through another " + "reference during the call; the write-back would overwrite it" + ) + replaced.append((item, index, after)) + for item, index, after in replaced: + item.caller_list[index] = after + + +def call_with_list_writebacks( + function: Callable[..., object], + pending: Sequence[PendingListWriteback], + args: Sequence[object], + kwargs: Mapping[str, object], +) -> object: + """Call ``function`` and apply ``pending`` write-backs, also when it raises.""" + if not pending: + return function(*args, **kwargs) + try: + result = function(*args, **kwargs) + except BaseException as error: + # Without instrumentation the caller would see the slots replaced + # before the exception, so write them back and re-raise unchanged. + try: + apply_list_writebacks(pending) + except ListWritebackError as writeback_error: + raise writeback_error from error + raise + apply_list_writebacks(pending) + return result diff --git a/traincheck/instrumentor/proxy_wrapper/proxy_basics.py b/traincheck/instrumentor/proxy_wrapper/proxy_basics.py index d765dd76..151c56b9 100644 --- a/traincheck/instrumentor/proxy_wrapper/proxy_basics.py +++ b/traincheck/instrumentor/proxy_wrapper/proxy_basics.py @@ -1,10 +1,17 @@ import ast import functools import inspect +from collections.abc import Callable import astor import traincheck.config.config as config +from traincheck.instrumentor.proxy_wrapper.list_writeback import ( + call_with_list_writebacks, + list_writeback_positions, + prepare_list_writebacks, +) +from traincheck.utils import typename def is_compile_internal_module(obj): @@ -73,13 +80,11 @@ def unproxy_arg(arg, inspect_torch_module=False): if is_proxied(arg): return unproxy_arg(arg._obj, inspect_torch_module) elif type(arg) in [list]: - # Unproxy in place. Callees such as torch.optim's functional sgd write - # results back into list arguments (e.g. momentum_buffer_list), and the - # caller reads them from the same list afterwards, so a copy would - # silently drop those writes (issue #176). - for index, element in enumerate(arg): - arg[index] = unproxy_arg(element, inspect_torch_module) - return arg + # Always a new list: the caller's list keeps its proxies (an optimizer's + # param list must, since its state is keyed by them). APIs that return + # results by replacing slots of a list argument are registered in + # list_writeback, and unproxy_func writes those slots back (issue #176). + return [unproxy_arg(element, inspect_torch_module) for element in arg] elif type(arg) in [tuple]: return tuple(unproxy_arg(element, inspect_torch_module) for element in arg) # if it is a torch module, unproxy all its named children @@ -105,13 +110,37 @@ def unproxy_args_kwargs(args, kwargs, inspect_torch_module=False): return args, kwargs -def unproxy_func(func, inspect_torch_module=False): +def unproxy_func( + func: Callable[..., object], + inspect_torch_module: bool = False, + api_name: str | None = None, +) -> Callable[..., object]: + """Wrap ``func`` so that it is called with unproxied arguments. + + ``api_name`` is the name ``func`` is registered under in + ``LIST_WRITEBACK_ARGUMENTS``; ``None`` derives it with ``typename``. Slots + that ``func`` replaces in a registered list argument are written back to + the caller's list, also when ``func`` raises. Registered parameters are + resolved here, so a registry entry that does not match ``func`` raises + ``ListWritebackError`` when wrapping rather than at a call. + """ original_func = func + lookup_name = typename(func) if api_name is None else api_name + positions = list_writeback_positions(func, lookup_name) @functools.wraps(original_func) - def wrapper(*args, **kwargs): - args, kwargs = unproxy_args_kwargs(args, kwargs, inspect_torch_module) - return original_func(*args, **kwargs) + def wrapper(*args: object, **kwargs: object) -> object: + callee_args, callee_kwargs = unproxy_args_kwargs( + args, kwargs, inspect_torch_module + ) + if positions is None: + return original_func(*callee_args, **callee_kwargs) + pending = prepare_list_writebacks( + lookup_name, positions, args, kwargs, callee_args, callee_kwargs + ) + return call_with_list_writebacks( + original_func, pending, callee_args, callee_kwargs + ) return wrapper diff --git a/traincheck/instrumentor/proxy_wrapper/proxy_observer.py b/traincheck/instrumentor/proxy_wrapper/proxy_observer.py index 0f0a6d28..e109cf35 100644 --- a/traincheck/instrumentor/proxy_wrapper/proxy_observer.py +++ b/traincheck/instrumentor/proxy_wrapper/proxy_observer.py @@ -66,7 +66,9 @@ def wrapper(*args, **kwargs): processed_function = original_function if unproxy: - processed_function = unproxy_func(original_function) + processed_function = unproxy_func( + original_function, api_name=original_function_name + ) result = processed_function(*args, **kwargs) diff --git a/traincheck/instrumentor/tracer.py b/traincheck/instrumentor/tracer.py index 59b2658b..584b60f4 100644 --- a/traincheck/instrumentor/tracer.py +++ b/traincheck/instrumentor/tracer.py @@ -30,6 +30,13 @@ get_instrumentation_logger_for_process, var_to_serializable, ) +from traincheck.instrumentor.proxy_wrapper.list_writeback import ( + ListWritebackPositions, + call_with_list_writebacks, + has_list_writeback, + list_writeback_positions, + prepare_list_writebacks, +) from traincheck.instrumentor.proxy_wrapper.proxy_basics import ( is_proxied, is_proxyparameter, @@ -360,7 +367,12 @@ def find_proxy_in_args(args): dump_loc=original_function_name, dump_config=var_dump_config ) + # The caller's arguments, kept only for calls with registered list + # write-backs; every other call keeps the direct call below. + writeback_caller: tuple[tuple[object, ...], dict[str, object]] | None = None if need_unproxy_args_kwargs: + if has_list_writeback(original_function_name): + writeback_caller = (args, kwargs) # Construct the actual receiver, never an object obtained by reading # proxy metadata from its partially initialized state. if is_constructor: @@ -387,7 +399,19 @@ def find_proxy_in_args(args): try: if COLLECT_OVERHEAD_METRICS: ORIG_ENTER_PERF_TIME = time.perf_counter() - result = original_function(*args, **kwargs) + if writeback_caller is None: + result = original_function(*args, **kwargs) + else: + # Inside the traced call, so a registry mismatch is recorded as the + # call's exception like any other failure. + result = call_with_registered_list_writebacks( + original_function, + original_function_name, + writeback_caller[0], + writeback_caller[1], + args, + kwargs, + ) if COLLECT_OVERHEAD_METRICS: ORIG_EXIT_PERF_TIME = time.perf_counter() except Exception as e: @@ -526,6 +550,56 @@ def core_wrapper_proxy(original_function, *args, **kwargs): return original_function(*args, **kwargs) +def call_with_registered_list_writebacks( + original_function: Callable[..., object], + original_function_name: str, + caller_args: Sequence[object], + caller_kwargs: Mapping[str, object], + args: Sequence[object], + kwargs: Mapping[str, object], +) -> object: + """Call ``original_function`` with unproxied ``args``/``kwargs`` and write + back the list slots registered for ``original_function_name``. + + ``function_wrapper`` has no wrap-time state of its own, so the registered + parameters are resolved here on each call; this runs only for registered + APIs that the tracer unproxies. + """ + with suppress_tracing(): + positions = list_writeback_positions(original_function, original_function_name) + assert positions is not None, f"{original_function_name} is not registered" + pending = prepare_list_writebacks( + original_function_name, positions, caller_args, caller_kwargs, args, kwargs + ) + return call_with_list_writebacks(original_function, pending, args, kwargs) + + +def core_wrapper_proxy_list_writeback( + original_function: Callable[..., object], + original_function_name: str, + positions: ListWritebackPositions, + *args: object, + **kwargs: object, +) -> object: + """``core_wrapper_proxy`` for APIs with registered list write-backs.""" + if tracing_suppressed(): + return original_function(*args, **kwargs) + + with suppress_tracing(): + callee_args, callee_kwargs = unproxy_args_kwargs(args, kwargs) + pending = prepare_list_writebacks( + original_function_name, + positions, + args, + kwargs, + callee_args, + callee_kwargs, + ) + return call_with_list_writebacks( + original_function, pending, callee_args, callee_kwargs + ) + + def wrapper( original_function: Callable[..., object], is_bound_method: bool, @@ -565,6 +639,13 @@ def wrapper( is_builtin or is_funcs_to_be_unproxied(original_function) ) original_function_name = typename(original_function) + # Resolved once here, so a registry entry that does not match the installed + # library fails at instrumentation time. + writeback_positions = ( + list_writeback_positions(original_function, original_function_name) + if need_unproxy_args_kwargs + else None + ) # determine statically whether to dump the trace if not disable_dump: METRIC_INSTRUMENTED_FUNC_LIST["dump"].append(original_function_name) @@ -592,7 +673,20 @@ def wrapped(*args: object, **kwargs: object) -> object: else: METRIC_INSTRUMENTED_FUNC_LIST["no_dump"].append(original_function_name) - if need_unproxy_args_kwargs: + if writeback_positions is not None: + positions = writeback_positions + + @functools.wraps(original_function) + def wrapped(*args: object, **kwargs: object) -> object: + return core_wrapper_proxy_list_writeback( + original_function, + original_function_name, + positions, + *args, + **kwargs, + ) + + elif need_unproxy_args_kwargs: @functools.wraps(original_function) def wrapped(*args: object, **kwargs: object) -> object: