Commit 837dc32
fix(networks): replace Tensor | None with Optional[Tensor] for TorchScript compatibility (#8879)
## Summary
Fixes #7939
The `|` union type syntax (e.g. `torch.Tensor | None`) was introduced in
Python 3.10. While `from __future__ import annotations` defers
annotation evaluation at runtime, **TorchScript's annotation parser does
not support this syntax** and fails when scripting models that include
these forward method signatures, producing:
```
RuntimeError: Can't redefine method: forward on class
```
This PR replaces `torch.Tensor | None` with `Optional[torch.Tensor]`
(from `typing`) in the `forward` methods of the three blocks that form
the ViT/UNETR scripting path:
- `monai/networks/blocks/crossattention.py` —
`CrossAttentionBlock.forward`
- `monai/networks/blocks/selfattention.py` — `SABlock.forward`
- `monai/networks/blocks/transformerblock.py` —
`TransformerBlock.forward`
## Test plan
- [x] `torch.jit.script(CrossAttentionBlock(...))` succeeds after fix
- [x] `torch.jit.script(SABlock(...))` succeeds after fix
- [x] `torch.jit.script(TransformerBlock(...))` succeeds after fix
- [ ] `python -m pytest tests/networks/nets/test_unetr.py -k
test_script`
- [ ] `python -m pytest tests/networks/blocks/test_crossattention.py`
- [ ] `python -m pytest tests/networks/blocks/test_selfattention.py`
---------
Signed-off-by: Oleksandr Sanin <alexaaander.sanin@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com>1 parent dc0f59c commit 837dc32
3 files changed
Lines changed: 17 additions & 3 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
11 | 11 | | |
12 | 12 | | |
13 | 13 | | |
| 14 | + | |
| 15 | + | |
14 | 16 | | |
15 | 17 | | |
16 | 18 | | |
| |||
139 | 141 | | |
140 | 142 | | |
141 | 143 | | |
142 | | - | |
| 144 | + | |
143 | 145 | | |
144 | 146 | | |
145 | 147 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
11 | 11 | | |
12 | 12 | | |
13 | 13 | | |
| 14 | + | |
| 15 | + | |
14 | 16 | | |
15 | 17 | | |
16 | 18 | | |
| |||
158 | 160 | | |
159 | 161 | | |
160 | 162 | | |
161 | | - | |
| 163 | + | |
162 | 164 | | |
163 | 165 | | |
164 | 166 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
11 | 11 | | |
12 | 12 | | |
13 | 13 | | |
| 14 | + | |
| 15 | + | |
14 | 16 | | |
15 | 17 | | |
16 | 18 | | |
| |||
23 | 25 | | |
24 | 26 | | |
25 | 27 | | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
26 | 33 | | |
27 | 34 | | |
28 | 35 | | |
| |||
102 | 109 | | |
103 | 110 | | |
104 | 111 | | |
105 | | - | |
| 112 | + | |
| 113 | + | |
| 114 | + | |
| 115 | + | |
106 | 116 | | |
107 | 117 | | |
108 | 118 | | |
| |||
0 commit comments