Rust 기반의 최첨단 자연어 처리 모델 및 파이프라인. tch-rs 또는 onnxruntime 바인딩을 사용하고 Rust-tokenizer에서 사전 처리하는 Hugging Face의 Transformers 라이브러리 포트입니다. 멀티스레드 토큰화 및 GPU 추론을 지원합니다. 이 저장소는 모델 기반 아키텍처, 작업별 헤드(아래 참조) 및 즉시 사용 가능한 파이프라인을 노출합니다. 벤치마크는 이 문서의 끝부분에서 확인할 수 있습니다.
단 몇 줄의 코드만으로 질문 응답, 명명된 엔터티 인식, 번역, 요약, 텍스트 생성, 대화 에이전트 등을 포함한 작업을 시작하세요.
let qa_model = QuestionAnsweringModel :: new ( Default :: default ( ) ) ? ;
let question = String :: from ( "Where does Amy live ?" ) ;
let context = String :: from ( "Amy lives in Amsterdam" ) ;
let answers = qa_model . predict ( & [ QaInput { question , context } ] , 1 , 32 ) ;
산출:
[Answer { score: 0.9976, start: 13, end: 21, answer: "Amsterdam" }]
현재 지원되는 작업은 다음과 같습니다.
서열 분류 | 토큰 분류 | 질문 답변 | 텍스트 생성 | 요약 | 번역 | 마스크드 LM | 문장 임베딩 | |
---|---|---|---|---|---|---|---|---|
디스틸버트 | ✅ | ✅ | ✅ | ✅ | ✅ | |||
모바일BERT | ✅ | ✅ | ✅ | ✅ | ||||
데버타 | ✅ | ✅ | ✅ | ✅ | ||||
데버타(v2) | ✅ | ✅ | ✅ | ✅ | ||||
에프넷 | ✅ | ✅ | ✅ | ✅ | ||||
버트 | ✅ | ✅ | ✅ | ✅ | ✅ | |||
로베르타 | ✅ | ✅ | ✅ | ✅ | ✅ | |||
GPT | ✅ | |||||||
GPT2 | ✅ | |||||||
GPT-네오 | ✅ | |||||||
GPT-J | ✅ | |||||||
바트 | ✅ | ✅ | ✅ | |||||
마리안 | ✅ | |||||||
엠바트 | ✅ | ✅ | ||||||
M2M100 | ✅ | |||||||
NLLB | ✅ | |||||||
엘렉트라 | ✅ | ✅ | ||||||
알버트 | ✅ | ✅ | ✅ | ✅ | ✅ | |||
T5 | ✅ | ✅ | ✅ | ✅ | ||||
롱T5 | ✅ | ✅ | ||||||
XLNet | ✅ | ✅ | ✅ | ✅ | ✅ | |||
개혁가 | ✅ | ✅ | ✅ | ✅ | ||||
프로핏넷 | ✅ | ✅ | ||||||
롱포머 | ✅ | ✅ | ✅ | ✅ | ||||
페가수스 | ✅ |
이 라이브러리는 C++ Libtorch API에 바인딩하기 위해 tch 크레이트를 사용합니다. libtorch 라이브러리가 필요하며 자동 또는 수동으로 다운로드할 수 있습니다. 다음은 이러한 바인딩을 사용하기 위해 환경을 설정하는 방법에 대한 참조를 제공합니다. 자세한 정보나 지원은 tch를 참조하세요.
또한 이 라이브러리는 사전 훈련된 모델을 다운로드하기 위해 캐시 폴더를 사용합니다. 이 캐시 위치의 기본값은 ~/.cache/.rustbert
이지만 RUSTBERT_CACHE
환경 변수를 설정하여 변경할 수 있습니다. 이 라이브러리에서 사용되는 언어 모델은 수백 MB에서 GB 단위입니다.
libtorch
다운로드하세요. 이 패키지에는 v2.4
필요합니다. "시작하기" 페이지에서 이 버전을 더 이상 사용할 수 없는 경우 대상 링크를 수정하여 파일에 액세스할 수 있어야 합니다(예: https://download.pytorch.org/libtorch/cu124/libtorch-cxx11-abi-shared-with-deps-2.4.0%2Bcu124.zip
). CUDA12가 포함된 Linux 버전의 경우 https://download.pytorch.org/libtorch/cu124/libtorch-cxx11-abi-shared-with-deps-2.4.0%2Bcu124.zip
. 참고: rust-bert
crates.io의 종속성으로 사용하는 경우 여기에 설명된 버전(현재 저장소 버전에 적용)과 다를 수 있으므로 게시된 패키지 readme에서 필수 LIBTORCH
확인하세요. export LIBTORCH=/path/to/libtorch
export LD_LIBRARY_PATH= ${LIBTORCH} /lib: $LD_LIBRARY_PATH
$ Env: LIBTORCH = " X:pathtolibtorch "
$ Env: Path += " ;X:pathtolibtorchlib "
brew install pytorch jq
export LIBTORCH= $( brew --cellar pytorch ) / $( brew info --json pytorch | jq -r ' .[0].installed[0].version ' )
export LD_LIBRARY_PATH= ${LIBTORCH} /lib: $LD_LIBRARY_PATH
또는 build
스크립트가 자동으로 libtorch
라이브러리를 다운로드하도록 할 수 있습니다. download-libtorch
기능 플래그를 활성화해야 합니다. libtorch의 CPU 버전이 기본적으로 다운로드됩니다. CUDA 버전을 다운로드하려면 환경 변수 TORCH_CUDA_VERSION
cu124
로 설정하세요. libtorch 라이브러리는 크기가 크므로(CUDA 지원 버전의 경우 몇 GB 정도) 첫 번째 빌드를 완료하는 데 몇 분이 걸릴 수 있습니다.
Cargo.toml
에 rust-bert
종속성을 추가하거나 Rust-bert 소스를 복제하고 예제를 실행하여 설치(및 libtorch와의 연결)를 확인하세요.
git clone [email protected]:guillaume-be/rust-bert.git
cd rust-bert
cargo run --example sentence_embeddings
ONNX 지원은 선택적 onnx
기능을 통해 활성화할 수 있습니다. 그런 다음 이 크레이트는 onnxruntime C++ 라이브러리에 대한 바인딩과 함께 ort 크레이트를 활용합니다. 추가 설치 지침/지원을 위해 사용자에게 이 페이지 프로젝트를 안내합니다.
onnx
기능을 활성화합니다. rust-bert
크레이트에는 ort
에 대한 선택적 종속성이 포함되어 있지 않으므로 최종 사용자는 필수 onnxruntime
C++ 라이브러리를 가져오는 데 적합한 기능 세트를 선택해야 합니다.ort
에 load-dynamic
화물 기능을 사용하세요.onnxruntime.dll
/ libonnxruntime.so
/ libonnxruntime.dylib
)의 위치를 가리키도록 ORT_DYLIB_PATH
를 설정합니다. onnxruntime 프로젝트의 릴리스 페이지에서 다운로드할 수 있습니다.대부분의 아키텍처(인코더, 디코더 및 인코더-디코더 포함)가 지원됩니다. 라이브러리는 Optimum 라이브러리를 사용하여 내보낸 모델과의 호환성을 유지하는 것을 목표로 합니다. Optimum을 사용하여 Transformer 모델을 ONNX로 내보내는 방법에 대한 자세한 가이드는 https://huggingface.co/docs/optimum/main/en/exporters/onnx/usage_guides/export_a_model에서 확인할 수 있습니다. ONNX 모델을 생성하는 데 사용된 리소스는 다음과 유사합니다. Pytorch를 기반으로 하는 모델로 pytorch를 ONNX 모델로 대체합니다. ONNX 모델은 선택적 인수 처리에 있어 Pytorch 모델보다 유연성이 떨어지기 때문에 디코더 또는 인코더-디코더 모델을 ONNX로 내보내면 일반적으로 여러 파일이 생성됩니다. 아래 표에 따라 이 파일은 이 라이브러리에서 사용하기 위해 필요하지만 모두 필요한 것은 아닙니다.
건축학 | 인코더 파일 | 과거 파일이 없는 디코더 | 과거 파일이 포함된 디코더 |
---|---|---|---|
인코더(예: BERT) | 필수의 | 사용되지 않음 | 사용되지 않음 |
디코더(예: GPT2) | 사용되지 않음 | 필수의 | 선택 과목 |
인코더-디코더(예: BART) | 필수의 | 필수의 | 선택 과목 |
decoder with past
선택 사항이지만 제공되지 않는 경우 모델이 주의 메커니즘에 대해 캐시된 과거 키와 값을 사용하지 않아 중복 계산 수가 많아지므로 계산 효율성이 떨어집니다. Optimum 라이브러리는 decoder with past
생성되도록 내보내기 옵션을 제공합니다. 기본 인코더 및 디코더 모델 아키텍처는 각각 encoder
및 decoder
모듈에서 사용 가능하고 편의상 노출됩니다.
생성 모델(순수 디코더 또는 인코더/디코더 아키텍처)은 models
모듈에서 사용할 수 있습니다. ost 파이프라인은 시퀀스 분류, 제로샷 분류, 토큰 분류(명명된 엔터티 인식 및 품사 태깅 포함), 질문 응답, 텍스트 생성, 요약 및 번역을 포함한 ONNX 모델 체크포인트에 사용할 수 있습니다. 이러한 모델은 파이프라인에서 사용될 때 Pytorch 대응 모델과 동일한 구성 및 토크나이저 파일을 사용합니다. ONNX 모델을 활용하는 예제는 ./examples
디렉터리에 제공됩니다.
Hugging Face의 파이프라인을 기반으로 즉시 사용 가능한 엔드투엔드 NLP 파이프라인을 이 상자의 일부로 사용할 수 있습니다. 현재 다음 기능을 사용할 수 있습니다.
면책조항 이 저장소의 기여자는 여기에 제안된 사전 훈련된 시스템의 제3자 활용으로 인한 생성에 대해 책임을 지지 않습니다.
주어진 질문과 맥락에서 추출적인 질문 답변. SQuAD(Stanford Question Answering Dataset)에서 미세 조정된 DistilBERT 모델
let qa_model = QuestionAnsweringModel :: new ( Default :: default ( ) ) ? ;
let question = String :: from ( "Where does Amy live ?" ) ;
let context = String :: from ( "Amy lives in Amsterdam" ) ;
let answers = qa_model . predict ( & [ QaInput { question , context } ] , 1 , 32 ) ;
산출:
[Answer { score: 0.9976, start: 13, end: 21, answer: "Amsterdam" }]
광범위한 소스 및 타겟 언어를 지원하는 번역 파이프라인. 번역 작업에 두 가지 주요 아키텍처를 활용합니다.
다음 언어 쌍에 대한 Marian 기반 사전 학습 모델은 라이브러리에서 쉽게 사용할 수 있지만 사용자는 예측을 위해 Pytorch 기반 모델을 가져올 수 있습니다.
제안된 사전 훈련된 Marian 모델이 지원하지 않는 언어의 경우 사용자는 100개 언어 간 직접 번역을 지원하는 M2M100 모델을 활용할 수 있습니다(중간 영어 번역 없음). 지원되는 언어의 전체 목록은 크레이트 문서에서 확인할 수 있습니다.
use rust_bert :: pipelines :: translation :: { Language , TranslationModelBuilder } ;
fn main ( ) -> anyhow :: Result < ( ) > {
let model = TranslationModelBuilder :: new ( )
. with_source_languages ( vec ! [ Language :: English ] )
. with_target_languages ( vec ! [ Language :: Spanish , Language :: French , Language :: Italian ] )
. create_model ( ) ? ;
let input_text = "This is a sentence to be translated" ;
let output = model . translate ( & [ input_text ] , None , Language :: French ) ? ;
for sentence in output {
println ! ( "{}" , sentence ) ;
}
Ok ( ( ) )
}
산출:
Il s'agit d'une phrase à traduire
사전 학습된 BART 모델을 사용한 추상적인 요약입니다.
let summarization_model = SummarizationModel :: new ( Default :: default ( ) ) ? ;
let input = [ "In findings published Tuesday in Cornell University's arXiv by a team of scientists
from the University of Montreal and a separate report published Wednesday in Nature Astronomy by a team
from University College London (UCL), the presence of water vapour was confirmed in the atmosphere of K2-18b,
a planet circling a star in the constellation Leo. This is the first such discovery in a planet in its star's
habitable zone — not too hot and not too cold for liquid water to exist. The Montreal team, led by Björn Benneke,
used data from the NASA's Hubble telescope to assess changes in the light coming from K2-18b's star as the planet
passed between it and Earth. They found that certain wavelengths of light, which are usually absorbed by water,
weakened when the planet was in the way, indicating not only does K2-18b have an atmosphere, but the atmosphere
contains water in vapour form. The team from UCL then analyzed the Montreal team's data using their own software
and confirmed their conclusion. This was not the first time scientists have found signs of water on an exoplanet,
but previous discoveries were made on planets with high temperatures or other pronounced differences from Earth.
" This is the first potentially habitable planet where the temperature is right and where we now know there is water, "
said UCL astronomer Angelos Tsiaras. " It's the best candidate for habitability right now. " " It's a good sign " ,
said Ryan Cloutier of the Harvard–Smithsonian Center for Astrophysics, who was not one of either study's authors.
" Overall, " he continued, " the presence of water in its atmosphere certainly improves the prospect of K2-18b being
a potentially habitable planet, but further observations will be required to say for sure. "
K2-18b was first identified in 2015 by the Kepler space telescope. It is about 110 light-years from Earth and larger
but less dense. Its star, a red dwarf, is cooler than the Sun, but the planet's orbit is much closer, such that a year
on K2-18b lasts 33 Earth days. According to The Guardian, astronomers were optimistic that NASA's James Webb space
telescope — scheduled for launch in 2021 — and the European Space Agency's 2028 ARIEL program, could reveal more
about exoplanets like K2-18b." ] ;
let output = summarization_model . summarize ( & input ) ;
(예: WikiNews)
산출:
"Scientists have found water vapour on K2-18b, a planet 110 light-years from Earth.
This is the first such discovery in a planet in its star's habitable zone.
The planet is not too hot and not too cold for liquid water to exist."
Microsoft의 DialoGPT를 기반으로 한 대화 모델입니다. 이 파이프라인을 사용하면 인간과 모델 간의 단일 또는 다중 턴 대화를 생성할 수 있습니다. DialoGPT 페이지에는 다음과 같이 명시되어 있습니다.
인간 평가 결과는 DialoGPT에서 생성된 응답이 단일 회전 대화 Turing 테스트에서 인간 응답 품질과 비슷하다는 것을 나타냅니다. (DialoGPT 저장소)
모델은 ConversationManager
사용하여 활성 대화를 추적하고 이에 대한 응답을 생성합니다.
use rust_bert :: pipelines :: conversation :: { ConversationModel , ConversationManager } ;
let conversation_model = ConversationModel :: new ( Default :: default ( ) ) ;
let mut conversation_manager = ConversationManager :: new ( ) ;
let conversation_id = conversation_manager . create ( "Going to the movies tonight - any suggestions?" ) ;
let output = conversation_model . generate_responses ( & mut conversation_manager ) ;
예제 출력:
"The Big Lebowski."
프롬프트를 기반으로 언어를 생성합니다. GPT2 및 GPT를 기본 모델로 사용할 수 있습니다. 빔 검색, top-k 및 핵 샘플링, 온도 설정 및 반복 페널티와 같은 기술을 포함합니다. 여러 프롬프트에서 문장의 일괄 생성을 지원합니다. 시퀀스는 모델의 패딩 토큰이 있는 경우 왼쪽에 채워지고 그렇지 않으면 알 수 없는 토큰이 채워집니다. 이는 결과에 영향을 미칠 수 있으므로 최상의 결과를 얻으려면 비슷한 길이의 프롬프트를 제출하는 것이 좋습니다.
let model = GPT2Generator :: new ( Default :: default ( ) ) ? ;
let input_context_1 = "The dog" ;
let input_context_2 = "The cat was" ;
let generate_options = GenerateOptions {
max_length : 30 ,
.. Default :: default ( )
} ;
let output = model . generate ( Some ( & [ input_context_1 , input_context_2 ] ) , generate_options ) ;
예제 출력:
[
"The dog's owners, however, did not want to be named. According to the lawsuit, the animal's owner, a 29-year"
"The dog has always been part of the family. "He was always going to be my dog and he was always looking out for me"
"The dog has been able to stay in the home for more than three months now. "It's a very good dog. She's"
"The cat was discovered earlier this month in the home of a relative of the deceased. The cat's owner, who wished to remain anonymous,"
"The cat was pulled from the street by two-year-old Jazmine."I didn't know what to do," she said"
"The cat was attacked by two stray dogs and was taken to a hospital. Two other cats were also injured in the attack and are being treated."
]
자연어 추론을 위해 미세 조정된 모델을 사용하여 제공된 레이블이 있는 입력 문장에 대해 제로샷 분류를 수행합니다.
let sequence_classification_model = ZeroShotClassificationModel :: new ( Default :: default ( ) ) ? ;
let input_sentence = "Who are you voting for in 2020?" ;
let input_sequence_2 = "The prime minister has announced a stimulus package which was widely criticized by the opposition." ;
let candidate_labels = & [ "politics" , "public health" , "economics" , "sports" ] ;
let output = sequence_classification_model . predict_multilabel (
& [ input_sentence , input_sequence_2 ] ,
candidate_labels ,
None ,
128 ,
) ;
산출:
[
[ Label { "politics", score: 0.972 }, Label { "public health", score: 0.032 }, Label {"economics", score: 0.006 }, Label {"sports", score: 0.004 } ],
[ Label { "politics", score: 0.975 }, Label { "public health", score: 0.0818 }, Label {"economics", score: 0.852 }, Label {"sports", score: 0.001 } ],
]
문장의 이진 감정을 예측합니다. DitilBERT 모델은 SST-2에서 미세 조정되었습니다.
let sentiment_classifier = SentimentModel :: new ( Default :: default ( ) ) ? ;
let input = [
"Probably my all-time favorite movie, a story of selflessness, sacrifice and dedication to a noble cause, but it's not preachy or boring." ,
"This film tried to be too many things all at once: stinging political satire, Hollywood blockbuster, sappy romantic comedy, family values promo..." ,
"If you like original gut wrenching laughter you will like this movie. If you are young or old then you will love this movie, hell even my mom liked it." ,
] ;
let output = sentiment_classifier . predict ( & input ) ;
(IMDb의 예시 제공)
산출:
[
Sentiment { polarity: Positive, score: 0.9981985493795946 },
Sentiment { polarity: Negative, score: 0.9927982091903687 },
Sentiment { polarity: Positive, score: 0.9997248985164333 }
]
텍스트에서 엔터티(사람, 위치, 조직, 기타)를 추출합니다. BERT는 바이에른 주립 도서관의 MDZ 디지털 도서관 팀이 기여한 CoNNL03에서 미세 조정된 대형 모델을 케이스에 담았습니다. 현재 영어, 독일어, 스페인어, 네덜란드어 모델이 제공됩니다.
let ner_model = NERModel :: new ( default :: default ( ) ) ? ;
let input = [
"My name is Amy. I live in Paris." ,
"Paris is a city in France."
] ;
let output = ner_model . predict ( & input ) ;
산출:
[
[
Entity { word: "Amy", score: 0.9986, label: "I-PER" }
Entity { word: "Paris", score: 0.9985, label: "I-LOC" }
],
[
Entity { word: "Paris", score: 0.9988, label: "I-LOC" }
Entity { word: "France", score: 0.9993, label: "I-LOC" }
]
]
입력 문서에서 키워드 및 핵심 문구 추출 추출
fn main ( ) -> anyhow :: Result < ( ) > {
let keyword_extraction_model = KeywordExtractionModel :: new ( Default :: default ( ) ) ? ;
let input = "Rust is a multi-paradigm, general-purpose programming language.
Rust emphasizes performance, type safety, and concurrency. Rust enforces memory safety—that is,
that all references point to valid memory—without requiring the use of a garbage collector or
reference counting present in other memory-safe languages. To simultaneously enforce
memory safety and prevent concurrent data races, Rust's borrow checker tracks the object lifetime
and variable scope of all references in a program during compilation. Rust is popular for
systems programming but also offers high-level features including functional programming constructs." ;
let output = keyword_extraction_model . predict ( & [ input ] ) ? ;
}
산출:
"rust" - 0.50910604
"programming" - 0.35731024
"concurrency" - 0.33825397
"concurrent" - 0.31229728
"program" - 0.29115444
텍스트에서 품사 태그(명사, 동사, 형용사...)를 추출합니다.
let pos_model = POSModel :: new ( default :: default ( ) ) ? ;
let input = [ "My name is Bob" ] ;
let output = pos_model . predict ( & input ) ;
산출:
[
Entity { word: "My", score: 0.1560, label: "PRP" }
Entity { word: "name", score: 0.6565, label: "NN" }
Entity { word: "is", score: 0.3697, label: "VBZ" }
Entity { word: "Bob", score: 0.7460, label: "NNP" }
]
문장 임베딩(벡터 표현)을 생성합니다. 이는 밀집된 정보 검색을 포함한 애플리케이션에 사용될 수 있습니다.
let model = SentenceEmbeddingsBuilder :: remote (
SentenceEmbeddingsModelType :: AllMiniLmL12V2
) . create_model ( ) ? ;
let sentences = [
"this is an example sentence" ,
"each sentence is converted"
] ;
let output = model . encode ( & sentences ) ? ;
산출:
[
[-0.000202666, 0.08148022, 0.03136178, 0.002920636 ...],
[0.064757116, 0.048519745, -0.01786038, -0.0479775 ...]
]
입력 문장에서 마스크된 단어를 예측합니다.
let model = MaskedLanguageModel :: new ( Default :: default ( ) ) ? ;
let sentences = [
"Hello I am a <mask> student" ,
"Paris is the <mask> of France. It is <mask> in Europe." ,
] ;
let output = model . predict ( & sentences ) ;
산출:
[
[MaskedToken { text: "college", id: 2267, score: 8.091}],
[
MaskedToken { text: "capital", id: 3007, score: 16.7249},
MaskedToken { text: "located", id: 2284, score: 9.0452}
]
]
간단한 파이프라인(시퀀스 분류, 토큰 분류, 질문 답변)의 경우 Python과 Rust 간의 성능이 비슷할 것으로 예상됩니다. 이는 이러한 파이프라인에서 가장 비용이 많이 드는 부분이 Torch 백엔드에서 공통 구현을 공유하는 언어 모델 자체이기 때문입니다. Rust의 엔드투엔드 NLP 파이프라인은 모든 파이프라인을 다루는 벤치마크 섹션을 제공합니다.
텍스트 생성 작업(요약, 번역, 대화, 자유 텍스트 생성)의 경우 상당한 이점을 기대할 수 있습니다(입력 및 애플리케이션에 따라 처리 속도가 최대 2~4배 빨라짐). Rust로 텍스트 생성 가속화 기사는 이러한 텍스트 생성 애플리케이션에 초점을 맞추고 Python과의 성능 비교에 대한 자세한 내용을 제공합니다.
자체 변압기 기반 모델을 노출하려는 사용자를 위해 기본 모델 및 작업별 헤드도 제공됩니다. 기본 토크나이저 Rust 라이브러리를 사용하여 날짜를 준비하는 방법에 대한 예는 BERT, DistilBERT, RoBERTa, GPT, GPT2 및 BART에 대한 ./examples
에서 확인할 수 있습니다. Pytorch에서 모델을 가져올 때 매개변수 명명 규칙은 Rust 스키마에 맞춰야 합니다. 가중치 파일에서 모델 매개변수 가중치를 찾을 수 없으면 사전 훈련된 가중치 로드가 실패합니다. 이 품질 검사를 건너뛰려면 변수 저장소에서 대체 메서드 load_partial
호출할 수 있습니다.
사전 훈련된 모델은 Hugging Face의 모델 허브에서 사용할 수 있으며 이 라이브러리에 정의된 RemoteResources
사용하여 로드할 수 있습니다.
Pytorch 가중치를 이 라이브러리와 호환되는 가중치 세트로 변환하기 위한 변환 유틸리티 스크립트가 ./utils
에 포함되어 있습니다. 이 스크립트를 사용하려면 Python과 torch
설정해야 합니다.