ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Model2Vec: 모델을 외워봅시다
    machine learning 2024. 12. 22. 13:22
    plm 기반의 embedding vector는 대량의 corpus를 기반으로 학습했기에 뛰어난 성능을 발휘하지만, 모델 백본 자체의 자원사용량이 크다는 이슈 가 있다 . model2vec 기법은 vector space의 근사 및 정렬을 통해 매우 가벼운 모델사이즈로 성능저하 없이 동일한 벡터임베딩(공간)을 생성한다 .

     

    01. Architecture & Principle

     

    model2vec는 sentence transformer 라이브러리를 기반으로 동작합니다. 가장 유용한 특징 중 하나는, 경량모델을 만들기위해 임의의 정의된 데이터셋이 필요하지 않고, 모델(과 특정 경우 custom vocabulary)만을 필요로 한다는 사실입니다.

     

    tokenizer에 사용된 vocab dictionary를 빈도 위주로 정의한 vocabulary를 모델에 통과시켜 vector set을 생성합니다. vector set에 대한 pca(principle component analysis)를 진행하여 벡터차원을 축소합니다. zipf's law에 기반한 weight embedding 기법을 통해 각 토큰(=벡터)에 대해 weight를 부여합니다.

    최종적으로는, 입력 문장에서 각 토큰별 가중치만 곱한 형태로 간편하게 사용할 수 있습니다.

     

    PCA(Principle Component Analysis)

    일반적으로 PCA 사용은 정보를 버리게 되므로 성능 손실과 연관되지만 차원을 축소하는 것이 오히려 성능을 크게 향상시켰습니다. 이는 PCA가 original vector space의 bias를 제거하는 방식으로 결과 공간을 정규화하여, 유용한 정보들만 남기는 학습에 더 유리하게 동작합니다.

     

    Zipfs

    최종 사용형태에서 space 내의 token들에 대해 단순 평균을 취하므로, vector들이 올바르게 가중치 가 부여되는 것이 중요합니다.

     

    일반적으로는 sentence transformer 가 학습하여 weight에 담아둔 context를 기반으로 모든 token에 대해 적절한 가중치를 부여해주지만, static embedding layer에서는 기대할 수 없습니다. 따라서, 입력 토큰들에게 적절한 가중치를 부여해주는 것이 매우 중요합니다.

     

    일반적으로는 빈번하게 등장하거나 중요하지 않은 단어들의 가중치를 낮추기 위해 Inverse Document Frequency(IDF)와 같은 것 을 사용하는것이 권장되지만, model2vec가 상정하는 use case에서는 document frequency를 계산하기 위한 corpus에 접근할 수 없습니다. model2vector는 오로지 모델/토크나이저만 사용하기로 결정했습니다.

     

    zipf's laws는 빈도순으로 정렬된 리스트가 주어졌을 때, 해당 리스트의 빈도순 정렬이 power law distribution을 따른다고 가정합니다. 따라서 vocabulary가 빈도순으로 정렬되어 있다고 가 정하면, 실제 문서를 기반으로 수집한 빈도에 대한 접근 없이도 매우 빈번한 항목들의 가중치를 정확하게 낮출 수 있습니다.

     

    tokenizer vocabulary가 빈도순으로 정렬되어 있으므로 이미 ranked list에 대한 접근할 수 있어, 추가적인 작업 없이 이 최적화를 사용하여 토큰별 가중치를 부여합니다.

     

     

    02. Usage

    sentence transformer에서 사용가능하다면 그 어떤 모델이라도 distillation하고 inference할 수 있습니다. distillation은 3가지 접근법 중 하나를 선택해서 진행할 수 있습니다.

    • Output
      • 실제 sentence transformer와 매우 유사하게 작동
      • 즉, subword tokenizer를 사용하고 vocabulary의 모든 wordpiece를 단순히 인코딩
      • 생성이 매우 빠르고(CPU에서 30초), 크기 가 매우 작으며(float32에서 30MB), 다만 일부 task에서는 성능이 다소 저하
    • Vocab (word)
      • 이 모드에서는 사용자 가 직접 vocabulary를 전달하여 representation 을 생성
      • 이를 통해 보유한 in-domain data에 대해 좋은 representation 을 생성할 수 있으며, GloVe나 word2vec의 drop-in replacement로 사용 될 수 있음
    • Vocab (subword)
      • 이 모드에서는 사용자의 vocabulary를 전달할 수 있으며, 동시에 subword vocabulary도 함께 사용하여 representation 을 생성
      • 이를 통해 보유한 in-domain data에 대해 좋은 representation 을 생성할 수 있음

     

    how to use

    • inference
    from model2vec import StaticModel
    
    # Load a model from the HuggingFace hub (in this case the M2V_base_output model)
    model_name = "minishlab/M2V_base_output"
    model = StaticModel.from_pretrained(model_name)
    
    # Make embeddings
    embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."])

     

    • distillation
    from model2vec import distill
    
    # Choose a Sentence Transformer model
    base_model_name = "BAAI/bge-base-en-v1.5"
    
    # Distill an output model with the chosen dimensions
    model = distill(model_name=base_model_name, pca_dims=256)
    
    # Make embeddings
    embeddings = model.encode(["supervillain Ganondorf has invaded Hyrule!"])
    print(model.tokenizer.encode("supervillain Ganondorf has invaded Hyrule!", add_special_tokens=
    # ['super', '##vill', '##ain', 'gan', '##ond', '##orf', 'has', 'invaded', 'h', '##yr', '##ule'
    
    # It looks like we split Ganondorf and Hyrule up into many subtokens
    # To solve this, we can add these words to our vocabulary.
    vocabulary = ["supervillain", "ganondorf", "hyrule"]
    
    # Distill the model with the custom vocabulary.
    model = distill(model_name=base_model_name, vocabulary=vocabulary, pca_dims=256)
    print(model.tokenizer.encode("supervillain Ganondorf has invaded Hyrule!", add_special_tokens=
    # ['supervillain', 'ganondorf', 'has', 'invaded', 'hyrule', '!']
    # Much better.

     

     

    'machine learning' 카테고리의 다른 글

    추천시스템 overall  (0) 2025.04.06
    Cluster 평가지표  (2) 2025.02.01
    Matryoshka Representation Learning  (2) 2024.12.22
    딥러닝 하드웨어 담론 (4)  (2) 2024.11.30
    딥러닝 하드웨어 담론 (3)  (0) 2024.11.24
Designed by Tistory.