Skip to content

Add support for callable in torchax.interop.JittableModule.functional_call in the first parameter #9451

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions torchax/test/test_jittable_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,25 @@ def test_isinstance_does_not_mix(self):
assert isinstance(JittableMoreAwesomeModel, EvenMoreAwesomeModel)
assert not isinstance(JittableMoreAwesomeModel, MyAwesomeModel)

def test_functional_call_callable(self):

def outer_function(model, x):
return x + 1

model = MyAwesomeModel()
jittable_module = interop.JittableModule(model)

# Check if the jittable module can be called like a function
input_tensor = torch.randn(1, 3, 224, 224)
expected_output = input_tensor + 1

output = jittable_module.functional_call(outer_function,
jittable_module.params,
jittable_module.buffers,
input_tensor)

assert torch.equal(output, expected_output)


if __name__ == '__main__':
unittest.main()
14 changes: 12 additions & 2 deletions torchax/torchax/interop.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,16 +90,26 @@ def __class__(self):
def __call__(self, *args, **kwargs):
return self.forward(*args, **kwargs)

def functional_call(self, method_name, params, buffers, *args, **kwargs):
def functional_call(self, method_or_name, params, buffers, *args, **kwargs):
kwargs = kwargs or {}
params_copy = copy.copy(params)
params_copy.update(buffers)
# reinflate the state dict so there are not any missing keys
for k, v in self._extra_dumped_weights.items():
for new_key in v:
params_copy[new_key] = params_copy[k]

if isinstance(method_or_name, str):
method = getattr(self._model, method_or_name)
else:
if not callable(method_or_name):
raise TypeError(
f"method_or_name should be a callable or a string, got {type(method_or_name)}"
)
method = method_or_name
args = (self._model,) + args
with torch_stateless._reparametrize_module(self._model, params_copy):
res = getattr(self._model, method_name)(*args, **kwargs)
res = method(*args, **kwargs)
return res

def forward(self, *args, **kwargs):
Expand Down
Loading