-
Notifications
You must be signed in to change notification settings - Fork 46
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add a helper function wrapper around einops rearrange that allows for…
… passing in anonymous dimensions as a list, for addressing a common tensor manipulation pattern of saving adjacent dimensions for flatten and then reconstitution
- Loading branch information
1 parent
731206d
commit b190c5e
Showing
3 changed files
with
38 additions
and
7 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,28 @@ | ||
import re | ||
from einops import rearrange | ||
|
||
def rearrange_with_dim_list(tensor, pattern, **kwargs): | ||
regex = r'(\.\.\.[a-zA-Z]+)' | ||
matches = re.findall(regex, pattern) | ||
dim_prefixes = tuple(map(lambda t: t.lstrip('...'), set(matches))) | ||
|
||
update_kwargs_dict = dict() | ||
|
||
for prefix in dim_prefixes: | ||
assert prefix in kwargs, f'dimension list "{prefix}" was not passed in' | ||
dim_list = kwargs[prefix] | ||
assert isinstance(dim_list, (list, tuple)), f'dimension list "{prefix}" needs to be a tuple of list of dimensions' | ||
dim_names = list(map(lambda ind: f'{prefix}{ind}', range(len(dim_list)))) | ||
update_kwargs_dict[prefix] = dict(zip(dim_names, dim_list)) | ||
|
||
def sub_with_anonymous_dims(t): | ||
dim_name_prefix = t.groups()[0].strip('...') | ||
return ' '.join(update_kwargs_dict[dim_name_prefix].keys()) | ||
|
||
pattern_new = re.sub(regex, sub_with_anonymous_dims, pattern) | ||
|
||
for prefix, update_dict in update_kwargs_dict.items(): | ||
del kwargs[prefix] | ||
kwargs.update(update_dict) | ||
|
||
return rearrange(tensor, pattern_new, **kwargs) |