원래 저장소가 더 이상 유지되지 않기 때문에 이는 강사 모델용 포크입니다. 또한 소스 코드를 일부 개선했습니다.
sentence-transformers
라이브러리와 작동하도록 수정했습니다.이 리포지토리에는 One Embedder, Any Task: Instruction-Finetuned Text Embeddings 논문에 대한 코드와 사전 훈련된 모델이 포함되어 있습니다. 빠른 프로젝트 개요를 보려면 프로젝트 페이지를 참조하세요.
모든 작업(예: 분류, 검색, 클러스터링, 텍스트 평가 등) 및 도메인(예: 과학, 금융 등)에 맞는 텍스트 임베딩을 생성할 수 있는 명령 미세 조정 텍스트 임베딩 모델인 Instructor ??를 소개합니다. 별도의 미세 조정 없이 단순히 작업 지시만 제공하면 됩니다 . Instructor?는 70가지 다양한 임베딩 작업에서 sota를 달성했습니다!
**************************** 업데이트 ********************* *******
encode
기능모든 텍스트 임베딩에 INSTRUCTOR를 사용하는 것은 매우 쉽습니다. Colab 노트북에서 쉽게 사용해 볼 수 있습니다. 로컬 머신에서 먼저 가상 환경을 생성하는 것이 좋습니다.
conda env create -n instructor python=3.7
git clone https://github.com/HKUNLP/instructor-embedding
pip install -r requirements.txt
그러면 우리가 사용한 환경 instructor
생성됩니다. 임베딩 도구를 사용하려면 먼저 PyPI에서 InstructorEmbedding
패키지를 설치하십시오.
pip install InstructorEmbedding
또는 코드에서 직접 설치
pip install -e .
다음을 실행하여 환경을 활성화하세요.
conda activate instructor
먼저 사전 학습된 모델을 다운로드합니다(사용 가능한 모델의 전체 목록은 모델 목록 참조).
from InstructorEmbedding import INSTRUCTOR
model = INSTRUCTOR ( 'hkunlp/instructor-large' )
그런 다음 모델에게 문장과 맞춤형 지침을 제공합니다.
# prepare texts with instructions
text_instruction_pairs = [
{ "instruction" : "Represent the Science title:" , "text" : "3D ActionSLAM: wearable person tracking in multi-floor environments" },
{ "instruction" : "Represent the Medicine sentence for retrieving a duplicate sentence:" , "text" : "Recent studies have suggested that statins, an established drug group in the prevention of cardiovascular mortality, could delay or prevent breast cancer recurrence but the effect on disease-specific mortality remains unclear." }
]
# postprocess
texts_with_instructions = []
for pair in text_instruction_pairs :
texts_with_instructions . append ([ pair [ "instruction" ], pair [ "text" ]])
# calculate embeddings
customized_embeddings = model . encode ( texts_with_instructions )
그리고 그게 이미 다입니다. 이제 임베딩이 포함된 numpy 배열 목록이 생겼습니다.
for pair , embedding in zip ( text_instruction_pairs , customized_embeddings ):
print ( "Instruction: " , pair [ "instruction" ])
print ( "text: " , pair [ "text" ])
print ( "Embedding: " , embedding )
print ( "" )
encode
기능 모델 사용자는 encode
기능만 사용해야 합니다.
model . encode ( sentences ,
batch_size : int = 32 ,
show_progress_bar : bool = None ,
output_value : str = 'sentence_embedding' ,
convert_to_numpy : bool = True ,
convert_to_tensor : bool = False ,
device : str = None ,
normalize_embeddings : bool = False )
sentences
: 삽입할 문장입니다. [["instruction prompt 0", "text to be embedded 0], ["instruction prompt 1", "text to be embedded 1], ...]
형식이어야 합니다.batch_size
(기본값: 32): 계산에 사용되는 배치 크기입니다. 각 배치에서 함께 처리되는 문장 수를 결정합니다.show_progress_bar
(기본값: 없음): True
로 설정하면 문장을 인코딩하는 동안 진행률 표시줄을 표시하여 인코딩 진행 상황을 시각적으로 표시합니다.output_value
(기본값: 'sentence_embedding'): 원하는 출력 유형을 지정합니다. 기본값 'sentence_embedding'은 문장 임베딩을 반환합니다. 'token_embeddings'로 설정하면 워드피스 토큰 임베딩이 반환됩니다. None으로 설정하면 모든 출력 값이 반환됩니다.convert_to_numpy
(기본값: True
): True
로 설정하면 출력은 numpy 벡터 목록입니다. False
로 설정하면 출력은 PyTorch 텐서 목록입니다.convert_to_tensor
(기본값: False
): True
로 설정하면 함수는 누적된 텐서를 단일 출력으로 반환합니다. 이 매개변수는 convert_to_numpy
에 지정된 모든 설정을 재정의합니다.device
(기본값: None): 계산에 사용할 torch.device를 지정합니다. 지정하지 않으면 함수는 기본 장치를 사용합니다.normalize_embeddings
(기본값: False
): True
로 설정하면 반환된 벡터의 길이는 1이 되어 정규화되었음을 나타냅니다. 이 경우 유사성 검색은 코사인 유사성 대신 더 빠른 내적( util.dot_score
)을 사용합니다. 다양한 크기의 INSTRUCTOR 체크포인트 시리즈를 출시했습니다. InstructorEmbedding
패키지를 사용하면 이러한 모델을 쉽게 로드할 수 있습니다.
모델 | 평균 점수 |
---|---|
hkunlp/강사 기반 | 55.9 |
hkunlp/강사-대형 | 58.4 |
hkunlp/강사-xl | 58.8 |
우리는 다음과 같은 몇 가지 구체적인 사용 사례를 제공합니다. 더 많은 예시와 적용 사례를 보려면 당사의 논문을 참조하세요.
특정 문장에 대한 맞춤형 임베딩을 계산하려면 통합 템플릿을 따라 지침을 작성할 수 있습니다.
task_objective
에 대한 domain
text_type
나타냅니다.
domain
선택사항이며 텍스트의 영역(예: 과학, 금융, 의학 등)을 지정합니다.text_type
필수이며 문장, 문서, 문단 등 인코딩 단위를 지정합니다.task_objective
는 선택사항이며 문서 검색, 문장 분류 등 삽입 목적을 지정합니다.INSTRUCTOR를 사용하면 맞춤화된 임베딩을 통해 두 문장 그룹 간의 유사성을 계산할 수 있습니다.
from sklearn . metrics . pairwise import cosine_similarity
sentences_a = [[ 'Represent the Science sentence: ' , 'Parton energy loss in QCD matter' ],
[ 'Represent the Financial statement: ' , 'The Federal Reserve on Wednesday raised its benchmark interest rate.' ]]
sentences_b = [[ 'Represent the Science sentence: ' , 'The Chiral Phase Transition in Dissipative Dynamics' ],
[ 'Represent the Financial statement: ' , 'The funds rose less than 0.5 per cent on Friday' ]]
embeddings_a = model . encode ( sentences_a )
embeddings_b = model . encode ( sentences_b )
similarities = cosine_similarity ( embeddings_a , embeddings_b )
import numpy as np
from sklearn . metrics . pairwise import cosine_similarity
query = [[ 'Represent the Wikipedia question for retrieving supporting documents: ' , 'where is the food stored in a yam plant' ]]
corpus = [[ 'Represent the Wikipedia document for retrieval: ' , 'Capitalism has been dominant in the Western world since the end of feudalism, but most feel[who?] that the term "mixed economies" more precisely describes most contemporary economies, due to their containing both private-owned and state-owned enterprises. In capitalism, prices determine the demand-supply scale. For example, higher demand for certain goods and services lead to higher prices and lower demand for certain goods lead to lower prices.' ],
[ 'Represent the Wikipedia document for retrieval: ' , "The disparate impact theory is especially controversial under the Fair Housing Act because the Act regulates many activities relating to housing, insurance, and mortgage loans—and some scholars have argued that the theory's use under the Fair Housing Act, combined with extensions of the Community Reinvestment Act, contributed to rise of sub-prime lending and the crash of the U.S. housing market and ensuing global economic recession" ],
[ 'Represent the Wikipedia document for retrieval: ' , 'Disparate impact in United States labor law refers to practices in employment, housing, and other areas that adversely affect one group of people of a protected characteristic more than another, even though rules applied by employers or landlords are formally neutral. Although the protected classes vary by statute, most federal civil rights laws protect based on race, color, religion, national origin, and sex as protected traits, and some laws include disability status and other traits as well.' ]]
query_embeddings = model . encode ( query )
corpus_embeddings = model . encode ( corpus )
similarities = cosine_similarity ( query_embeddings , corpus_embeddings )
retrieved_doc_id = np . argmax ( similarities )
print ( retrieved_doc_id )
import sklearn . cluster
sentences = [[ 'Represent the Medicine sentence for clustering: ' , 'Dynamical Scalar Degree of Freedom in Horava-Lifshitz Gravity' ],
[ 'Represent the Medicine sentence for clustering: ' , 'Comparison of Atmospheric Neutrino Flux Calculations at Low Energies' ],
[ 'Represent the Medicine sentence for clustering: ' , 'Fermion Bags in the Massive Gross-Neveu Model' ],
[ 'Represent the Medicine sentence for clustering: ' , "QCD corrections to Associated t-tbar-H production at the Tevatron" ],
[ 'Represent the Medicine sentence for clustering: ' , 'A New Analysis of the R Measurements: Resonance Parameters of the Higher, Vector States of Charmonium' ]]
embeddings = model . encode ( sentences )
clustering_model = sklearn . cluster . MiniBatchKMeans ( n_clusters = 2 )
clustering_model . fit ( embeddings )
cluster_assignment = clustering_model . labels_
print ( cluster_assignment )
우리는 Super-NI(Super-NaturalInstructions), 문장 변환기 임베딩 훈련 데이터, KILT 및 MedMCQA의 330개 데이터세트 컬렉션으로 구성된 MEDI(Multitask Embeddings Data with Instructions)를 구성하며 광범위한 도메인과 작업을 포괄합니다. 제공되지 않은 경우 양수 및 음수 쌍을 구성하고 이를 통합된 형식으로 저장합니다.
[
{'query': ['Represent the Wikipedia question for retrieving relevant documents;', 'big little lies season 2 how many episodes'], 'pos': ['Represent the Wikipedia document for retrieval;', 'Big Little Lies (TV series) series garnered several accolades. It received 16 Emmy Award nominations and won eight, including Outstanding Limited Series and acting awards for Kidman, Skarsgård, and Dern. The trio also won Golden Globe Awards in addition to a Golden Globe Award for Best Miniseries or Television Film win for the series. Kidman and Skarsgård also received Screen Actors Guild Awards for their performances. Despite originally being billed as a miniseries, HBO renewed the series for a second season. Production on the second season began in March 2018 and is set to premiere in 2019. All seven episodes are being written by Kelley'], 'neg': ['Represent the Wikipedia document for retrieval;', 'Little People, Big World final minutes of the season two-A finale, "Farm Overload". A crowd had gathered around Jacob, who was lying on the ground near the trebuchet. The first two episodes of season two-B focus on the accident, and how the local media reacted to it. The first season of "Little People, Big World" generated solid ratings for TLC (especially in the important 18–49 demographic), leading to the show's renewal for a second season. Critical reviews of the series have been generally positive, citing the show's positive portrayal of little people. Conversely, other reviews have claimed that the show has a voyeuristic bend'], 'task_id': 1}
{'query': ['Represent the Wikipedia question for retrieving relevant documents;', 'who sang waiting for a girl like you'], 'pos': ['Represent the Wikipedia document for retrieval;', 'Waiting for a Girl Like You Waiting for a Girl Like You "Waiting for a Girl Like You" is a 1981 power ballad by the British-American rock band Foreigner. The distinctive synthesizer theme was performed by the then-little-known Thomas Dolby, and this song also marked a major departure from their earlier singles because their previous singles were mid to upper tempo rock songs while this song was a softer love song with the energy of a power ballad. It was the second single released from the album "4" (1981) and was co-written by Lou Gramm and Mick Jones. It has become one of the band's most'], 'neg': ['Represent the Wikipedia document for retrieval;', 'Waiting for a Girl Like You held off the number 1 spot by Olivia Newton-John's single "Physical" for nine consecutive weeks, and then by Hall & Oates' "I Can't Go for That (No Can Do)" for a tenth week on January 30, 1982. Because of its chart longevity, it ended up being the number 19 song on the Top 100 singles of 1982. The song was the band's biggest hit until "I Want to Know What Love Is" hit number 1 in 1985. The song lists at number 100 on ""Billboard"'s Greatest Songs of All Time". Waiting for a Girl Like You "Waiting for a Girl'], 'task_id': 1}
...
{'query': ['Represent the Wikipedia sentence for retrieving relevant documents;', 'i LOVE sweet martini drinks!'], 'pos': ['Represent the Wikipedia document for retrieval;', "Appletini AppletininAn Apple martini (Appletini for short) is a cocktail containing vodka and one or more of apple juice, apple cider, apple liqueur, or apple brandy.nThis drink, originally called an Adam's Apple Martini because the bartender who created it was named Adam, was created in 1996 at Lola's West Hollywood restaurant.nThe drink, Adam's Apple was advertised by Smirnoff in the July 1972 issue of Playboy Magazine to the inside front cover. The recipe called for an ounce or so of Smirnoff"], 'neg': ['Represent the Wikipedia document for retrieval;', "Aromatised wine similar beverages described in this legislation are 'aromatised wine-based drinks' (non-fortified) and 'aromatised wine-product cocktail' (blended, lower alcohol drink under 7% ABV).nVarieties of aromatised wine.nVarieties of aromatised wine Vermouth.nVermouth is the most widely used aromatised wine due to its use in cocktails and famous commercial brands such as Martini and Cinzano which are commonplace around the world. Vermouth can be sweet or dry and red, white, pink or orange. It is traditionally"], 'task_id': 300}
]
각 인스턴스는 쿼리, 양수 쌍, 음수 쌍 및 작업 ID로 구성됩니다. 이는 동일한 교육 배치의 데이터가 동일한 작업에서 나온 것인지 확인하는 데 사용됩니다. MEDI 데이터는 이 링크에서 다운로드할 수 있습니다.
INSTRUCTOR 교육을 위한 예제 스크립트를 제공합니다. 먼저 MEDI 데이터를 다운로드하고 폴더의 압축을 풀고 medi-data.json
--cache_dir
아래에 넣어야 할 수도 있습니다.
python train . py - - model_name_or_path sentence - transformers / gtr - t5 - large - - output_dir { output_directory } - - cache_dir { cache_directory } - - max_source_length 512 - - num_train_epochs 10 - - save_steps 500 - - cl_temperature 0.1 - - warmup_ratio 0.1 - - learning_rate 2e-5 - - overwrite_output_dir
우리는 다음과 같은 주장을 설명합니다.
--model_name_or_path
: 시작할 사전 학습된 체크포인트입니다. 모델 ID(예: sentence-transformers/gtr-t5-large
, sentence-transformers/sentence-t5-large
) 또는 체크포인트 경로(예: 변환기 트레이너가 저장한 체크포인트)를 모두 지원합니다.--cl_temperature
: 대조 손실 온도--cache_dir
: 다운로드한 모델과 데이터를 캐시하는 디렉터리입니다. 다운로드한 MEDI 데이터( medi-data.json
)는 --cache_dir
디렉터리에 있어야 합니다.--output_dir
: 평가를 위해 훈련된 모델(체크포인트)을 저장할 디렉터리입니다. 다른 모든 인수는 --overwrite_output_dir
, --num_train_epochs
, --learning_rate
와 같은 표준 Huggingface's transformers
훈련 인수입니다. 자세한 내용은 Huggingface 변환기를 참조하세요.
우리는 광범위한 작업과 영역에 걸쳐 70가지 다양한 작업에 대해 INSTRUCTOR를 대규모로 평가합니다. 특히 MTEB, Billboard 및 Prompt Retrieval의 세 가지 벤치마크를 기준으로 평가를 진행합니다. 평가 스크립트 실행에 대한 자세한 내용은 다음에서 설명합니다.
MTEB 벤치마크 데이터 세트에서 모델 성능을 평가하려면 먼저 MTEB 라이브러리를 설치하십시오.
cd evaluation / MTEB
pip install - e .
그런 다음 다음 명령을 실행하십시오.
python examples / evaluate_model . py - - model_name hkunlp / instructor - large - - output_dir outputs - - task_name ArguAna - - result_file results
--model_name
지정하여 학습된 모델 체크포인트를 평가하고 --task_name
변경하여 모든 MTEB 데이터 세트를 실행할 수 있습니다. 모든 작업의 평가 지표는 당사의 논문이나 MTEB 벤치마크를 확인하세요.
Billboard에서 모델 성능을 평가하려면 다음 명령을 실행하십시오.
cd evaluation / text_evaluation
python main . py - - model_name hkunlp / instructor - large - - task mscoco - - add_prompt
--model_name
지정하여 학습된 모델 체크포인트를 평가하고 --task
변경하여 모든 Billboard 데이터 세트를 실행할 수 있습니다. Billboard의 세 가지 데이터 세트 모두에서 Pearson 상관 관계를 보고합니다.
프롬프트 검색에서 모델 성능을 평가하려면 다음 명령을 실행하십시오.
cd evaluation / prompt_retrieval
python main . py - - embedding_model hkunlp / instructor - large - - task rte - - model_cache_dir { cache_dir } - - output_dir { output_dir } - - add_prompt
--model_name
지정하여 학습된 모델 체크포인트를 평가하고 --task
변경하여 프롬프트 검색 데이터 세트를 실행할 수 있습니다. 일관된 측정항목을 갖기 위해 프롬프트 검색의 모든 작업을 "텍스트 대 텍스트" 형식으로 변환하고 Rouge-L 점수를 보고합니다.
instructor embedding 모델을 양자화 하려면 다음 코드를 실행하세요.
# imports
import torch
from InstructorEmbedding import INSTRUCTOR
# load the model
model = INSTRUCTOR ( 'hkunlp/instructor-large' , device = 'cpu' ) # you can use GPU
# quantize the model
qmodel = torch . quantization . quantize_dynamic (
model , { torch . nn . Linear }, dtype = torch . qint8 )
# Inference
sentence = "3D ActionSLAM: wearable person tracking in multi-floor environments"
instruction = "Represent the Science title:"
embeddings = qmodel . encode ([[ instruction , sentence ]])
# you can also normalize the embeddings: normalize_embeddings=True
print ( f"Quantized Embeddings: n { embeddings } " )
모델 크기를 10배로 줄여 추론 시간도 일반 모델보다 단축됩니다 :)
코드나 논문과 관련하여 질문이 있으시면 언제든지 Hongjin ( [email protected]
) 및 Weijia ( [email protected]
)에게 이메일을 보내주십시오. 더 빠르고 효과적으로 도움을 드릴 수 있도록 문제를 세부적으로 명시해 주시기 바랍니다.
우리의 작업이 도움이 되었다고 생각하시면 다음 내용을 인용해 주세요.
@inproceedings { INSTRUCTOR ,
title = { One Embedder, Any Task: Instruction-Finetuned Text Embeddings } ,
author = { Su, Hongjin and Shi, Weijia and Kasai, Jungo and Wang, Yizhong and Hu, Yushi and Ostendorf, Mari and Yih, Wen-tau and Smith, Noah A. and Zettlemoyer, Luke and Yu, Tao } ,
url = { https://arxiv.org/abs/2212.09741 } ,
year = { 2022 } ,
}
INSTRUCTOR 확장을 위한 커뮤니티의 노력에 감사드립니다!
InstructorTextEmbedder
및 InstructorDocumentEmbedder
구성 요소가 포함되어 있습니다.