元のリポジトリがもう維持されていないため、これは Instructor モデルのフォークです。また、ソース コードにもいくつかの改良を加えました。
sentence-transformers
ライブラリで動作するように修正しました。このリポジトリには、論文「One Embedder, Any Task: struction-finetuned Text Embeddings」のコードと事前トレーニングされたモデルが含まれています。プロジェクトの概要については、プロジェクト ページを参照してください。
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
(デフォルト: None): 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
(デフォルト: なし): 計算に使用する 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 を使用すると、カスタマイズされた埋め込みを使用して 2 つの文グループ間の類似性を計算できます。
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-Naturalstructions)、文変換埋め込みトレーニング データ、KILT、MedMCQA からの 330 個のデータセットのコレクションで構成され、広範囲のドメインとタスクにまたがる Multitask Embeddings Data with Instructions (MEDI) を構築します。正と負のペアが提供されていない場合はそれらを構築し、統一された形式で保存します。
[
{'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
) またはチェックポイント パス (例えば、transformers トレーナーによって保存されたチェックポイント) の両方をサポートします。--cl_temperature
: コントラスト損失の温度--cache_dir
: ダウンロードされたモデルとデータをキャッシュするディレクトリ。ダウンロードした MEDI データ ( medi-data.json
) は、ディレクトリ--cache_dir
の下に配置する必要があります。--output_dir
: 評価用にトレーニングされたモデル (チェックポイント) を保存するディレクトリ。他のすべての引数は、 --overwrite_output_dir
、 --num_train_epochs
、 --learning_rate
など、標準のHuggingface's transformers
トレーニング引数です。詳細については、ハギングフェイストランスフォーマーを参照してください。
私たちは、幅広いタスクと領域にわたる 70 の多様なタスクに関して INSTRUCTOR を大規模に評価します。具体的には、MTEB、Billboard、Prompt Retrieval の 3 つのベンチマークに基づいて評価を構築します。評価スクリプトの実行については、以下で詳しく説明します。
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 の 3 つのデータセットすべてで、ピアソン相関を報告します。
プロンプト取得でのモデルのパフォーマンスを評価するには、次のコマンドを実行します。
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 分の 1 に削減され、推論時間は通常のモデルよりも短くなります :)
コードまたは論文に関する質問がある場合は、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
コンポーネントが含まれています。