DiTy / bi-encoder-russian-msmarco

huggingface.co
Total runs: 249
24-hour runs: 16
7-day runs: 9
30-day runs: -1.0K
Model's Last Updated: August 02 2024
sentence-similarity

Introduction of bi-encoder-russian-msmarco

Model Details of bi-encoder-russian-msmarco

DiTy/bi-encoder-russian-msmarco

This is a sentence-transformers model based on a pre-trained DeepPavlov/rubert-base-cased and finetuned with MS-MARCO Russian passage ranking dataset : It maps sentences & paragraphs to a 768 dimensional dense vector space and can be used for asymmetric semantic search in the Russian language.

Usage (Sentence-Transformers)

Using this model becomes easy when you have sentence-transformers installed:

pip install -U sentence-transformers

Then you can use the model like this:

from sentence_transformers import SentenceTransformer, util

sentences = [
    'какое состояние может определить тест с физической нагрузкой', 
    'Тест с физической нагрузкой разработан, чтобы выяснить, содержат ли одна или несколько коронарных артерий, питающих сердце, жировые отложения (бляшки), которые блокируют кровеносный сосуд на 70% или более. Для подтверждения результата часто требуется дополнительное тестирование. Результат испытаний.',
    'Тест направлен на то, чтобы выяснить, не получает ли какой-либо участок сердечной мышцы достаточный кровоток во время тренировки. Он похож на тест с физической нагрузкой, фармакологический или химический стресс-тест. Он также известен при стресс-тесте таллием, сканировании перфузии миокарда или радионуклидном тесте.'
]

model = SentenceTransformer('DiTy/bi-encoder-russian-msmarco')
embeddings = model.encode(sentences)
results = util.semantic_search(embeddings[0], embeddings[1:])[0]

print(f"Sentence similarity: {results}")
# `Sentence similarity: [{'corpus_id': 0, 'score': 0.8545001149177551}, {'corpus_id': 1, 'score': 0.023047829046845436}]`
Usage (HuggingFace Transformers)

Without sentence-transformers , you can use the model like this: First, you pass your input through the transformer model, then you have to apply the right pooling-operation on-top of the contextualized word embeddings.

from transformers import AutoTokenizer, AutoModel
import torch


#Mean Pooling - Take attention mask into account for correct averaging
def mean_pooling(model_output, attention_mask):
    token_embeddings = model_output[0] #First element of model_output contains all token embeddings
    input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
    return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)


# Sentences we want sentence embeddings for
sentences = [
  'красный плоский лишай вызван стрессом',
  'В большинстве случаев причину появления красного плоского лишая невозможно. Это не вызвано стрессом, но иногда эмоциональный стресс усугубляет ситуацию. Известно, что это заболевание возникает после контакта с определенными химическими веществами, такими как те, которые используются для проявления цветных фотографий. У некоторых людей определенные лекарства вызывают красный плоский лишай. Эти препараты включают лекарства от высокого кровяного давления, болезней сердца, диабета, артрита и малярии, антибиотики, нестероидные противовоспалительные обезболивающие и т. Д.',
  'К сожалению для работодателей, в разных штатах страны есть несколько дел, по которым суды установили, что стресс, вызванный работой, может быть основанием для увольнения с работы, если стресс достигает уровня серьезного состояния здоровья, которое вызывает они не могут выполнять свою работу.',
]

# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained('DiTy/bi-encoder-russian-msmarco')
model = AutoModel.from_pretrained('DiTy/bi-encoder-russian-msmarco')

# Tokenize sentences
encoded_input = tokenizer(sentences, max_length=512, padding='max_length', truncation=True, return_tensors='pt')

# Compute token embeddings
with torch.no_grad():
    model_output = model(**encoded_input)

# Perform pooling. In this case, mean pooling.
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])

print("Sentence embeddings:")
print(sentence_embeddings)
Training

The model was trained with the parameters:

DataLoader :

torch.utils.data.dataloader.DataLoader of length 1989041 with parameters:

{'batch_size': 16, 'sampler': 'torch.utils.data.sampler.RandomSampler', 'batch_sampler': 'torch.utils.data.sampler.BatchSampler'}

Loss :

sentence_transformers.losses.MultipleNegativesRankingLoss.MultipleNegativesRankingLoss with parameters:

{'scale': 20.0, 'similarity_fct': 'cos_sim'}

Parameters of the fit()-Method:

{
    "epochs": 5,
    "evaluation_steps": 250000,
    "evaluator": "sentence_transformers.evaluation.InformationRetrievalEvaluator",
    "max_grad_norm": 1,
    "optimizer_class": "<class 'torch.optim.adamw.AdamW'>",
    "optimizer_params": {
        "lr": 2e-05
    },
    "scheduler": "WarmupLinear",
    "steps_per_epoch": null,
    "warmup_steps": 10000,
    "weight_decay": 0.01
}
Full Model Architecture
SentenceTransformer(
  (0): Transformer({'max_seq_length': 512, 'do_lower_case': False}) with Transformer model: BertModel 
  (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})
)

Runs of DiTy bi-encoder-russian-msmarco on huggingface.co

249
Total runs
16
24-hour runs
15
3-day runs
9
7-day runs
-1.0K
30-day runs

More Information About bi-encoder-russian-msmarco huggingface.co Model

More bi-encoder-russian-msmarco license Visit here:

https://choosealicense.com/licenses/mit

bi-encoder-russian-msmarco huggingface.co

bi-encoder-russian-msmarco huggingface.co is an AI model on huggingface.co that provides bi-encoder-russian-msmarco's model effect (), which can be used instantly with this DiTy bi-encoder-russian-msmarco model. huggingface.co supports a free trial of the bi-encoder-russian-msmarco model, and also provides paid use of the bi-encoder-russian-msmarco. Support call bi-encoder-russian-msmarco model through api, including Node.js, Python, http.

bi-encoder-russian-msmarco huggingface.co Url

https://huggingface.co/DiTy/bi-encoder-russian-msmarco

DiTy bi-encoder-russian-msmarco online free

bi-encoder-russian-msmarco huggingface.co is an online trial and call api platform, which integrates bi-encoder-russian-msmarco's modeling effects, including api services, and provides a free online trial of bi-encoder-russian-msmarco, you can try bi-encoder-russian-msmarco online for free by clicking the link below.

DiTy bi-encoder-russian-msmarco online free url in huggingface.co:

https://huggingface.co/DiTy/bi-encoder-russian-msmarco

bi-encoder-russian-msmarco install

bi-encoder-russian-msmarco is an open source model from GitHub that offers a free installation service, and any user can find bi-encoder-russian-msmarco on GitHub to install. At the same time, huggingface.co provides the effect of bi-encoder-russian-msmarco install, users can directly use bi-encoder-russian-msmarco installed effect in huggingface.co for debugging and trial. It also supports api for free installation.

bi-encoder-russian-msmarco install url in huggingface.co:

https://huggingface.co/DiTy/bi-encoder-russian-msmarco

Url of bi-encoder-russian-msmarco

bi-encoder-russian-msmarco huggingface.co Url

Provider of bi-encoder-russian-msmarco huggingface.co

DiTy
ORGANIZATIONS

Other API from DiTy