Sentence Similarity
sentence-transformers
Safetensors
Transformers
English
mistral
feature-extraction
mirei
llm2vec
text-embedding
embeddings
retrieval
custom_code
text-embeddings-inference
Run this model with HF Jobs
Run iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B", trust_remote_code=True) sentences = [ "That is a happy person", "That is a happy dog", "That is a very happy person", "Today is a sunny day" ] embeddings = model.encode(sentences) similarities = model.similarity(embeddings, embeddings) print(similarities.shape) # [4, 4] - Transformers
How to use iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained("iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B", trust_remote_code=True) model = AutoModel.from_pretrained("iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Commit ·
bcb2ad0
0
Parent(s):
Initial commit
Browse filesFiles changed (15)
- .gitattributesAdded+36
- 1_Pooling/config.jsonAdded+10
- README.mdAdded+110
- README_JA.mdAdded+110
- assets/concept.jpgAdded
- config.jsonAdded+32
- config_sentence_transformers.jsonAdded+14
- model.safetensorsAdded+3
- modeling_bidirectional_mistral.pyAdded+520
- modules.jsonAdded+14
- sentence_bert_config.jsonAdded+4
- special_tokens_map.jsonAdded+30
- tokenizer.jsonAdded
- tokenizer.modelAdded+3
- tokenizer_config.jsonAdded+51
123456789101112131415161718192021222324252627282930313233343536*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textassets/concept.jpg filter=lfs diff=lfs merge=lfs -text12345678910{ "word_embedding_dimension": 1536, "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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110---language:- enlicense: mitlibrary_name: sentence-transformerspipeline_tag: sentence-similaritytags:- mirei- mistral- transformers- llm2vec- text-embedding- embeddings- feature-extraction- retrievalbase_model: iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B-PTdatasets:- sentence-transformers/embedding-training-data---
# Sentence-Mistral-Bi-EN-0.5B
English / [Japanese](README_JA.md)
## OverviewSentence-Mistral-Bi-EN-0.5B fine-tunes [iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B-PT](https://huggingface.co/iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B-PT) with supervised contrastive learning on the supervised subsets of [sentence-transformers/embedding-training-data](https://huggingface.co/datasets/sentence-transformers/embedding-training-data) (AllNLI, MS MARCO, Quora duplicate questions, NQ, SQuAD, and TriviaQA), yielding 1,536-dimensional English sentence embeddings.
- **[Hugging Face Collection](https://huggingface.co/collections/iamtatsuki05/mirei)**- **[GitHub](https://github.com/iamtatsuki05/MIREI)**

## Usage### Requirements```sentence-transformers>=4.1.0transformers>=4.51.0accelerate>=1.6.0sentencepiece>=0.2.0flash-attn>=2.7.3```
### Sample Code```pythonimport torchfrom sentence_transformers import SentenceTransformer
model_name = "iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B"model_kwargs = { "torch_dtype": torch.bfloat16, "attn_implementation": "flash_attention_2",}model = SentenceTransformer(model_name, model_kwargs=model_kwargs, trust_remote_code=True)
queries = ["What kind of character is Hachiware?"]docs = [ "Hachiware is a cat-like character from Chiikawa with a bright, sociable, and positive personality. Hachiware enjoys everyday life with Chiikawa and friends and eagerly joins adventures such as subjugation missions.", "Usagi is a carefree, free-spirited character whose bold actions and sharp intuition pull Chiikawa and friends along, while still caring deeply about friends.",]q_emb = model.encode(queries, normalize_embeddings=True)d_emb = model.encode(docs, normalize_embeddings=True)scores = model.similarity(q_emb, d_emb)print(scores)```
## Model Details- **Base model:** [iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B-PT](https://huggingface.co/iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B-PT)- **Architecture:** Mistral- **Maximum sequence length:** 8,192 tokens- **Embedding dimension:** 1536 (mean pooling)- **Tokenizer:** Mistral tokenizer / vocabulary size 32,000- **Positional encoding:** RoPE- **Supported languages:** English- **Similarity metric:** cosine
## Model Series
These English 0.5B encoders start from weakly supervised checkpoints and undergo supervised fine-tuning on the supervised subsets of [sentence-transformers/embedding-training-data](https://huggingface.co/datasets/sentence-transformers/embedding-training-data). The first three rows are the main Encoder / Decoder / Decoder-PT comparison; the remaining rows vary the decoder configuration (Mistral, Qwen2.5 trained from scratch) or the pre-trained source model (Qwen2.5-0.5B, InstructLM-500M).
| ID | Architecture | #Param. | #Param.<br>w/o Emb. | MTEB-Avg | MTEB-Retrieval | MTEB-STS | MTEB-Classification | MTEB-Reranking | MTEB-Clustering ||:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|| [iamtatsuki05/Sentence-ModernBERT-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-ModernBERT-EN-0.5B) | ModernBERT | 677M | 546M | 53.66 | 40.32 | 76.04 | 67.31 | 42.93 | 41.69 || [iamtatsuki05/Sentence-Llama-Bi-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-Llama-Bi-EN-0.5B) | Llama | 661M | 530M | 52.12 | 37.31 | 74.10 | 66.28 | 42.29 | 40.63 || [iamtatsuki05/Sentence-Sarashina-Bi-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-Sarashina-Bi-EN-0.5B) | Llama | 661M | 530M | 56.54 | 42.62 | 78.91 | 72.45 | 45.39 | 43.35 || [iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B)<br>(this model) | Mistral | 518M | 469M | 52.70 | 38.44 | 75.04 | 66.60 | 42.53 | 40.87 || [iamtatsuki05/Sentence-Qwen2.5-Scratch-Bi-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-Qwen2.5-Scratch-Bi-EN-0.5B) | Qwen2.5 | 494M | 357M | 51.73 | 36.70 | 73.86 | 65.20 | 42.00 | 40.90 || [iamtatsuki05/Sentence-Qwen2.5-Bi-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-Qwen2.5-Bi-EN-0.5B) | Qwen2.5 | 494M | 357M | 57.19 | 44.18 | 79.48 | 71.92 | 45.23 | **45.15** || [iamtatsuki05/Sentence-InstructLM-Bi-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-InstructLM-Bi-EN-0.5B) | Mistral | 518M | 469M | **57.73** | **46.11** | **80.01** | **73.19** | **45.71** | 43.62 |
Scores are measured on the 37-task English subset of MTEB (eng, v2) that covers the same five task families as JMTEB. Each task-family score averages all datasets, splits, and subsets in the family, and MTEB-Avg is the macro average over the five families.
## LicenceThis model is distributed under the [MIT License](https://opensource.org/license/mit/).
## How to Cite
```tex@article{MIREI title={同一条件下における Encoder/Decoder アーキテクチャによる文埋め込みの性能分析}, author={岡田 龍樹 and 杉本 徹}, journal={言語処理学会第 32 回年次大会 (NLP2026)}, year={2026}}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110---language:- enlicense: mitlibrary_name: sentence-transformerspipeline_tag: sentence-similaritytags:- mirei- mistral- transformers- llm2vec- text-embedding- embeddings- feature-extraction- retrievalbase_model: iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B-PTdatasets:- sentence-transformers/embedding-training-data---
# Sentence-Mistral-Bi-EN-0.5B
[English](README.md) / Japanese
## OverviewSentence-Mistral-Bi-EN-0.5B は、[iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B-PT](https://huggingface.co/iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B-PT) を [sentence-transformers/embedding-training-data](https://huggingface.co/datasets/sentence-transformers/embedding-training-data) の教師ありサブセット(AllNLI、MS MARCO、Quora duplicate questions、NQ、SQuAD、TriviaQA)で教師あり対照学習を行った 1536 次元の英語埋め込みモデルです。
- **[Hugging Face Collection](https://huggingface.co/collections/iamtatsuki05/mirei)**- **[GitHub](https://github.com/iamtatsuki05/MIREI)**

## Usage### Requirements```sentence-transformers>=4.1.0transformers>=4.51.0accelerate>=1.6.0sentencepiece>=0.2.0flash-attn>=2.7.3```
### Sample Code```pythonimport torchfrom sentence_transformers import SentenceTransformer
model_name = "iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B"model_kwargs = { "torch_dtype": torch.bfloat16, "attn_implementation": "flash_attention_2",}model = SentenceTransformer(model_name, model_kwargs=model_kwargs, trust_remote_code=True)
queries = ["What kind of character is Hachiware?"]docs = [ "Hachiware is a cat-like character from Chiikawa with a bright, sociable, and positive personality. Hachiware enjoys everyday life with Chiikawa and friends and eagerly joins adventures such as subjugation missions.", "Usagi is a carefree, free-spirited character whose bold actions and sharp intuition pull Chiikawa and friends along, while still caring deeply about friends.",]q_emb = model.encode(queries, normalize_embeddings=True)d_emb = model.encode(docs, normalize_embeddings=True)scores = model.similarity(q_emb, d_emb)print(scores)```
## Model Details- **ベースモデル:** [iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B-PT](https://huggingface.co/iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B-PT)- **アーキテクチャ:** Mistral- **最大シーケンス長:** 8,192 トークン- **埋め込み次元:** 1536(Mean Pooling)- **トークナイザ:** Mistral tokenizer / 語彙数 32,000- **位置エンコーディング:** RoPE- **対応言語:** 英語- **類似度指標:** cosine
## Model Series
弱教師あり学習済みモデルに対して [sentence-transformers/embedding-training-data](https://huggingface.co/datasets/sentence-transformers/embedding-training-data) の教師ありサブセットで教師あり学習した英語 0.5B モデル群です。上の 3 行が Encoder / Decoder / Decoder-PT の主比較、残りは Decoder の構成(Mistral、ゼロから学習した Qwen2.5)や転用元の事前学習済みモデル(Qwen2.5-0.5B、InstructLM-500M)を変えた比較です。
| ID | Architecture | #Param. | #Param.<br>w/o Emb. | MTEB-Avg | MTEB-Retrieval | MTEB-STS | MTEB-Classification | MTEB-Reranking | MTEB-Clustering ||:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|| [iamtatsuki05/Sentence-ModernBERT-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-ModernBERT-EN-0.5B) | ModernBERT | 677M | 546M | 53.66 | 40.32 | 76.04 | 67.31 | 42.93 | 41.69 || [iamtatsuki05/Sentence-Llama-Bi-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-Llama-Bi-EN-0.5B) | Llama | 661M | 530M | 52.12 | 37.31 | 74.10 | 66.28 | 42.29 | 40.63 || [iamtatsuki05/Sentence-Sarashina-Bi-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-Sarashina-Bi-EN-0.5B) | Llama | 661M | 530M | 56.54 | 42.62 | 78.91 | 72.45 | 45.39 | 43.35 || [iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-Mistral-Bi-EN-0.5B)<br>(this model) | Mistral | 518M | 469M | 52.70 | 38.44 | 75.04 | 66.60 | 42.53 | 40.87 || [iamtatsuki05/Sentence-Qwen2.5-Scratch-Bi-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-Qwen2.5-Scratch-Bi-EN-0.5B) | Qwen2.5 | 494M | 357M | 51.73 | 36.70 | 73.86 | 65.20 | 42.00 | 40.90 || [iamtatsuki05/Sentence-Qwen2.5-Bi-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-Qwen2.5-Bi-EN-0.5B) | Qwen2.5 | 494M | 357M | 57.19 | 44.18 | 79.48 | 71.92 | 45.23 | **45.15** || [iamtatsuki05/Sentence-InstructLM-Bi-EN-0.5B](https://huggingface.co/iamtatsuki05/Sentence-InstructLM-Bi-EN-0.5B) | Mistral | 518M | 469M | **57.73** | **46.11** | **80.01** | **73.19** | **45.71** | 43.62 |
スコアは MTEB (eng, v2) のうち JMTEB と同じ 5 タスク群に対応する英語 37 タスクで測定しました。各タスク群のスコアは群内の全データセット・分割・サブセットの平均、MTEB-Avg は 5 タスク群のマクロ平均です。
## Licence本モデルは [MIT License](https://opensource.org/license/mit/) の下で配布されます。
## 引用
```tex@article{MIREI title={同一条件下における Encoder/Decoder アーキテクチャによる文埋め込みの性能分析}, author={岡田 龍樹 and 杉本 徹}, journal={言語処理学会第 32 回年次大会 (NLP2026)}, year={2026}}```1234567891011121314151617181920212223242526272829303132{ "architectures": [ "MistralBiModel" ], "attention_dropout": 0.0, "auto_map": { "AutoModel": "modeling_bidirectional_mistral.MistralBiModel", "AutoModelForCausalLM": "modeling_bidirectional_mistral.MistralBiForMNTP", "AutoModelForSequenceClassification": "modeling_bidirectional_mistral.MistralBiForSequenceClassification" }, "bos_token_id": 1, "dtype": "float32", "eos_token_id": 2, "head_dim": null, "hidden_act": "silu", "hidden_size": 1536, "initializer_range": 0.02, "intermediate_size": 4320, "max_position_embeddings": 8192, "model_type": "mistral", "num_attention_heads": 24, "num_hidden_layers": 16, "num_key_value_heads": 24, "pad_token_id": 2, "rms_norm_eps": 1e-05, "rope_theta": 10000.0, "sliding_window": 2048, "tie_word_embeddings": false, "transformers_version": "4.56.1", "use_cache": true, "vocab_size": 32000}1234567891011121314{ "model_type": "SentenceTransformer", "__version__": { "sentence_transformers": "5.1.0", "transformers": "4.56.1", "pytorch": "2.8.0+cu128" }, "prompts": { "query": "", "document": "" }, "default_prompt_name": null, "similarity_fn_name": "cosine"}123version https://git-lfs.github.com/spec/v1oid sha256:59c7a1881d1f67443051e4b1a72c87196ca101f38a10e1baca296454a9fc2dd4size 2074826128123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520from __future__ import annotations
from typing import Unpack
import torchfrom peft import PeftModelfrom torch import nnfrom transformers import ( AutoTokenizer, MistralConfig, MistralForCausalLM, MistralModel, MistralPreTrainedModel,)from transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_attn_mask_utils import AttentionMaskConverterfrom transformers.modeling_outputs import BaseModelOutputWithPast, SequenceClassifierOutputWithPastfrom transformers.tokenization_utils_base import BatchEncodingfrom transformers.utils import TransformersKwargs, is_torch_flex_attn_available, loggingfrom transformers.utils.generic import check_model_inputs
if is_torch_flex_attn_available(): from torch.nn.attention.flex_attention import BlockMask from transformers.integrations.flex_attention import make_flex_block_causal_mask
logger = logging.get_logger(__name__)
class SentenceEncoderMixin: @staticmethod def _skip_instruction(sentence_feature: BatchEncoding): assert sentence_feature['attention_mask'].shape == sentence_feature['embed_mask'].shape sentence_feature['attention_mask'] = sentence_feature['embed_mask']
@staticmethod def _tokenize_with_instruction( sentences: str | list[str], tokenizer: AutoTokenizer, instruction: str = '', max_length: int | None = None, ) -> BatchEncoding: if isinstance(sentences, str): sentences = [sentences]
plain = tokenizer( sentences, padding=True, truncation=True, return_tensors='pt', add_special_tokens=False, max_length=max_length, ) mixed = tokenizer( [instruction + s for s in sentences], padding=True, truncation=True, return_tensors='pt', add_special_tokens=True, max_length=max_length, )
masks = [] for i, seq_len in enumerate(plain['attention_mask'].sum(dim=1)): m = torch.zeros_like(mixed['attention_mask'][i]) if seq_len > 0: m[-seq_len:] = 1 masks.append(m.unsqueeze(0)) mixed['embed_mask'] = torch.cat(masks, dim=0) return mixed
def _pool(self, feats: BatchEncoding, hidden: torch.Tensor) -> torch.Tensor: if self.skip_instruction: self._skip_instruction(feats)
seq_lens = feats['attention_mask'].sum(dim=-1)
if self.pooling_mode == 'mean': return torch.stack( [ (hidden[i, -l:, :].mean(dim=0) if l > 0 else hidden.new_zeros(hidden.size(-1))) for i, l in enumerate(seq_lens) ], dim=0, ) elif self.pooling_mode == 'weighted_mean': bs, L, _ = hidden.shape w = hidden.new_zeros(bs, L) for i, l in enumerate(seq_lens): if l > 0: ar = torch.arange(l, device=w.device) + 1 w[i, -l:] = ar / ar.sum() return (hidden * w.unsqueeze(-1)).sum(dim=1) elif self.pooling_mode in ('eos_token', 'last_token'): return hidden[:, -1] elif self.pooling_mode == 'bos_token': bos_id = self.tokenizer.bos_token_id mask = (feats['input_ids'] == bos_id).unsqueeze(-1).expand_as(hidden) return hidden[mask].view(hidden.size(0), -1) else: raise ValueError(f'{self.pooling_mode} not supported.')
@torch.no_grad() def encode( self, sentences: str | list[str], tokenizer: AutoTokenizer, *, instruction: str = '', max_length: int | None = None, ) -> torch.Tensor: self.tokenizer = tokenizer feats = self._tokenize_with_instruction( sentences, tokenizer, instruction=instruction, max_length=max_length, ).to(self.device) hidden = self(**feats).last_hidden_state return self._pool(feats, hidden)
class MistralBiModel(MistralModel, SentenceEncoderMixin): _no_split_modules = ['MistralDecoderLayer']
def __init__( self, config: MistralConfig, *, pooling_mode: str = 'mean', skip_instruction: bool = True, max_length: int | None = None, ) -> None: super().__init__(config) self.set_causal(False)
self.pooling_mode = pooling_mode self.skip_instruction = skip_instruction self.tokenizer: AutoTokenizer | None = None self.max_length = max_length
def set_causal(self, causal: bool = False): for layer in self.layers: layer.self_attn.is_causal = causal
# Copied verbatim from modeling_bidirectional_llama.py (the LLM2Vec-style bidirectional adaptation # of the upstream causal-mask helper: the commented-out blocks are the upstream causal code). # transformers 4.56.1 no longer calls this hook from MistralModel.forward, so the forward() override # below calls it explicitly. def _update_causal_mask( self, attention_mask: 'BlockMask' | torch.Tensor, input_tensor: torch.Tensor, cache_position: torch.Tensor, past_key_values: Cache, output_attentions: bool = False, ): if self.config._attn_implementation == 'flash_attention_2': if attention_mask is not None and (attention_mask == 0.0).any(): return attention_mask return None if self.config._attn_implementation == 'flex_attention': if isinstance(attention_mask, torch.Tensor): attention_mask = make_flex_block_causal_mask(attention_mask, is_causal=False) return attention_mask
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail # to infer the attention mask. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 using_compilable_cache = past_key_values.is_compileable if past_key_values is not None else False
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward # if self.config._attn_implementation == "sdpa" and not using_compilable_cache and not output_attentions: # if AttentionMaskConverter._ignore_causal_mask_sdpa( # attention_mask, # inputs_embeds=input_tensor, # past_key_values_length=past_seen_tokens, # is_training=self.training, # ): # return None
dtype = input_tensor.dtype sequence_length = input_tensor.shape[1] if using_compilable_cache: target_length = past_key_values.get_max_cache_shape() else: target_length = ( attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else past_seen_tokens + sequence_length + 1 )
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D). causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position( attention_mask, sequence_length=sequence_length, target_length=target_length, dtype=dtype, cache_position=cache_position, batch_size=input_tensor.shape[0], )
if ( self.config._attn_implementation == 'sdpa' and attention_mask is not None and attention_mask.device.type in ['cuda', 'xpu', 'npu'] and not output_attentions ): # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path. # Details: https://github.com/pytorch/pytorch/issues/110213 min_dtype = torch.finfo(dtype).min causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
return causal_mask
# Copied verbatim from modeling_bidirectional_llama.py @staticmethod def _prepare_4d_causal_attention_mask_with_cache_position( attention_mask: torch.Tensor, sequence_length: int, target_length: int, dtype: torch.dtype, # device: torch.device, this not used cache_position: torch.Tensor, batch_size: int, **kwargs, ): device = cache_position.device if attention_mask is not None and attention_mask.dim() == 4: # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing. causal_mask = attention_mask else: min_dtype = torch.finfo(dtype).min # causal_mask = torch.full( # (sequence_length, target_length), # fill_value=min_dtype, # dtype=dtype, # device=device, # )
# if sequence_length != 1: # causal_mask = torch.triu(causal_mask, diagonal=1) causal_mask = torch.zeros((sequence_length, target_length), dtype=dtype, device=device)
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1) causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1) if attention_mask is not None: causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit mask_length = attention_mask.shape[-1] padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to( causal_mask.device ) padding_mask = padding_mask == 0 causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( padding_mask, min_dtype )
return causal_mask
# Copied verbatim from transformers 4.56.1 MistralModel.forward, except for the marked block that # replaces the upstream causal mask creation with the bidirectional _update_causal_mask above. # The upstream @auto_docstring decorator is dropped: it raises an IndexError for classes defined # outside the transformers package. @check_model_inputs def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, use_cache: bool | None = None, cache_position: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutputWithPast: if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError('You must specify exactly one of input_ids or inputs_embeds')
if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids)
if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config)
if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device )
if position_ids is None: position_ids = cache_position.unsqueeze(0)
# === MODIFIED from transformers 4.56.1 (bidirectional attention) === # The upstream code below built causal masks (sliding-window ones when config.sliding_window # is set); the bidirectional mask is built instead. # mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask # causal_mask = mask_function( # config=self.config, # input_embeds=inputs_embeds, # attention_mask=attention_mask, # cache_position=cache_position, # past_key_values=past_key_values, # position_ids=position_ids, # ) causal_mask = self._update_causal_mask( attention_mask, inputs_embeds, cache_position, past_key_values, ) # === END MODIFIED ===
hidden_states = inputs_embeds position_embeddings = self.rotary_emb(hidden_states, position_ids)
for decoder_layer in self.layers[: self.config.num_hidden_layers]: hidden_states = decoder_layer( hidden_states, attention_mask=causal_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = self.norm(hidden_states) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, )
def encode_document( self, sentences: str | list[str], tokenizer: AutoTokenizer, instruction: str = '', max_length: int | None = None, ) -> torch.Tensor: return self.encode(sentences, tokenizer, instruction=instruction, max_length=max_length)
def encode_query( self, sentences: str | list[str], tokenizer: AutoTokenizer, instruction: str = '', max_length: int | None = None, ) -> torch.Tensor: return self.encode( sentences, tokenizer, instruction=instruction, max_length=max_length, )
class MistralBiForMNTP(MistralForCausalLM): def __init__( self, config: MistralConfig, *, pooling_mode: str = 'mean', skip_instruction: bool = True, max_length: int | None = None, ) -> None: MistralPreTrainedModel.__init__(self, config) self.model = MistralBiModel( config, pooling_mode=pooling_mode, skip_instruction=skip_instruction, max_length=max_length, ) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.post_init()
@torch.no_grad() def encode( self, sentences: str | list[str], tokenizer: AutoTokenizer, *, instruction: str = '', max_length: int | None = None, **kwargs, ) -> torch.Tensor: return self.model.encode( sentences, tokenizer, instruction=instruction, max_length=max_length, **kwargs, )
def set_causal(self, causal: bool = False): self.model.set_causal(causal)
@property def pooling_mode(self): return self.model.pooling_mode
@pooling_mode.setter def pooling_mode(self, mode: str): self.model.pooling_mode = mode
@property def skip_instruction(self): return self.model.skip_instruction
@skip_instruction.setter def skip_instruction(self, flag: bool): self.model.skip_instruction = flag
def get_model_for_peft(self): return self.model
def set_model_for_peft(self, model: PeftModel): self.model = model
def save_peft_model(self, path: str): if isinstance(self.model, PeftModel): self.model.save_pretrained(path) else: raise ValueError('self.model is not a PeftModel')
class MistralBiForSequenceClassification(MistralPreTrainedModel): def __init__( self, config: MistralConfig, pooling_mode: str = 'mean', skip_instruction: bool = True, max_length: int | None = None, ) -> None: super().__init__(config) self.num_labels = config.num_labels self.model = MistralBiModel( config, pooling_mode=pooling_mode, skip_instruction=skip_instruction, max_length=max_length, ) self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
self.post_init()
def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, ) -> SequenceClassifierOutputWithPast: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """
transformer_outputs: BaseModelOutputWithPast = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, ) hidden_states = transformer_outputs.last_hidden_state logits = self.score(hidden_states)
if input_ids is not None: batch_size = input_ids.shape[0] else: batch_size = inputs_embeds.shape[0]
if self.config.pad_token_id is None and batch_size != 1: raise ValueError('Cannot handle batch sizes > 1 if no padding token is defined.') if self.config.pad_token_id is None: last_non_pad_token = -1 elif input_ids is not None: # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32) token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32) last_non_pad_token = (token_indices * non_pad_mask).argmax(-1) else: last_non_pad_token = -1 logger.warning_once( f'{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be ' 'unexpected if using padding tokens in conjunction with `inputs_embeds.`' )
pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
loss = None if labels is not None: loss = self.loss_function( logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config, )
return SequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, )1234567891011121314[ { "idx": 0, "name": "0", "path": "", "type": "sentence_transformers.models.Transformer" }, { "idx": 1, "name": "1", "path": "1_Pooling", "type": "sentence_transformers.models.Pooling" }]1234{ "max_seq_length": 8192, "do_lower_case": false}123456789101112131415161718192021222324252627282930{ "bos_token": { "content": "<s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "</s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "</s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "unk_token": { "content": "<unk>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123version https://git-lfs.github.com/spec/v1oid sha256:dadfd56d766715c61d2ef780a525ab43b8e6da4de6865bda3d95fdef5e134055size 493443123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051{ "add_bos_token": true, "add_eos_token": false, "add_prefix_space": null, "added_tokens_decoder": { "0": { "content": "<unk>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "1": { "content": "<s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "2": { "content": "</s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "additional_special_tokens": [], "bos_token": "<s>", "clean_up_tokenization_spaces": false, "eos_token": "</s>", "extra_special_tokens": {}, "legacy": true, "max_length": 256, "model_max_length": 256, "pad_to_multiple_of": null, "pad_token": "</s>", "pad_token_type_id": 0, "padding_side": "left", "sp_model_kwargs": {}, "spaces_between_special_tokens": false, "stride": 0, "tokenizer_class": "LlamaTokenizer", "truncation_side": "right", "truncation_strategy": "longest_first", "unk_token": "<unk>", "use_default_system_prompt": false}.gitattributesAdded+36
1_Pooling/config.jsonAdded+10
README.mdAdded+110
README_JA.mdAdded+110
assets/concept.jpgAdded

Large File Pointer Details
- SHA256: 864229e9c3d402238537ed86edec125d1e0d41594b65a6ac7f573b27932e5b77
- Pointer size: 131 Bytes
- Size of remote file: 328 kB
config.jsonAdded+32
config_sentence_transformers.jsonAdded+14
model.safetensorsAdded+3
modeling_bidirectional_mistral.pyAdded+520
modules.jsonAdded+14
sentence_bert_config.jsonAdded+4
special_tokens_map.jsonAdded+30
tokenizer.jsonAdded
tokenizer.modelAdded+3
tokenizer_config.jsonAdded+51