Huggingface hub에 모델을 올리는 법을 자꾸 까먹어서 글로 남겨보려고 합니다. 방법들을 찾아보니 총 3가지 방법이 있는거 같은데, 이들에 대해 다뤄보고자 합니다. 실습에 사용된 패키지와 버전은 아래와 같습니다.

transformers==4.14.1 
huggingface-hub==0.2.1 # transformers 설치하면 같이 설치됨

그리고 빠른 실습을 위해 모델의 용량이 작은 gpt2-tiny모델을 이용하였습니다.

1. push_to_hub() 이용

모델과 토크나이저에 대해서 push_to_hub()메소드를 이용하여 바로 모델을 업로드하는 방법이 있습니다. 이 방법을 이용하면 원격 저장소 생성까지 한 후에 업로드를 해줍니다.

from transformers import AutoTokenizer, AutoModelForCausalLM

print("model loading...")

# Model & Tokenizer loading
tokenizer = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
model = AutoModelForCausalLM.from_pretrained("sshleifer/tiny-gpt2")

# Repository 생성 & model upload
REPO_NAME = YOUR_REPO_NAME # ex) 'my-bert-fine-tuned'
AUTH_TOKEN = YOUR_OWN_TOKEN # <https://huggingface.co/settings/token>

## Upload to Huggingface Hub
model.push_to_hub(
    REPO_NAME, 
    use_temp_dir=True, 
    use_auth_token=AUTH_TOKEN
)
tokenizer.push_to_hub(
    REPO_NAME, 
    use_temp_dir=True, 
    use_auth_token=AUTH_TOKEN
)

위 코드를 통해 모델을 업로드할 때, 권한을 위한 토큰값이 필요합니다.

Huggingface 홈페이지에 로그인한 후 오른쪽 상단 프로필 > Settings > Access Tokens을 누르거나 로그인 후에 링크를 클릭하면 바로 토큰을 관리할 수 있는 페이지가 나타납니다. 페이지 상단을 보면 User Access Tokens부분이 있는데, 여기서 New token을 눌러 토큰을 생성할 수 있습니다. 이 때, Role을 read로 하면 권한 에러가 발생하므로 write로 설정해야합니다.

New Token 클릭
Role을 write로 해서 토큰을 생성
생성된 토큰의 모습

이렇게 생성된 토큰값을 AUTH_TOKEN의 값으로 이용하면 됩니다.

2. CLI 이용

다음은 CLI환경에서 모델을 업로드하는 방법입니다. 우선 아래 코드를 이용해 모델과 토크나이저가 model 디렉토리에 저장되어 있다고 하겠습니다.

from transformers import AutoTokenizer, AutoModelForCausalLM

print("model loading...")

# Model & Tokenizer loading
tokenizer = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
model = AutoModelForCausalLM.from_pretrained("sshleifer/tiny-gpt2")

tokenizer.save_pretrained("./model")
model.save_pretrained("./model")

이후 이용법은 깃허브에 파일을 올리는 것과 동일합니다.

다만 모델의 용량이 큰 것은 수십GB에 이르기 때문에 용량이 큰 파일도 업로드 할 수 있도록 git lfs(Large File Storage)를 설치합니다. 설치가 완료되면 user.email과 user.name을 huggingface 계정의 이메일과 이름으로 설정해줍니다.

git lfs install
git config --global user.email YOUR_EMAIL
git config --global user.name YOUR_NAME

그리고 huggingface-cli login을 입력하여 로그인을 합니다. 로그인을 위해 토큰값이 필요한데, 위의 과정을 통해 생성된 토큰값을 입력하면 됩니다.

huggingface-cli login

이후 아래 과정을 통해 모델을 업로드하면 됩니다.

# Repository 생성
# organization에 생성할 경우
# huggingface-cli repo create YOUR_MODEL_NAME --organization YOUR_ORG_NAME
huggingface-cli repo create YOUR_MODEL_NAME

# 원격 저장소 가져오기
git clone <https://huggingface.co/USER_NAME/YOUR_MODEL_NAME>

# 모델, 토크나이저 Copy
cp -r model/* YOUR_MODEL_NAME
cd YOUR_MODEL_NAME
git add *
git commit -m "Initial commit"
git push

3. huggingface-hub 이용

마지막으로 transformers 패키지를 설치하면 같이 설치되는 huggingface-hub 패키지를 이용하는 방법이 있는데, 이를 이용하면 코드 상에서 모델 업로드 뿐만 아니라 더 많은 작업을 수행할 수 있습니다. 주의할 점은 ipynb파일에서만 작업이 가능한 점입니다.

먼저 아래 코드로 huggingface 계정과 연동시킬 수 있는데, 위의 과정과 마찬가지로 토큰값이 필요합니다.

from huggingface_hub import notebook_login

notebook_login()

create_repo()와 delete_repo()를 이용하면 원격 저장소를 생성하고, 삭제할 수 있습니다.

from huggingface_hub import create_repo

# Repository 생성
create_repo(name=REPO_NAME)

# Repository 삭제
delete_repo(name=REPO_NAME

아래 코드를 이용하면 Repository 객체를 생성할 수 있습니다. 여기서 첫 번째 인자는 생성할 로컬 저장소 이름이고, 두 번째 인자는 연동할 원격 저장소 이름입니다. 코드를 실행하면 객체가 생성되면서 원격 저장소의 파일들이 로컬 저장소에 복사되고, 객체를 이용해서 원격 저장소와 관련된 작업들을 할 수 있습니다.

from huggingface_hub import Repository

repo = Repository(LOCAL_DIR_NAME, clone_from=NAMESPACE/REPO_NAME)

로컬에 저장한 모델을 로컬 저장소로 복사합니다.

!cp -r model/* LOCAL_DIR_NAME

아래 코드를 이용해서 로컬 저장소에 있는 모델들을 원격 저장소에 업로드 할 수 있습니다.

repo.git_add()
repo.git_commit('Initial commit')
repo.git_push()

그리고 upload_file()를 이용하면 add, commit, push 작업 없이 바로 하나의 파일을 업로드할 수도 있습니다. 여기서는 굳이 로컬 저장소에 있지 않은 파일도 업로드가 가능합니다. path_in_repo 인자값은 원격 저장소에 저장되는 파일의 이름입니다.

from huggingface_hub import upload_file, delete_file

# 파일을 직접 업로드
upload_file(
    LOCAL_FILE_PATH,
    path_in_repo=REPO_FILE_PATH,
    repo_id=NAMESPACE/REPO_NAME,
)

delete_file()를 이용하면 원격 저장소의 파일을 바로 삭제할 수도 있습니다.

# 파일 삭제
delete_file(
    REPO_FILE_PATH,
    repo_id=NAMESPACE/REPO_NAME,
)

Reference

+ Recent posts