Lightning-AI / Lightning-AI/lightning-thunder
Support `torch.Tensor.register_hook`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 1.5k
- Forks
- 121
- PR merge metrics
- No merged PRs in 30d
Description
🚀 Feature
Motivation
In Lightning Fabric, we use this once for error checking that the user properly called backward. https://github.com/Lightning-AI/pytorch-lightning/blob/096b063d6eeb41567409f4a6b9bac6f5af28ed93/src/lightning/fabric/wrappers.py#L232-L233. cc @awaelchli
I don't expect that we run this hook properly on backward, but it would be useful to simply ignore it and not fail on it, maybe showing a warning.
Pitch
import thunder
import torch
def hook(_):
print("Hello")
def fn(x):
y = x * 2
y.register_hook(hook)
return y
t = torch.tensor([1.0], requires_grad=True)
fn = thunder.jit(fn)
out = fn(t)
out.backward()
print(out)
y.register_hook(hook)
File "/home/carmocca/git/lightning-thunder/thunder/core/interpreter.py", line 5862, in _impl
return fn.__func__(fn.__self__, *args, **kwargs)
File "/home/carmocca/git/lightning-thunder/thunder/core/interpreter.py", line 1243, in jit_wrapped
res = ufn(*uargs, **ukwargs)
File "/home/carmocca/git/lightning-thunder/thunder/core/proxies.py", line 1210, in __getattr__
method: None | Callable = resolve_method(attr, self)
File "/home/carmocca/git/lightning-thunder/thunder/core/langctxs.py", line 68, in resolve_method
method: Callable = ctx.get_method(id, *args, **kwargs)
File "/home/carmocca/git/lightning-thunder/thunder/torch/langctx.py", line 40, in get_method
raise AttributeError(f"The {self.name} language context has no method {id}")
AttributeError: The torch language context has no method register_hook
Additional context
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the issue with the Lightning Fabric example and trace the method lookup through thunder/core/proxies.py and thunder/torch/langctx.py, especially get_method. Confirm how torch.Tensor.register_hook should be handled when compiled, then verify the example no longer fails and produces the intended ignored-hook or warning behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python, pytorch
- Domain
- machine-learning
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100