Views
No views yet
10.18653/v1/2026.semeval-1.25Qualcomm-AI-Research/BamiBERT.| Evaluation Split | Accuracy | F1-Score (Macro) | Precision (Macro) | Recall (Macro) |
|---|---|---|---|---|
| 5-Fold Validation (Mean) | 0.9124 | 0.9045 | 0.9052 | 0.9089 |
| Public Test Set | 0.9086 | 0.9068 | 0.9052 | 0.9089 |
| Test Set | Accuracy | F1-Score (Macro) | Precision (Macro) | Recall (Macro) |
|---|---|---|---|---|
| Full Training | 0.9086 | 0.9068 | 0.9052 | 0.9089 |
| Freezed-first-3-layers | 0.9015 | 0.8991 | 0.8989 | 0.8993 |
| Freezed-first-6-layers | - | - | - | - |
MoEClassifier dynamically routed token representations through \(K=2\) selected experts out of \(N=4\) available experts per forward pass. The Macro F1-Score tracking across each individual validation fold is recorded as follows:
BamiBertMoePredictor wrapper for inference on sentiment analysis tasks.VnCoreNLP) or if you cannot use this tool, you could use pyvi.!pip install torch transformers huggingface_hub safetensors1import os
2import torch
3import torch.nn as nn
4import torch.nn.functional as F
5from transformers import AutoTokenizer, AutoConfig
6from huggingface_hub import hf_hub_download
7from safetensors.torch import load_file
8from vncorenlp import VnCoreNLP
9
10class BamiBertMoePredictor:
11 """
12 Production-ready Wrapper for the BamiBERT-MoE Sentiment Analysis network.
13 Dynamically loads configuration properties from Hugging Face Hub and
14 handles end-to-end inference processing.
15 """
16 def __init__(self, repo_id: str, vncorenlp_path: str, device: str = 'cuda'):
17 """
18 Initializes tokenizer, remote configurations, custom MoE layers, and weights.
19
20 Args:
21 repo_id (str): Hugging Face Repository identifier.
22 vncorenlp_path (str): File path to the VnCoreNLP compiled .jar tool.
23 device (str): Execution hardware allocation ('cuda' or 'cpu').
24 """
25 self.device = torch.device(device if torch.cuda.is_available() else 'cpu')
26
27 print(f"Fetching Tokenizer & Config from Hub: {repo_id}...")
28 self.tokenizer = AutoTokenizer.from_pretrained(repo_id)
29 hf_config = AutoConfig.from_pretrained(repo_id)
30
31 # Inject dynamic hyperparameter definitions from remote config
32 self.config = hf_config
33 self.config.model_name = getattr(hf_config, "_name_or_path", "Qualcomm-AI-Research/BamiBERT")
34 self.config.max_len = getattr(hf_config, "max_len", 128)
35 self.config.num_classes = getattr(hf_config, "num_classes", 2)
36 self.config.num_experts = getattr(hf_config, "num_experts", 4)
37 self.config.selection_k = getattr(hf_config, "selection_k", 2)
38 self.config.vncorenlp_path = vncorenlp_path
39
40 print("Initializing MoEBanhMiBert architecture...")
41 self.model = MoEBanhMiBert(self.config)
42
43 print("Pulling model.safetensors artifacts from Hub...")
44 weights_path = hf_hub_download(repo_id=repo_id, filename="model.safetensors")
45
46 print("➔ Injecting safe weights into model structure...")
47 safetensors_weights = load_file(weights_path)
48 self.model.load_state_dict(safetensors_weights)
49 self.model.to(self.device)
50 self.model.eval()
51
52 print("Spawning VnCoreNLP Word Segmenter token pipeline...")
53 self.segmenter = VnCoreNLP(self.config.vncorenlp_path, annotators="wseg")
54 print("ARTIFACT LOADING COMPLETE! Predictor framework ready.")
55
56 def predict(self, text: str) -> dict:
57 """
58 Executes end-to-end sentiment tracking over raw input strings.
59
60 Args:
61 text (str): Raw unstructured text query.
62
63 Returns:
64 dict: Structured outcomes containing mapped label and confidence rate.
65 """
66 # Execute text normalization mapping and syllable compound splitting
67 cleaned = clean_text(text)
68 word_segment = self.segmenter.tokenize(cleaned)
69 segmented = " ".join(w for sentence in word_segment for w in sentence)
70
71 # Generate model input tensors matching specific maximum limits
72 inputs = self.tokenizer(
73 segmented,
74 return_tensors="pt",
75 padding="max_length",
76 truncation=True,
77 max_length=self.config.max_len
78 )
79 inputs = {k: v.to(self.device) for k, v in inputs.items()}
80
81 # Run isolated forward execution layer
82 with torch.no_grad():
83 outputs = self.model(**inputs)
84 logits = outputs[0] if isinstance(outputs, tuple) else outputs
85 probs = F.softmax(logits, dim=-1)
86 prediction = torch.argmax(probs, dim=-1).item()
87 confidence = probs[0][prediction].item()
88
89 label_map = {0: "Negative", 1: "Positive"}
90 return {
91 "text": text,
92 "label": label_map[prediction],
93 "confidence": f"{confidence * 100:.2f}%"
94 }
95
96# --- STANDALONE MODEL EXECUTION FLOW ---
97if __name__ == "__main__":
98 REPO_ID = "TheSon2202/bamibert-moe-sentiment"
99 VNCORENLP_PATH = "VnCoreNLP/VnCoreNLP-1.1.1.jar"
100
101 # Instantiate clean predictor sequence from shared storage weights
102 predictor = BamiBertMoePredictor(repo_id=REPO_ID, vncorenlp_path=VNCORENLP_PATH)
103
104 print("\n" + "="*60)
105 print("RUNNING MOE SENTIMENT INFERENCE BENCHMARK")
106 print("="*60)
107
108 # Evaluated test sample collection (1 Positive, 1 Negative)
109 test_cases = [
110 "Sản phẩm dùng đỉnh thực sự, giao hàng siêu nhanh, đóng gói rất cẩn thận!",
111 "đồ ăn ở đây ngon quá đi, nhưng dịch vụ tệ quá, cho 1 sao"
112 ]
113
114 for text in test_cases:
115 res = predictor.predict(text)
116 print(f"Raw Comment : {res['text']}")
117 print(f"Predicted : {res['label']} ({res['confidence']})")
118 print("-" * 60)1{
2 "text": "Đồ ở shop này xài bao ngon luôn á, chấm 10 điểm!",
3 "label": "Positive",
4 "confidence": "69.13%"
5}1{
2 "text": 'đồ ăn ở đây ngon quá đi, nhưng dịch vụ tệ quá, cho 1 sao',
3 "label": 'Negative',
4 "confidence": '61.16%'
5}1@article{BamiBERT,
2 title = {{BamiBERT: A New BERT-based Language Model for Vietnamese}},
3 author = {Dat Quoc Nguyen and Thinh Pham and Chi Tran and Linh The Nguyen},
4 journal = {arXiv preprint},
5 volume = {arXiv:2607.02259},
6 year = {2026}
7}