Instructions to use themohal/saraiki-roberta-nlu with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use themohal/saraiki-roberta-nlu with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="themohal/saraiki-roberta-nlu")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("themohal/saraiki-roberta-nlu", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Saraiki RoBERTa NLU (multi-task)
One shared Saraiki RoBERTa encoder with a linear head per label space. It covers 8 tasks:
| Task | Head(s) | Input | Output |
|---|---|---|---|
| POS | pos |
list of words | UPOS tag per word |
| NER | ner |
list of words | BIO tag per word |
| Sentiment | sentiment, emotion, sarcasm |
one sentence | 3 labels |
| Hate speech | hate |
one sentence | class |
| Dialect | dialect, dialect_macro |
one sentence | micro variety + macro region |
| SIB topic | sib |
one sentence | topic category |
| XNLI | xnli |
premise + hypothesis | entailment / neutral / contradiction |
| Language ID | lid |
one sentence | language code (Perso-Arabic scripts) |
The repo has no transformers head class, so you load the encoder and the heads yourself (code below). Label lists are stored in tasks.json.
Repo files
encoder/ # RoBERTa encoder (save_pretrained)
heads.safetensors # all linear heads
tasks.json # labels, cls_heads, token_tasks, max_len, eval scores
tokenizer files
Install
pip install torch transformers huggingface_hub safetensors
Load the model (once)
import json, os, torch, torch.nn as nn
from huggingface_hub import snapshot_download
from safetensors.torch import load_file
from transformers import AutoModel, AutoTokenizer
REPO = "themohal/saraiki-roberta-nlu"
DEV = "cuda:0" if torch.cuda.is_available() else "cpu"
local = snapshot_download(REPO, allow_patterns=[
"encoder/*", "heads.safetensors", "tasks.json", "tokenizer*", "vocab.json",
"merges.txt", "special_tokens_map.json", "added_tokens.json"])
cfg = json.load(open(os.path.join(local, "tasks.json"), encoding="utf-8"))
LABELS, CLS_HEADS, TOKEN_TASKS, MAX_LEN = cfg["labels"], cfg["cls_heads"], cfg["token_tasks"], cfg["max_len"]
class MultiTaskModel(nn.Module):
def __init__(self, encoder, labels):
super().__init__()
self.encoder = encoder
h = encoder.config.hidden_size
self.heads = nn.ModuleDict({k: nn.Linear(h, len(v)) for k, v in labels.items()})
def forward(self, task, input_ids, attention_mask):
hs = self.encoder(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
if task in TOKEN_TASKS: # pos, ner: one prediction per token
return self.heads[task](hs)
pooled = hs[:, 0] # all other tasks: <s> token
return {name: self.heads[name](pooled) for name in CLS_HEADS[task]}
try:
enc = AutoModel.from_pretrained(os.path.join(local, "encoder"), add_pooling_layer=False)
except TypeError:
enc = AutoModel.from_pretrained(os.path.join(local, "encoder"))
model = MultiTaskModel(enc, LABELS)
model.heads.load_state_dict(load_file(os.path.join(local, "heads.safetensors")))
model.to(DEV).eval()
# byte-level BPE needs add_prefix_space=True (the same tokenizer setup was used in training)
try:
tok = AutoTokenizer.from_pretrained(local, use_fast=True, add_prefix_space=True)
except Exception:
tok = AutoTokenizer.from_pretrained(local, use_fast=True)
Inference helpers
@torch.no_grad()
def predict_words(task, words):
"""Token tasks (pos, ner). `words` = already split list of words."""
e = tok([words], is_split_into_words=True, truncation=True,
max_length=MAX_LEN, return_tensors="pt").to(DEV)
pred = model(task, e["input_ids"], e["attention_mask"]).argmax(-1)[0].tolist()
out, prev = [], None
for pos, w in enumerate(e.word_ids(0)): # first sub-word of each word = its label
if w is not None and w != prev:
out.append((words[w], LABELS[task][pred[pos]]))
prev = w
return out
@torch.no_grad()
def predict_text(task, text):
"""Sentence tasks (sentiment, hate, dialect, sib, lid). Returns {head: label}."""
e = tok([text], truncation=True, max_length=MAX_LEN, return_tensors="pt").to(DEV)
lg = model(task, e["input_ids"], e["attention_mask"])
return {name: LABELS[name][v.argmax(-1).item()] for name, v in lg.items()}
@torch.no_grad()
def predict_pair(premise, hypothesis):
"""XNLI: premise + hypothesis encoded together as ONE sequence."""
e = tok([premise], [hypothesis], truncation=True, max_length=MAX_LEN, return_tensors="pt").to(DEV)
lg = model("xnli", e["input_ids"], e["attention_mask"])
return {name: LABELS[name][v.argmax(-1).item()] for name, v in lg.items()}
@torch.no_grad()
def predict_text_proba(task, text):
"""Same as predict_text but returns the full probability distribution per head."""
e = tok([text], truncation=True, max_length=MAX_LEN, return_tensors="pt").to(DEV)
lg = model(task, e["input_ids"], e["attention_mask"])
return {name: dict(zip(LABELS[name], v.softmax(-1)[0].tolist())) for name, v in lg.items()}
How to infer, task by task
1. POS (pos)
Input is a list of words, not a raw string. Split on whitespace first. Output is one UPOS tag per word.
words = "تہاڈا ناں کیا ہے".split()
print(predict_words("pos", words))
# [(word, 'PRON'), (word, 'NOUN'), ...]
2. NER (ner)
Same input as POS. Output is a BIO tag per word (O, B-<TYPE>, I-<TYPE>).
words = "..".split()
tags = predict_words("ner", words)
def to_entities(tagged):
ents, cur = [], None
for w, t in tagged:
if t.startswith("B-") or (t.startswith("I-") and (cur is None or cur[0] != t[2:])):
if cur: ents.append(cur)
cur = [t[2:], [w]]
elif t.startswith("I-") and cur:
cur[1].append(w)
else:
if cur: ents.append(cur)
cur = None
if cur: ents.append(cur)
return [(typ, " ".join(ws)) for typ, ws in ents]
print(to_entities(tags)) # [('PER', '...'), ('LOC', '...')]
3. Sentiment, emotion, sarcasm (sentiment)
One call returns three heads. Sarcasm labels are "false" / "true".
print(predict_text("sentiment", "..."))
# {'sentiment': '...', 'emotion': '...', 'sarcasm': 'false'}
4. Hate speech (hate)
Trained on the Saraiki-script column only, so give it Saraiki text.
print(predict_text("hate", "..."))
# {'hate': '<label_name>'}
5. Dialect (dialect)
Two heads: the micro variety (8 local varieties) and the macro region group.
print(predict_text("dialect", "..."))
# {'dialect': 'multani', 'dialect_macro': 'central'}
6. SIB topic classification (sib)
One sentence in, one topic category out.
print(predict_text("sib", "..."))
# {'sib': '<category>'}
7. XNLI (xnli)
Takes a sentence pair. Do not concatenate the two strings yourself; use predict_pair.
Labels are entailment, neutral, contradiction.
print(predict_pair("premise sentence", "hypothesis sentence"))
# {'xnli': 'entailment'}
8. Language ID (lid)
Predicts one of the Perso-Arabic-script languages, including Saraiki (Brahui is dropped).
print(predict_text("lid", "..."))
# {'lid': 'skr'}
Notes
- Max input length is 256 sub-word tokens (
MAX_LEN); longer text is truncated. - Always call
model.eval()and usetorch.no_grad()(the helpers already do). - The full list of valid labels per head is in
tasks.json->labels. - SIB and XNLI labels come from LLM translations of English data, so check outputs by hand before trusting them.
- LID was trained on formal Wikipedia-style text, so expect lower accuracy on informal social-media text.
- Dialect is trained from POS/NER sentences, so it works best on sentences similar to that data.
- Eval scores for the published step are in
tasks.json->eval.
Model tree for themohal/saraiki-roberta-nlu
Base model
FacebookAI/roberta-base