Dies ist eine Abzweigung für das Instructor-Modell, da das ursprüngliche Repository nicht mehr beibehalten wird. Ich habe auch einige Verbesserungen an ihrem Quellcode vorgenommen:
sentence-transformers
Bibliothek über 2.2.2 funktioniert.Dieses Repository enthält den Code und vorab trainierte Modelle für unseren Artikel One Embedder, Any Task: Instruction-Finetuned Text Embeddings. Eine schnelle Projektübersicht finden Sie auf unserer Projektseite.
Wir stellen Instructor ?? vor, ein auf Anweisungen abgestimmtes Texteinbettungsmodell, das Texteinbettungen generieren kann, die auf jede Aufgabe (z. B. Klassifizierung, Abruf, Clustering, Textauswertung usw.) und Domänen (z. B. Wissenschaft, Finanzen usw.) zugeschnitten sind. durch einfaches Bereitstellen der Aufgabenanweisung, ohne Feinabstimmung . Lehrer? erreicht sota bei 70 verschiedenen Einbettungsaufgaben!
************************** Aktualisierungen ********************* *******
encode
Es ist sehr einfach, INSTRUCTOR für alle Texteinbettungen zu verwenden. Sie können es ganz einfach im Colab-Notizbuch ausprobieren. Wir empfehlen, auf Ihrem lokalen Rechner zunächst eine virtuelle Umgebung zu erstellen:
conda env create -n instructor python=3.7
git clone https://github.com/HKUNLP/instructor-embedding
pip install -r requirements.txt
Dadurch wird der instructor
erstellt, den wir verwendet haben. Um das Einbettungstool zu verwenden, installieren Sie zunächst das InstructorEmbedding
Paket von PyPI
pip install InstructorEmbedding
oder installieren Sie es direkt aus unserem Code
pip install -e .
Aktivieren Sie die Umgebung durch Ausführen
conda activate instructor
Laden Sie zunächst ein vorab trainiertes Modell herunter (eine vollständige Liste der verfügbaren Modelle finden Sie in der Modellliste).
from InstructorEmbedding import INSTRUCTOR
model = INSTRUCTOR ( 'hkunlp/instructor-large' )
Geben Sie dann dem Modell den Satz und die individuelle Anweisung.
# 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 )
Und das ist es schon. Wir haben jetzt eine Liste von Numpy-Arrays mit den Einbettungen.
for pair , embedding in zip ( text_instruction_pairs , customized_embeddings ):
print ( "Instruction: " , pair [ "instruction" ])
print ( "text: " , pair [ "text" ])
print ( "Embedding: " , embedding )
print ( "" )
encode
Die Benutzer des Modells müssen nur die encode
verwenden:
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
: Die einzubettenden Sätze. Es sollte das Format [["instruction prompt 0", "text to be embedded 0], ["instruction prompt 1", "text to be embedded 1], ...]
haben.batch_size
(Standard: 32): Die für die Berechnung verwendete Batch-Größe. Es bestimmt die Anzahl der Sätze, die in jedem Stapel zusammen verarbeitet werden.show_progress_bar
(Standard: Keine): Wenn auf True
gesetzt, wird beim Codieren von Sätzen ein Fortschrittsbalken angezeigt, der eine visuelle Anzeige des Codierungsfortschritts bietet.output_value
(Standard: 'sentence_embedding'): Gibt den gewünschten Ausgabetyp an. Der Standardwert „sentence_embedding“ gibt Satzeinbettungen zurück. Wenn Sie es auf „token_embeddings“ setzen, werden Wordpiece-Token-Einbettungen zurückgegeben. Wenn Sie es auf „Keine“ setzen, werden alle Ausgabewerte zurückgegeben.convert_to_numpy
(Standard: True
): Wenn auf True
gesetzt, ist die Ausgabe eine Liste von Numpy-Vektoren. Bei Festlegung auf False
ist die Ausgabe eine Liste von PyTorch-Tensoren.convert_to_tensor
(Standard: False
): Wenn auf True
gesetzt, gibt die Funktion einen gestapelten Tensor als einzelne Ausgabe zurück. Dieser Parameter überschreibt alle durch convert_to_numpy
angegebenen Einstellungen.device
(Standard: Keine): Gibt das für die Berechnung zu verwendende Torch-Gerät an. Wenn nicht angegeben, verwendet die Funktion das Standardgerät.normalize_embeddings
(Standard: False
): Wenn auf True
gesetzt, haben die zurückgegebenen Vektoren eine Länge von 1, was darauf hinweist, dass sie normalisiert sind. In diesem Fall würde die Ähnlichkeitssuche das schnellere Skalarprodukt ( util.dot_score
) anstelle der Kosinusähnlichkeit verwenden. Wir haben eine Reihe von INSTRUCTOR-Kontrollpunkten mit unterschiedlichen Größen herausgebracht. Sie können diese Modelle einfach mit InstructorEmbedding
Paket laden.
Modell | Durchschn. Punktzahl |
---|---|
hkunlp/instructor-base | 55.9 |
hkunlp/instructor-large | 58.4 |
hkunlp/instructor-xl | 58,8 |
Im Folgenden stellen wir einige konkrete Anwendungsfälle vor. Weitere Beispiele und Anwendungen finden Sie in unserem Dokument
Wenn Sie benutzerdefinierte Einbettungen für bestimmte Sätze berechnen möchten, können Sie der einheitlichen Vorlage folgen, um Anweisungen zu schreiben:
Stellen Sie die domain
text_type
für task_objective
dar:
domain
ist optional und gibt die Domäne des Textes an, z. B. Wissenschaft, Finanzen, Medizin usw.text_type
ist erforderlich und gibt die Kodierungseinheit an, z. B. Satz, Dokument, Absatz usw.task_objective
ist optional und gibt das Ziel der Einbettung an, z. B. das Abrufen eines Dokuments, das Klassifizieren des Satzes usw.Mit INSTRUCTOR können Sie Ähnlichkeiten zwischen zwei Satzgruppen mit benutzerdefinierten Einbettungen berechnen.
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 )
Wir erstellen Multitask Embeddings Data with Instructions (MEDI), bestehend aus einer Sammlung von 330 Datensätzen von Super-NI (Super-NaturalInstructions), Satztransformator-Einbettungstrainingsdaten, KILT und MedMCQA, die ein breites Spektrum an Bereichen und Aufgaben abdecken. Wir konstruieren positive und negative Paare, wenn sie nicht bereitgestellt werden, und speichern sie in einem einheitlichen Format:
[
{'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}
]
Jede Instanz besteht aus einer Abfrage, einem positiven Paar, einem negativen Paar und der ID der Aufgabe, die verwendet wird, um sicherzustellen, dass Daten im selben Trainingsbatch von derselben Aufgabe stammen. Die MEDI-Daten können unter diesem Link heruntergeladen werden.
Wir stellen das Beispielskript für die Schulung von INSTRUCTOR zur Verfügung. Möglicherweise müssen Sie zuerst die MEDI-Daten herunterladen, den Ordner entpacken und medi-data.json
unter --cache_dir
ablegen.
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
Wir erläutern die Argumente im Folgenden:
--model_name_or_path
: Vorab trainierte Prüfpunkte für den Anfang. Wir unterstützen sowohl Modell-IDs (z. B. sentence-transformers/gtr-t5-large
, sentence-transformers/sentence-t5-large
) als auch Prüfpunktpfade (z. B. vom Transformers-Trainer gespeicherter Prüfpunkt).--cl_temperature
: Temperatur für Kontrastverlust--cache_dir
: Das Verzeichnis zum Zwischenspeichern heruntergeladener Modelle und Daten. Die heruntergeladenen MEDI-Daten ( medi-data.json
) sollten im Verzeichnis --cache_dir
abgelegt werden.--output_dir
: Das Verzeichnis zum Speichern der trainierten Modelle (Prüfpunkte) zur Auswertung. Alle anderen Argumente sind standardmäßige Huggingface's transformers
Trainingsargumente, wie zum Beispiel --overwrite_output_dir
, --num_train_epochs
, --learning_rate
. Einzelheiten finden Sie unter Huggingface-Transformatoren
Wir bewerten den INSTRUCTOR umfassend anhand von 70 verschiedenen Aufgaben, die ein breites Spektrum an Aufgaben und Bereichen abdecken. Konkret bauen wir unsere Bewertung auf drei Benchmarks auf: MTEB, Billboard und Prompt Retrieval. Im Folgenden erläutern wir die Details zum Ausführen von Evaluierungsskripten.
Um die Modellleistung im MTEB-Benchmark-Datensatz zu bewerten, installieren Sie zunächst die MTEB-Bibliothek
cd evaluation / MTEB
pip install - e .
Führen Sie dann den folgenden Befehl aus:
python examples / evaluate_model . py - - model_name hkunlp / instructor - large - - output_dir outputs - - task_name ArguAna - - result_file results
Sie können die Prüfpunkte Ihres trainierten Modells auswerten, indem Sie --model_name
angeben und alle MTEB-Datensätze ausführen, indem Sie --task_name
ändern. Sehen Sie sich unser Papier oder den MTEB-Benchmark für Bewertungsmetriken aller Aufgaben an.
Führen Sie den folgenden Befehl aus, um die Modellleistung auf Billboard zu bewerten:
cd evaluation / text_evaluation
python main . py - - model_name hkunlp / instructor - large - - task mscoco - - add_prompt
Sie können die Prüfpunkte Ihres trainierten Modells auswerten, indem Sie --model_name
angeben und alle Billboard-Datensätze ausführen, indem Sie --task
ändern. In allen drei Datensätzen in Billboard berichten wir über die Pearson-Korrelation.
Führen Sie den folgenden Befehl aus, um die Modellleistung beim Prompt Retrieval zu bewerten:
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
Sie können die Prüfpunkte Ihres trainierten Modells auswerten, indem Sie --model_name
angeben, und Eingabeaufforderungsabrufdatensätze ausführen, indem Sie --task
ändern. Um eine konsistente Metrik zu erhalten, wandeln wir alle Aufgaben im Prompt Retrieval in ein „Text-zu-Text“-Format um und geben den Rouge-L-Score an.
Führen Sie den folgenden Code aus, um das instructor embedding zu quantisieren :
# 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 } " )
Es reduziert die Modellgröße um das Zehnfache und die Inferenzzeit ist kürzer als beim normalen Modell :)
Wenn Sie Fragen zum Code oder zum Papier haben, senden Sie bitte eine E-Mail an Hongjin ( [email protected]
) und Weijia ( [email protected]
). Versuchen Sie bitte, das Problem detailliert zu beschreiben, damit wir Ihnen besser und schneller helfen können.
Wenn Sie unsere Arbeit hilfreich finden, zitieren Sie uns bitte:
@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 } ,
}
Wir danken der Community für die Erweiterung von INSTRUCTOR!
InstructorTextEmbedder
und InstructorDocumentEmbedder
.