Huggingface의 Activations

carpediem·2022년 12월 27일
0

Library

목록 보기
4/4

Huggingface는 Activation function들을 어떻게 관리할까?

  • Activation function의 경우 deterministic 하므로 수식을 exp, times, add etc. 이용하여 정의한 후, 모델 학습에 이용하면 된다.
  • Huggingface의 경우 이러한 함수들을 호출할 때, 이름 그대로 이용하는데 용이하게 하기 위해서 ClassInstantier 클래스를 정의하여 활용한다. 이는 Key를 이용해서 미리 정의해놓은 activation function을 바로 callable하게 사용할 수 있도록 하기 위해서이다.
import torch
from transformers.activations import *

class ClassInstantier(OrderedDict):
    def __getitem__(self, key):
        content = super().__getitem__(key)
        cls, kwargs = content if isinstance(content, tuple) else (content, {})
        return cls(**kwargs)

# Below functions are already defined.
ACT2CLS = {
    "gelu": GELUActivation,
    "gelu_10": (ClippedGELUActivation, {"min": -10, "max": 10}),
    "gelu_fast": FastGELUActivation,
    "gelu_new": NewGELUActivation,
    "gelu_python": (GELUActivation, {"use_gelu_python": True}),
    "linear": LinearActivation,
    "mish": MishActivation,
    "quick_gelu": QuickGELUActivation,
    "relu": nn.ReLU,
    "relu6": nn.ReLU6,
    "sigmoid": nn.Sigmoid,
    "silu": SiLUActivation,
    "swish": SiLUActivation,
    "tanh": nn.Tanh,
}

if __name__ == "__main__":
  ACT2FN = ClassInstantier(ACT2CLS)
  gelu = ACT2FN["gelu"]
  random_var = torch.randn(2,3)
  print(gelu(random_var))
profile
Seize the day!

0개의 댓글