시작은 미약하였으나 , 그 끝은 창대하리라

[Huggingface] 가중치 없이 모델 로드 및 모델 구조 변경 본문

인공지능/딥러닝 및 파이토치 기타 정리

[Huggingface] 가중치 없이 모델 로드 및 모델 구조 변경

애플파ol 2024. 4. 23. 23:00

1. 가중치 없이 모델 로드 

► 우리는 허깅페이스에서 weight, bias가 최적화 되어있는 pretrained된 모델을 사용한다. 하지만 모델의 weight, bias를 제외하고 아키텍쳐만 필요할 때가 있다. Hugging Face에서는 친절하게도 이러한 기능을 제공을 해준다.

 

- Huggingface에 원하는 모델을 검색후 config를 사용하면 된다. (아래예시는 DETR예시)

  (상단 코드 weight load 안함, 하단 코드 weight load 함)

# load without weight and bias

# Initializing a DETR facebook/detr-resnet-50 style configuration
from transformers import DetrForObjectDetection, DetrConfig
# Initializing a model (with random weights) from the facebook/detr-resnet-50 style configuration
configuration = DetrConfig()
model = DetrForObjectDetection(config=configuration)

print(configuration)
print()
print(model)


##################################################
##################################################
##################################################


# pretrained model load
from transformers import AutoConfig,AutoModel

configuration = AutoConfig.from_pretrained("facebook/detr-resnet-50", revision="no_timm")
model = AutoModel.from_config(configuration)
print(configuration)
print()
print(model)

 

config file을 사용해서 초기화를 하면 weight가 load 안된다고 나와있음.

- 아래는 각각(pretrain, without pretrain) config를 출력했을 때 사진. (pretrain사진은 너무 길어서 자름)

좌측 :  pretrained model,  우측 : without pretrained model

 

 

 


 

 

 

2. 모델 구조 변경

모델의 하이퍼 파라미터를 변경하고 싶을 수도 있다. 이를 위해 Config에서 수정을 하면 되며, huggingface홈페이지에 들어가서 어떠한 parameters들을 사용하는지 보고 수정하면 된다.

 

DETR모델의 인자 값들

► 아래와 같이 수정하면 된다. 

from transformers import DetrConfig

configuration = DetrConfig(activation_dropout=0.1,activation_function='gelu')
print(configuration)

 

► 좌측은 기존 DetrConfig() 를 수행했을 때 나오는 config들, 우측은 위에 코드를 사용하여 수정한 사진

    (맨위의 activiation_dropout, activation_function의 값이 변한것을 볼 수 있다)

 

좌측 : defalut 값, 우측: 파라미터 변경

 

 

 

 

reference

- https://huggingface.co/docs/transformers/model_doc/detr#transformers.DetrModel

 

 

 

Comments