Views
No views yet
pip install -q transformers==4.51.0 sentence-transformers==5.1.1 flash-attn langchain_community langchain_huggingface langchain_gigachat1import torch
2import torch.nn.functional as F
3
4from torch import Tensor
5from transformers import AutoTokenizer, AutoModel
6
7
8def get_detailed_instruct(task_description: str, query: str) -> str:
9 return f'Instruct: {task_description}\nQuery: {query}'
10
11# Each query must come with a one-sentence instruction that describes the task
12task = 'Given a web search query, retrieve relevant passages that answer the query'
13
14queries = [
15 get_detailed_instruct(task, 'What is the capital of Russia?'),
16 get_detailed_instruct(task, 'Explain gravity')
17]
18# No need to add instruction for retrieval documents
19documents = [
20 "The capital of Russia is Moscow.",
21 "Gravity is a force that attracts two bodies towards each other. It gives weight to physical objects and is responsible for the movement of planets around the sun."
22]
23input_texts = queries + documents
24
25# We recommend enabling flash_attention_2 for better acceleration and memory saving.
26tokenizer = AutoTokenizer.from_pretrained(
27 'ai-sage/Giga-Embeddings-instruct',
28 trust_remote_code=True
29)
30model = AutoModel.from_pretrained(
31 'ai-sage/Giga-Embeddings-instruct',
32 attn_implementation="flash_attention_2",
33 torch_dtype=torch.bfloat16,
34 trust_remote_code=True
35)
36model.eval()
37model.cuda()
38
39max_length = 4096
40
41# Tokenize the input texts
42batch_dict = tokenizer(
43 input_texts,
44 padding=True,
45 truncation=True,
46 max_length=max_length,
47 return_tensors="pt",
48)
49batch_dict.to(model.device)
50embeddings = model(**batch_dict, return_embeddings=True)
51
52scores = (embeddings[:2] @ embeddings[2:].T)
53print(scores.tolist())
54# [[0.58203125, 0.0712890625], [0.06884765625, 0.62109375]]1import torch
2
3from sentence_transformers import SentenceTransformer
4
5# Load the model
6# We recommend enabling flash_attention_2 for better acceleration and memory saving
7model = SentenceTransformer(
8 "ai-sage/Giga-Embeddings-instruct",
9 model_kwargs={
10 "attn_implementation": "flash_attention_2",
11 "torch_dtype": torch.bfloat16,
12 "trust_remote_code": "True"
13 },
14 config_kwargs={
15 "trust_remote_code": "True"
16 }
17)
18model.max_seq_length = 4096
19
20# The queries and documents to embed
21queries = [
22 'What is the capital of Russia?',
23 'Explain gravity'
24]
25# No need to add instruction for retrieval documents
26documents = [
27 "The capital of Russia is Moscow.",
28 "Gravity is a force that attracts two bodies towards each other. It gives weight to physical objects and is responsible for the movement of planets around the sun."
29]
30
31# Encode the queries and documents. Note that queries benefit from using a prompt
32query_embeddings = model.encode(queries, prompt='Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery: ')
33document_embeddings = model.encode(documents)
34
35# Compute the (cosine) similarity between the query and document embeddings
36similarity = model.similarity(query_embeddings, document_embeddings)
37print(similarity)
38# tensor([[0.5846, 0.0702],
39# [0.0691, 0.6207]])1import torch
2
3from langchain_huggingface import HuggingFaceEmbeddings
4
5# Load model
6embeddings = HuggingFaceEmbeddings(
7 model_name='ai-sage/Giga-Embeddings-instruct',
8 encode_kwargs={},
9 model_kwargs={
10 'device': 'cuda',
11 'trust_remote_code': True,
12 'model_kwargs': {'torch_dtype': torch.bfloat16},
13 'prompts': {'query': 'Instruct: Given a question, retrieve passages that answer the question\nQuery: '}
14 }
15)
16
17# Tokenizer
18embeddings._client.tokenizer.tokenize("Hello world! I am GigaChat")
19
20# Query embeddings
21query_embeddings = embeddings.embed_query("Hello world!")
22print(f"Your embeddings: {query_embeddings[0:20]}...")
23print(f"Vector size: {len(query_embeddings)}")
24
25# Document embeddings
26documents = ["foo bar", "bar foo"]
27documents_embeddings = embeddings.embed_documents(documents)
28print(f"Vector size: {len(documents_embeddings)} x {len(documents_embeddings[0])}")"Retrieve semantically similar text""Given a text, retrieve semantically similar text""Дано предложение, необходимо найти его парафраз""Классифицируй отзыв на товар как положительный, отрицательный или нейтральный""Классифицируй чувствительную тему по запросу"'Дан вопрос, необходимо найти абзац текста с ответом'.'Дан вопрос, необходимо найти абзац текста с ответом''Given the question, find a paragraph with the answer'f'Instruct: {task_description}\nQuery: {query}'. Использование инструкций позволяет значительно улучшить качество поиска и релевантность результатов, что подтверждается тестами на бенчмарках, таких как RuBQ, MIRACL. Для симметричных задач добавление инструкции перед каждым запросом обеспечивает согласованность и повышает точность модели.