Commit eb55abe
committed
fix(networks): replace Tensor | None union syntax with Optional[Tensor] for TorchScript compatibility
The `|` union type syntax (e.g. `torch.Tensor | None`) was introduced in
Python 3.10. While `from __future__ import annotations` defers evaluation
at runtime, TorchScript's annotation parser does not support this syntax
and fails when scripting models that contain these forward method signatures.
Replace `torch.Tensor | None` with `Optional[torch.Tensor]` in the
`forward` methods of:
- `monai/networks/blocks/crossattention.py` (CrossAttentionBlock)
- `monai/networks/blocks/selfattention.py` (SABlock)
- `monai/networks/blocks/transformerblock.py` (TransformerBlock)
These three blocks are used in the ViT/UNETR scripting path, causing
`RuntimeError: Can't redefine method: forward on class` when
`torch.jit.script()` is called on a UNETR model.
Closes #7939
Signed-off-by: Oleksandr Sanin <alexaaander.sanin@gmail.com>1 parent 0a8d945 commit eb55abe
3 files changed
Lines changed: 6 additions & 3 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
13 | 13 | | |
14 | 14 | | |
15 | 15 | | |
| 16 | + | |
16 | 17 | | |
17 | 18 | | |
18 | 19 | | |
| |||
139 | 140 | | |
140 | 141 | | |
141 | 142 | | |
142 | | - | |
| 143 | + | |
143 | 144 | | |
144 | 145 | | |
145 | 146 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
14 | 14 | | |
15 | 15 | | |
16 | 16 | | |
| 17 | + | |
17 | 18 | | |
18 | 19 | | |
19 | 20 | | |
| |||
158 | 159 | | |
159 | 160 | | |
160 | 161 | | |
161 | | - | |
| 162 | + | |
162 | 163 | | |
163 | 164 | | |
164 | 165 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
13 | 13 | | |
14 | 14 | | |
15 | 15 | | |
| 16 | + | |
16 | 17 | | |
17 | 18 | | |
18 | 19 | | |
| |||
89 | 90 | | |
90 | 91 | | |
91 | 92 | | |
92 | | - | |
| 93 | + | |
93 | 94 | | |
94 | 95 | | |
95 | 96 | | |
| |||
0 commit comments