본문 바로가기

인공지능/Python

Flexible! Powerful! Einops

Einops?

tensor의 차원을 원하는대로 바꿀 수 있는 라이브러리

굉장히 직관적이며 빠르게 작동

 

Example

기본 코드 예시

from einops import rearrange, reduce, repeat

# rearrange elements according to the pattern
rearrange(torch.zeros((3,244,244)), 'c h w -> h w c').shape
#torch.Size([244, 244, 3])

# combine rearrangement and reduction
reduce(torch.zeros((16,3,224,224)), 'b c (h h2) (w w2) -> b h w c','mean',h2 = 16, w2 = 16).shape
#torch.Size([16, 14, 14, 3])

# copy along a new axis 
repeat(torch.zeros((3,224,224)), 'c h w -> b h w c', b = 16).shape
#torch.Size([16, 224, 224, 3])

input_tensor의 차원을 순서대로 naming하고 이를 재배치 해준다.

- 소괄호로 묶으면 곱셈이라는 뜻

reduce는 mean, max 정도가 들어갈 수 있는 것 같다.

- max 가 들어가면 max pooling과 같은 역할을 한다고 보임

 

Usage

실제 적용 예시 (Vision Transformer image patch processing)

- pytorch layer 버전으로 존재하여 nn.Sequential에 끼워 넣을 수 있음

- tensorflow, numpy, jax 모두 지원

from einops.layers.torch import Rearrange

self.to_patch_embedding = nn.Sequential(
    Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1 = patch_height, p2 = patch_width),
    nn.Linear(patch_dim, dim),
)