Text Generation
Transformers
Burmese
English
myanmar
burmese
llm
chat
instruction-following
conversational
autoregressive
Instructions to use amkyawdev/myanmar-ghost with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use amkyawdev/myanmar-ghost with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="amkyawdev/myanmar-ghost") messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("amkyawdev/myanmar-ghost", dtype="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use amkyawdev/myanmar-ghost with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "amkyawdev/myanmar-ghost" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "amkyawdev/myanmar-ghost", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/amkyawdev/myanmar-ghost
- SGLang
How to use amkyawdev/myanmar-ghost with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "amkyawdev/myanmar-ghost" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "amkyawdev/myanmar-ghost", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "amkyawdev/myanmar-ghost" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "amkyawdev/myanmar-ghost", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use amkyawdev/myanmar-ghost with Docker Model Runner:
docker model run hf.co/amkyawdev/myanmar-ghost
File size: 5,272 Bytes
cfb5e7f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | """Transformer-based sentiment model for Myanmar text."""
import logging
from typing import Any, Dict, Optional
import torch
import torch.nn as nn
from transformers import (
AutoConfig,
AutoModel,
AutoModelForSequenceClassification,
AutoTokenizer,
)
from .base_model import BaseModel
logger = logging.getLogger(__name__)
class TransformerSentimentModel(BaseModel):
"""Transformer-based sentiment classification model."""
def __init__(
self,
model_name: str = "bert-base-multilingual-cased",
num_labels: int = 4,
dropout: float = 0.1,
freeze_encoder: bool = False,
):
"""
Args:
model_name: Pretrained model name
num_labels: Number of sentiment labels
dropout: Dropout rate
freeze_encoder: Whether to freeze encoder weights
"""
super().__init__()
self.model_name = model_name
self.num_labels = num_labels
# Load pretrained config
self.config = AutoConfig.from_pretrained(model_name)
# Load pretrained model
self.transformer = AutoModel.from_pretrained(model_name)
# Classification head
self.dropout = nn.Dropout(dropout)
self.classifier = nn.Linear(self.config.hidden_size, num_labels)
# Freeze encoder if requested
if freeze_encoder:
for param in self.transformer.parameters():
param.requires_grad = False
self.to(self.device)
def forward(
self,
input_ids: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
) -> torch.Tensor:
"""Forward pass."""
outputs = self.transformer(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
)
# Use [CLS] token representation
pooled_output = outputs.last_hidden_state[:, 0, :]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
return logits
def predict(
self,
texts: list,
tokenizer,
batch_size: int = 16,
) -> Dict[str, Any]:
"""Make predictions on texts."""
self.eval()
all_probs = []
with torch.no_grad():
for i in range(0, len(texts), batch_size):
batch_texts = texts[i:i + batch_size]
encoding = tokenizer(
batch_texts,
padding=True,
truncation=True,
max_length=512,
return_tensors="pt",
)
input_ids = encoding["input_ids"].to(self.device)
attention_mask = encoding["attention_mask"].to(self.device)
logits = self.forward(input_ids, attention_mask)
probs = torch.softmax(logits, dim=-1)
all_probs.append(probs.cpu().numpy())
import numpy as np
all_probs = np.vstack(all_probs)
sentiment_labels = ["negative", "neutral", "positive", "sarcastic"]
predictions = []
for i, probs in enumerate(all_probs):
pred_idx = probs.argmax()
predictions.append({
"text": texts[i],
"sentiment": sentiment_labels[pred_idx],
"confidence": probs[pred_idx],
"probabilities": {
label: probs[j] for j, label in enumerate(sentiment_labels)
},
})
return {"predictions": predictions}
def extract_features(
self,
input_ids: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
"""Extract hidden features."""
outputs = self.transformer(
input_ids=input_ids,
attention_mask=attention_mask,
)
return outputs.last_hidden_state
def load_pretrained_model(
model_path: str,
num_labels: int = 4,
) -> TransformerSentimentModel:
"""Load a pretrained model from path or HuggingFace."""
# Check if it's a HuggingFace model
if "/" in model_path:
return TransformerSentimentModel(
model_name=model_path,
num_labels=num_labels,
)
# Load from local checkpoint
model = TransformerSentimentModel(num_labels=num_labels)
checkpoint = torch.load(model_path, map_location="cpu")
if "model_state_dict" in checkpoint:
model.load_state_dict(checkpoint["model_state_dict"])
elif "model" in checkpoint:
model.transformer = checkpoint["model"]
return model
if __name__ == "__main__":
print("Testing TransformerSentimentModel...")
model = TransformerSentimentModel(
model_name="bert-base-multilingual-cased",
num_labels=4,
)
print(f"Total parameters: {model.get_num_parameters():,}")
print(f"Trainable parameters: {model.get_num_trainable_parameters():,}")
|