Initial upload: NeoAraBERT (Mix checkpoint)
Browse filesFiles changed (10)
- README.mdAdded+36
- config.jsonAdded+31
- model.pyAdded+444
- model.safetensorsAdded+3
- rotary.pyAdded+61
- special_tokens_map.jsonAdded+10
- tokenizer.jsonAdded
- tokenizer.pyAdded+158
- tokenizer_config.jsonAdded+72
- vocab.txtAdded
123456789101112131415161718192021222324252627282930313233343536# NeoAraBERTNeoAraBERT is a state-of-the-art open-source Arabic text-embedding model built on the NeoBERT architecture. We pretrain NeoAraBERT on diverse open-source and internal datasets covering modern standard, classical, and dialectal Arabic. We guided our design choices with Arabic tailored ablation studies including text normalization, light stemming, and diacritics-aware tokenization handling. We also performed POS-aware token masking and learning-rate scheduling ablation studies. We benchmarked NeoAraBERT against five top-performing Arabic models on 23 tasks, including a synonym-based task, [Muradif](https://huggingface.co/datasets/U4RASD/Muradif), that directly assesses embedding quality with no additional fine-tuning. NeoAraBERT variants rank first in 18 tasks and improve average performance across the full benchmark suite.
This is the NeoAraBERT_Mix checkpoint, our best-performing checkpoint overall. This model was introduced at the 64th Annual Meeting of the Association for Computational Linguistics (ACL 2026). For more information, visit our website: https://www.acrps.ai/neoarabert.
### How to UseInstall these libraries:```pip install fast-disambig torch==2.5.1 transformers xformers==0.0.28.post3```Load the model and use it to generate embeddings:```pythonfrom transformers import AutoModel, AutoTokenizer
model_name = "U4RASD/NeoAraBERT"tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)model = AutoModel.from_pretrained(model_name, trust_remote_code=True)
# Tokenize input texttext = "المركز العربيّ للأبحاث ودراسة السياسات هو مؤسّسة بحثيّة فكريّة مستقلّة للعلوم الاجتماعية والإنسانية؛ النظرية والتطبيقية."inputs = tokenizer(text, return_tensors="pt")
# Generate embeddingsoutputs = model(**inputs)embedding = outputs.last_hidden_state[:, 0, :]print(embedding.shape)```
### CitationIf you use the code, model, or the Muradif benchmark, please reference this work in your paper:```bibtexThe citation will be added here soon.```
### LicenseThis model is licensed under the CC BY-SA 4.0 license. The text of the license can be found [here](https://creativecommons.org/licenses/by-sa/4.0/).12345678910111213141516171819202122232425262728293031{ "architectures": [ "NeoBERTLMHead" ], "auto_map": { "AutoConfig": "model.NeoBERTConfig", "AutoModel": "model.NeoBERT", "AutoModelForMaskedLM": "model.NeoBERTLMHead", "AutoModelForSequenceClassification": "model.NeoBERTForSequenceClassification" }, "classifier_init_range": 0.02, "decoder_init_range": 0.02, "dim_head": 64, "embedding_init_range": 0.02, "hidden_size": 768, "intermediate_size": 3072, "kwargs": { "classifier_init_range": 0.02, "trust_remote_code": true }, "max_length": 1024, "model_type": "neobert", "norm_eps": 1e-05, "num_attention_heads": 12, "num_hidden_layers": 28, "pad_token_id": 0, "torch_dtype": "float32", "transformers_version": "4.48.2", "trust_remote_code": true, "vocab_size": 65000}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444import torchfrom torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELossfrom torch.nn.functional import scaled_dot_product_attention
from typing import Optional, Tupleimport numpy as np
from xformers.ops import SwiGLU
try: from flash_attn.flash_attn_interface import flash_attn_varlen_func
FLASH_ATTN_AVAILABLE = Trueexcept ImportError: FLASH_ATTN_AVAILABLE = False
from transformers import ( PreTrainedModel, PretrainedConfig, DataCollatorForLanguageModeling,)from transformers.modeling_outputs import ( BaseModelOutput, MaskedLMOutput, SequenceClassifierOutput,)
try: import logging as _std_logging from transformers.utils import logging as _hf_logging
class _DropNeoBERTLoadReport(_std_logging.Filter): def filter(self, record): return "LOAD REPORT" not in record.getMessage()
_hf_logging.get_logger("transformers.modeling_utils").addFilter(_DropNeoBERTLoadReport())except Exception: pass
from .rotary import precompute_freqs_cis, apply_rotary_emb
class DataCollatorWithPacking(DataCollatorForLanguageModeling): def __init__(self, pack_sequences=False, **kwargs): super().__init__(**kwargs) self.pack_sequences = pack_sequences
def __call__(self, batch): if self.pack_sequences: # Add position_ids if not present if "position_ids" not in batch[0]: for item in batch: item["position_ids"] = list(range(len(item["input_ids"])))
# Pack the sequences into a single list input_ids_list = [item["input_ids"] for item in batch] position_ids_list = [item["position_ids"] for item in batch] seqlens = np.array([0] + [len(ids) for ids in input_ids_list])
packed_batch = { "position_ids": np.concatenate(position_ids_list, axis=0), "input_ids": np.concatenate(input_ids_list, axis=0), "cu_seqlens": np.cumsum(seqlens), "max_seqlen": max(seqlens), }
batch = super().__call__([packed_batch]) batch["cu_seqlens"] = batch["cu_seqlens"].to(torch.int32).squeeze() else: batch = super().__call__(batch) batch["attention_mask"] = batch["attention_mask"].to(torch.bool)
return batch
class NeoBERTConfig(PretrainedConfig): model_type = "neobert"
# All config parameters must have a default value. def __init__( self, hidden_size: int = 768, num_hidden_layers: int = 28, num_attention_heads: int = 12, intermediate_size: int = 3072, embedding_init_range: float = 0.02, decoder_init_range: float = 0.02, norm_eps: float = 1e-05, vocab_size: int = 65000, pad_token_id: int = 0, max_length: int = 1024, **kwargs, ): super().__init__(**kwargs)
self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads if hidden_size % num_attention_heads != 0: raise ValueError("Hidden size must be divisible by the number of heads.") self.dim_head = hidden_size // num_attention_heads self.intermediate_size = intermediate_size self.embedding_init_range = embedding_init_range self.decoder_init_range = decoder_init_range self.norm_eps = norm_eps self.vocab_size = vocab_size self.pad_token_id = pad_token_id self.max_length = max_length self.kwargs = kwargs
class EncoderBlock(nn.Module): """Transformer encoder block."""
def __init__(self, config: NeoBERTConfig): super().__init__()
self.config = config
# Attention self.qkv = nn.Linear(in_features=config.hidden_size, out_features=config.hidden_size * 3, bias=False) self.wo = nn.Linear(in_features=config.hidden_size, out_features=config.hidden_size, bias=False)
# Feedforward network multiple_of = 8 intermediate_size = int(2 * config.intermediate_size / 3) intermediate_size = multiple_of * ((intermediate_size + multiple_of - 1) // multiple_of) self.ffn = SwiGLU(config.hidden_size, intermediate_size, config.hidden_size, bias=False)
# Layer norms self.attention_norm = nn.RMSNorm(config.hidden_size, config.norm_eps) self.ffn_norm = nn.RMSNorm(config.hidden_size, config.norm_eps)
def forward( self, x: torch.Tensor, attention_mask: torch.Tensor, freqs_cis: torch.Tensor, output_attentions: bool, max_seqlen: int = None, cu_seqlens: torch.Tensor = None, ): # Attention attn_output, attn_weights = self._att_block( self.attention_norm(x), attention_mask, freqs_cis, output_attentions, max_seqlen, cu_seqlens )
# Residual x = x + attn_output
# Feed-forward x = x + self.ffn(self.ffn_norm(x))
return x, attn_weights
def _att_block( self, x: torch.Tensor, attention_mask: torch.Tensor, freqs_cis: torch.Tensor, output_attentions: bool, max_seqlen: int = None, cu_seqlens: torch.Tensor = None, ): batch_size, seq_len, _ = x.shape
xq, xk, xv = self.qkv(x).view(batch_size, seq_len, self.config.num_attention_heads, self.config.dim_head * 3).chunk(3, axis=-1)
xq, xk = apply_rotary_emb(xq, xk, freqs_cis)
# Attn block attn_weights = None
# Flash attention if the tensors are packed if cu_seqlens is not None: attn = flash_attn_varlen_func( q=xq.squeeze(0), k=xk.squeeze(0), v=xv.squeeze(0), cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens, max_seqlen_q=max_seqlen, max_seqlen_k=max_seqlen, dropout_p=0.0, causal=False, ) # Eager attention if attention weights are needed in the output elif output_attentions: attn_weights = xq.permute(0, 2, 1, 3) @ xk.permute(0, 2, 3, 1) / (xq.size(-1) ** 0.5) if attention_mask is not None: attn_weights = attn_weights * attention_mask attn_weights = attn_weights.softmax(-1) attn = attn_weights @ xv.permute(0, 2, 1, 3) attn = attn.transpose(1, 2) # Fall back to SDPA otherwise else: attn = scaled_dot_product_attention( query=xq.transpose(1, 2), key=xk.transpose(1, 2), value=xv.transpose(1, 2), attn_mask=attention_mask.bool(), dropout_p=0, ).transpose(1, 2)
return self.wo(attn.reshape(batch_size, seq_len, self.config.num_attention_heads * self.config.dim_head)), attn_weights
class NeoBERTPreTrainedModel(PreTrainedModel): config_class = NeoBERTConfig base_model_prefix = "model" _supports_cache_class = True
def _init_weights(self, module): if isinstance(module, nn.Linear): module.weight.data.uniform_(-self.config.decoder_init_range, self.config.decoder_init_range) elif isinstance(module, nn.Embedding): module.weight.data.uniform_(-self.config.embedding_init_range, self.config.embedding_init_range)
class NeoBERT(NeoBERTPreTrainedModel): config_class = NeoBERTConfig
def __init__(self, config: NeoBERTConfig): super().__init__(config)
self.config = config
self.encoder = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
# Ensures freqs_cis is moved to the same devices as the model. Non-persistent buffers are not saved in the state_dict. freqs_cis = precompute_freqs_cis(config.hidden_size // config.num_attention_heads, config.max_length) self.register_buffer("freqs_cis", freqs_cis, persistent=False)
self.transformer_encoder = nn.ModuleList() for _ in range(config.num_hidden_layers): self.transformer_encoder.append(EncoderBlock(config))
self.layer_norm = nn.RMSNorm(config.hidden_size, config.norm_eps)
# Initialize weights and apply final processing self.post_init()
def forward( self, input_ids: Optional[torch.Tensor] = None, position_ids: torch.Tensor = None, max_seqlen: int = None, cu_seqlens: torch.Tensor = None, attention_mask: torch.Tensor = None, inputs_embeds: Optional[torch.Tensor] = None, output_hidden_states: bool = False, output_attentions: bool = False, **kwargs, ): # Initialize hidden_states, attentions = [], []
if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
# Expand and repeat: (Batch, Length) -> (Batch, Heads, Length, Length) if attention_mask is not None: attention_mask = attention_mask.unsqueeze(1).unsqueeze(1).repeat(1, self.config.num_attention_heads, attention_mask.size(-1), 1)
# Checks to be done if inputs are packed sequences if cu_seqlens is not None: assert ( FLASH_ATTN_AVAILABLE ), "Flash-attention is not available. Please ''pip install flash_attn'', or provide un-packed sequences." assert not output_attentions, "Output attentions is not supported when sequences are packed." assert max_seqlen is not None, "Missing max_seqlen. It must be provided when cu_seqlens are not None." assert (input_ids if input_ids is not None else inputs_embeds).shape[ 0 ] == 1, "Cumulative sequence lengths are provided but inputs are not packed." assert ( input_ids if input_ids is not None else inputs_embeds ).is_cuda, "Packing uses an implementation of flash-attention and is only supported on GPU."
# RoPE freqs_cis = ( self.freqs_cis[position_ids] if position_ids is not None else self.freqs_cis[: (input_ids if input_ids is not None else inputs_embeds).shape[1]].unsqueeze(0) )
# Embedding x = self.encoder(input_ids) if input_ids is not None else inputs_embeds
# Transformer encoder for layer in self.transformer_encoder: x, attn = layer(x, attention_mask, freqs_cis, output_attentions, max_seqlen, cu_seqlens) if output_hidden_states: hidden_states.append(x) if output_attentions: attentions.append(attn)
# Final normalization layer x = self.layer_norm(x)
# Return the output of the last hidden layer return BaseModelOutput( last_hidden_state=x, hidden_states=hidden_states if output_hidden_states else None, attentions=attentions if output_attentions else None, )
class NeoBERTLMHead(NeoBERTPreTrainedModel): config_class = NeoBERTConfig
def __init__(self, config: NeoBERTConfig): super().__init__(config)
self.config = config
self.model = NeoBERT(config) self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
self.post_init()
def forward( self, input_ids: torch.Tensor, position_ids: torch.Tensor = None, max_seqlen: int = None, cu_seqlens: torch.Tensor = None, attention_mask: torch.Tensor = None, output_hidden_states: bool = False, output_attentions: bool = False, **kwargs, ):
output = self.model.forward( input_ids=input_ids, position_ids=position_ids, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens, attention_mask=attention_mask, output_hidden_states=output_hidden_states, output_attentions=output_attentions, ) logits = self.decoder(output.last_hidden_state)
return MaskedLMOutput( hidden_states=output.hidden_states if output_hidden_states else None, attentions=output.attentions if output_attentions else None, logits=logits, )
class NeoBERTForSequenceClassification(NeoBERTPreTrainedModel): config_class = NeoBERTConfig
def __init__(self, config: NeoBERTConfig): super().__init__(config)
self.config = config
self.num_labels = getattr(config, "num_labels", 2) self.classifier_dropout = getattr(config, "classifier_dropout", 0.1) self.classifier_init_range = getattr(config, "classifier_init_range", 0.02)
self.model = NeoBERT(config)
self.dense = nn.Linear(self.config.hidden_size, self.config.hidden_size) self.dropout = nn.Dropout(self.classifier_dropout) self.classifier = nn.Linear(self.config.hidden_size, self.num_labels)
self.post_init()
def _init_weights(self, module): if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=self.classifier_init_range) if module.bias is not None: module.bias.data.zero_()
def forward( self, input_ids: Optional[torch.Tensor] = None, position_ids: torch.Tensor = None, max_seqlen: int = None, cu_seqlens: torch.Tensor = None, attention_mask: torch.Tensor = None, output_hidden_states: bool = False, output_attentions: bool = False, labels: Optional[torch.Tensor] = None, return_dict: Optional[bool] = None, ): return_dict = return_dict if return_dict is not None else self.config.use_return_dict output = self.model.forward( input_ids=input_ids, position_ids=position_ids, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens, attention_mask=attention_mask, output_hidden_states=output_hidden_states, output_attentions=output_attentions, ) hidden_states = output.last_hidden_state
x = hidden_states[:, 0, :] x = self.dropout(x) x = self.dense(x) x = torch.tanh(x) x = self.dropout(x)
logits = self.classifier(x)
loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(logits.squeeze(), labels.squeeze()) else: loss = loss_fct(logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(logits, labels)
if not return_dict: result = (logits,) return ((loss,) + result) if loss is not None else result
return SequenceClassifierOutput( loss=loss, logits=logits, hidden_states=output.hidden_states if output_hidden_states else None, attentions=output.attentions if output_attentions else None, )123version https://git-lfs.github.com/spec/v1oid sha256:d24b68c316381d1e5dc93afbd1d1c52a19ce579ac940b4750c2215ba9587944csize 119253843212345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# From https://github.com/facebookresearch/llama/blob/main/llama/model.py
import torchfrom typing import Tuple
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0): """ Precompute the frequency tensor for complex exponentials (cis) with given dimensions.
This function calculates a frequency tensor with complex exponentials using the given dimension 'dim' and the end index 'end'. The 'theta' parameter scales the frequencies. The returned tensor contains complex values in complex64 data type.
Args: dim (int): Dimension of the frequency tensor. end (int): End index for precomputing frequencies. theta (float, optional): Scaling factor for frequency computation. Defaults to 10000.0.
Returns: torch.Tensor: Precomputed frequency tensor with complex exponentials. """
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) t = torch.arange(end, device=freqs.device) freqs = torch.outer(t, freqs).float() return torch.polar(torch.ones_like(freqs), freqs)
def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor): assert freqs_cis.shape[1:] == (x.shape[1], x.shape[-1]) return freqs_cis.contiguous().unsqueeze(2)
def apply_rotary_emb( xq: torch.Tensor, xk: torch.Tensor, freqs_cis: torch.Tensor,) -> Tuple[torch.Tensor, torch.Tensor]: """ Apply rotary embeddings to input tensors using the given frequency tensor.
This function applies rotary embeddings to the given query 'xq' and key 'xk' tensors using the provided frequency tensor 'freqs_cis'. The input tensors are reshaped as complex numbers, and the frequency tensor is reshaped for broadcasting compatibility. The resulting tensors contain rotary embeddings and are returned as real tensors.
Args: xq (torch.Tensor): Query tensor to apply rotary embeddings. xk (torch.Tensor): Key tensor to apply rotary embeddings. freqs_cis (torch.Tensor): Precomputed frequency tensor for complex exponentials.
Returns: Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings. """ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2)) xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2)) freqs_cis = reshape_for_broadcast(freqs_cis, xq_) xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3) xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3) return xq_out.type_as(xq), xk_out.type_as(xk)12345678910{ "additional_special_tokens": [ "[+]" ], "cls_token": "[CLS]", "mask_token": "[MASK]", "pad_token": "[PAD]", "sep_token": "[SEP]", "unk_token": "[UNK]"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158from typing import List, Tuplefrom transformers import PreTrainedTokenizerFastimport reimport fast_disambig
_TATWEEL_RE = re.compile(r"\u0640")_ALIF_RE = re.compile(r"[آأإٱ]")_ALIF_MAK_RE = re.compile(r"ى")_TEH_MARB_RE = re.compile(r"ة")_ZERO_WIDTH_RE = re.compile(r"[\u200B-\u200D\u200E\u200F\uFEFF]")ARABIC_DIACRITICS = { "ً", "ٌ", "ٍ", "َ", "ُ", "ِ", "ّ", "ْ", "ٗ", "٘", "ٙ", "ٚ", "ٛ", "ٜ", "ٝ", "ٞ", "ٟ", "ؐ", "ؑ", "ؒ", "ؓ", "ؔ", "ؕ", "ؖ", "ؗ", "ؘ", "ؙ", "ؚ", "ۖ", "ۗ", "ۘ", "ۙ", "ۚ", "ۛ", "ۜ", "۟", "۠", "ۡ", "ۢ", "ۣ", "ۤ", "ۧ", "ۨ", "۪", "۫", "۬", "ۭ",}
def separate_diacritics(text): tokens = re.split(r'(\s+|\[\+\])', text) processed_tokens = []
for token in tokens: if not token: continue if token.isspace() or token == '[+]': processed_tokens.append(token) continue
if not any(c in ARABIC_DIACRITICS for c in token): processed_tokens.append(token) continue
base_chars = [] diac_groups = []
for char in token: if char in ARABIC_DIACRITICS: if not diac_groups: base_chars.append(" ") diac_groups.append([]) diac_groups[-1].append(char) else: base_chars.append(char) diac_groups.append([])
base_word = "".join(base_chars) diac_string = [] for group in diac_groups: if group: diac_string.append("".join(group)) else: diac_string.append("◌")
processed_tokens.append(base_word + " " + "".join(diac_string)) return "".join(processed_tokens)
def normalize_arabic(text): text = _TATWEEL_RE.sub("", text) text = _ZERO_WIDTH_RE.sub("", text) text = _ALIF_RE.sub("ا", text) text = _ALIF_MAK_RE.sub("ي", text) text = _TEH_MARB_RE.sub("ه", text) return text
class ArabicMorphTokenizer(PreTrainedTokenizerFast): slow_tokenizer_class = None
def __init__(self, tokenizer_file=None, apply_stemming=True, **kwargs): super().__init__(tokenizer_file=tokenizer_file, **kwargs) self.apply_stemming = apply_stemming if self.apply_stemming: self.stemmer = fast_disambig.camel.Stemmer()
def _preprocess_one(self, s, do_stem): if isinstance(s, (list, tuple)): return [self._preprocess_one(x, do_stem) for x in s] if do_stem: s = self.stemmer.stem(s, preserve_diacritics=True) s = normalize_arabic(s) s = separate_diacritics(s) return s
def _preprocess_pair(self, text, text_pair, do_stem): def maybe(s): return self._preprocess_one(s, do_stem) if isinstance(s, str) else s if isinstance(text, (list, tuple)): text = [maybe(x) for x in text] else: text = maybe(text) if isinstance(text_pair, (list, tuple)): text_pair = [maybe(x) for x in text_pair] else: text_pair = maybe(text_pair) return text, text_pair
def _pop_flag(self, kwargs): v = kwargs.pop("apply_stemming", None) return self.apply_stemming if v is None else bool(v)
def __call__(self, text=None, text_pair=None, *args, **kwargs): flag = self._pop_flag(kwargs) if not getattr(self, "_processing", False): self._processing = True try: text, text_pair = self._preprocess_pair(text, text_pair, flag) return super().__call__(text=text, text_pair=text_pair, *args, **kwargs) finally: self._processing = False return super().__call__(text=text, text_pair=text_pair, *args, **kwargs)
def encode(self, text, text_pair=None, *args, **kwargs): flag = self._pop_flag(kwargs) if not getattr(self, "_processing", False): self._processing = True try: text, text_pair = self._preprocess_pair(text, text_pair, flag) return super().encode(text, text_pair, *args, **kwargs) finally: self._processing = False return super().encode(text, text_pair, *args, **kwargs)
def encode_plus(self, text=None, text_pair=None, *args, **kwargs): flag = self._pop_flag(kwargs) if not getattr(self, "_processing", False): self._processing = True try: text, text_pair = self._preprocess_pair(text, text_pair, flag) return super().encode_plus(text=text, text_pair=text_pair, *args, **kwargs) finally: self._processing = False return super().encode_plus(text=text, text_pair=text_pair, *args, **kwargs)
def batch_encode_plus(self, batch_text_or_text_pairs=None, *args, **kwargs): flag = self._pop_flag(kwargs) if not getattr(self, "_processing", False): self._processing = True try: data = batch_text_or_text_pairs if isinstance(data, (list, tuple)): new_data = [] for item in data: if isinstance(item, (list, tuple)) and len(item) == 2: new_data.append(self._preprocess_pair(item[0], item[1], flag)) else: new_data.append(self._preprocess_one(item, flag)) batch_text_or_text_pairs = new_data return super().batch_encode_plus(batch_text_or_text_pairs=batch_text_or_text_pairs, *args, **kwargs) finally: self._processing = False return super().batch_encode_plus(batch_text_or_text_pairs=batch_text_or_text_pairs, *args, **kwargs)
def preprocess(self, text, apply_stemming=True): flag = self.apply_stemming if apply_stemming is None else bool(apply_stemming) return self._preprocess_one(text, flag)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172{ "added_tokens_decoder": { "0": { "content": "[PAD]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "1": { "content": "[UNK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "2": { "content": "[CLS]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "3": { "content": "[SEP]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "4": { "content": "[MASK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "5": { "content": "[+]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "additional_special_tokens": [ "[+]" ], "clean_up_tokenization_spaces": false, "cls_token": "[CLS]", "do_lower_case": false, "extra_special_tokens": {}, "mask_token": "[MASK]", "model_max_length": 1000000000000000019884624838656, "pad_token": "[PAD]", "sep_token": "[SEP]", "strip_accents": null, "tokenize_chinese_chars": true, "tokenizer_class": "ArabicMorphTokenizer", "trust_remote_code": true, "unk_token": "[UNK]", "auto_map": { "AutoTokenizer": ["tokenizer.ArabicMorphTokenizer", null] }, "apply_stemming": true}README.mdAdded+36
config.jsonAdded+31
model.pyAdded+444
model.safetensorsAdded+3
rotary.pyAdded+61
special_tokens_map.jsonAdded+10
tokenizer.jsonAdded
tokenizer.pyAdded+158
tokenizer_config.jsonAdded+72
vocab.txtAdded