forked from Project-MONAI/MONAI
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
6973 sincos pos embed (Project-MONAI#6986)
Fixes Project-MONAI#6973 ### Description Adding support for sincos positional embedding for monai.networks.blocks.patchembedding.PatchEmbedding class. This pull request corresponds to this opened issue Project-MONAI#6973 ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [x] Breaking change (fix or new feature that would cause existing functionality to change). - [x] New tests added to cover the changes. - [x] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [x] Quick tests passed locally by running `./runtests.sh --quick --unittests --disttests`. - [x] In-line docstrings updated. - [x] Documentation updated, tested `make html` command in the `docs/` folder. --------- Signed-off-by: NoTody <[email protected]>
- Loading branch information
Showing
10 changed files
with
215 additions
and
53 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
# Copyright (c) MONAI Consortium | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from __future__ import annotations | ||
|
||
import collections.abc | ||
from itertools import repeat | ||
from typing import List, Union | ||
|
||
import torch | ||
import torch.nn as nn | ||
|
||
__all__ = ["build_sincos_position_embedding"] | ||
|
||
|
||
# From PyTorch internals | ||
def _ntuple(n): | ||
def parse(x): | ||
if isinstance(x, collections.abc.Iterable) and not isinstance(x, str): | ||
return tuple(x) | ||
return tuple(repeat(x, n)) | ||
|
||
return parse | ||
|
||
|
||
def build_sincos_position_embedding( | ||
grid_size: Union[int, List[int]], embed_dim: int, spatial_dims: int = 3, temperature: float = 10000.0 | ||
) -> torch.nn.Parameter: | ||
""" | ||
Builds a sin-cos position embedding based on the given grid size, embed dimension, spatial dimensions, and temperature. | ||
Reference: https://github.com/cvlab-stonybrook/SelfMedMAE/blob/68d191dfcc1c7d0145db93a6a570362de29e3b30/lib/models/mae3d.py | ||
Args: | ||
grid_size (List[int]): The size of the grid in each spatial dimension. | ||
embed_dim (int): The dimension of the embedding. | ||
spatial_dims (int): The number of spatial dimensions (2 for 2D, 3 for 3D). | ||
temperature (float): The temperature for the sin-cos position embedding. | ||
Returns: | ||
pos_embed (nn.Parameter): The sin-cos position embedding as a learnable parameter. | ||
""" | ||
|
||
if spatial_dims == 2: | ||
to_2tuple = _ntuple(2) | ||
grid_size_t = to_2tuple(grid_size) | ||
h, w = grid_size_t | ||
grid_h = torch.arange(h, dtype=torch.float32) | ||
grid_w = torch.arange(w, dtype=torch.float32) | ||
|
||
grid_h, grid_w = torch.meshgrid(grid_h, grid_w, indexing="ij") | ||
|
||
assert embed_dim % 4 == 0, "Embed dimension must be divisible by 4 for 2D sin-cos position embedding" | ||
|
||
pos_dim = embed_dim // 4 | ||
omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim | ||
omega = 1.0 / (temperature**omega) | ||
out_h = torch.einsum("m,d->md", [grid_h.flatten(), omega]) | ||
out_w = torch.einsum("m,d->md", [grid_w.flatten(), omega]) | ||
pos_emb = torch.cat([torch.sin(out_w), torch.cos(out_w), torch.sin(out_h), torch.cos(out_h)], dim=1)[None, :, :] | ||
elif spatial_dims == 3: | ||
to_3tuple = _ntuple(3) | ||
grid_size_t = to_3tuple(grid_size) | ||
h, w, d = grid_size_t | ||
grid_h = torch.arange(h, dtype=torch.float32) | ||
grid_w = torch.arange(w, dtype=torch.float32) | ||
grid_d = torch.arange(d, dtype=torch.float32) | ||
|
||
grid_h, grid_w, grid_d = torch.meshgrid(grid_h, grid_w, grid_d, indexing="ij") | ||
|
||
assert embed_dim % 6 == 0, "Embed dimension must be divisible by 6 for 3D sin-cos position embedding" | ||
|
||
pos_dim = embed_dim // 6 | ||
omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim | ||
omega = 1.0 / (temperature**omega) | ||
out_h = torch.einsum("m,d->md", [grid_h.flatten(), omega]) | ||
out_w = torch.einsum("m,d->md", [grid_w.flatten(), omega]) | ||
out_d = torch.einsum("m,d->md", [grid_d.flatten(), omega]) | ||
pos_emb = torch.cat( | ||
[ | ||
torch.sin(out_w), | ||
torch.cos(out_w), | ||
torch.sin(out_h), | ||
torch.cos(out_h), | ||
torch.sin(out_d), | ||
torch.cos(out_d), | ||
], | ||
dim=1, | ||
)[None, :, :] | ||
else: | ||
raise NotImplementedError("Spatial Dimension Size {spatial_dims} Not Implemented!") | ||
|
||
pos_embed = nn.Parameter(pos_emb) | ||
pos_embed.requires_grad = False | ||
|
||
return pos_embed |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.