Text Generation
Transformers
Safetensors
qwen2
coder
code
agent
conversational
text-generation-inference
Instructions to use AdminReal/NexusCoder with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use AdminReal/NexusCoder with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="AdminReal/NexusCoder") messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("AdminReal/NexusCoder") model = AutoModelForCausalLM.from_pretrained("AdminReal/NexusCoder", device_map="auto") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=40) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use AdminReal/NexusCoder with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "AdminReal/NexusCoder" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "AdminReal/NexusCoder", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/AdminReal/NexusCoder
- SGLang
How to use AdminReal/NexusCoder 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 "AdminReal/NexusCoder" \ --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": "AdminReal/NexusCoder", "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 "AdminReal/NexusCoder" \ --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": "AdminReal/NexusCoder", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use AdminReal/NexusCoder with Docker Model Runner:
docker model run hf.co/AdminReal/NexusCoder
File size: 10,636 Bytes
eca5751 | 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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | """
Model Evaluator Tool - Đánh giá ML model trên dataset.
===========================================
Lazy import torch / sklearn. Tải model + dataset, chạy inference,
tính metrics (reuse ml_metrics_tool logic).
Author: Hieu Louis (2026)
"""
from __future__ import annotations
import csv
import json
import os
from typing import Any, Dict, List, Optional
from .base import Tool, ToolResult, ToolContext, ToolCategory, ToolSafety
TASKS = {"classification", "regression"}
DATASET_FORMATS = {"csv", "jsonl", "json", "npy"}
class ModelEvaluatorTool(Tool):
"""Đánh giá ML model (sklearn / PyTorch) trên dataset."""
category = ToolCategory.ML
safety = ToolSafety.MODERATE
requires_confirmation = True
@property
def name(self) -> str:
return "model_evaluator"
@property
def description(self) -> str:
return "Evaluate ML model trên dataset (sklearn/torch) với metrics tùy chọn."
@property
def parameters(self) -> Dict[str, Any]:
return {
"type": "object",
"properties": {
"model_path": {"type": "string", "description": "Đường dẫn file model (.pkl/.joblib/.pt/.pth)"},
"dataset_path": {"type": "string", "description": "Dataset file (.csv/.jsonl/.json/.npy)"},
"task": {
"type": "string",
"enum": sorted(TASKS),
"default": "classification",
},
"metrics": {
"type": "array",
"items": {"type": "string"},
"description": "Metrics cần tính (bỏ qua → tính tất cả)",
},
"feature_cols": {"type": "array", "items": {"type": "string"}, "description": "CSV: tên cột feature"},
"label_col": {"type": "string", "description": "CSV: tên cột label"},
"framework": {"type": "string", "enum": ["auto", "sklearn", "torch"], "default": "auto"},
"batch_size": {"type": "integer", "default": 64},
},
"required": ["model_path", "dataset_path"],
}
def validate_args(self, args: Dict[str, Any]) -> Optional[str]:
if not args.get("model_path"):
return "Missing required arg: model_path"
if not args.get("dataset_path"):
return "Missing required arg: dataset_path"
task = args.get("task", "classification")
if task not in TASKS:
return f"Invalid task='{task}'. Supported: {sorted(TASKS)}"
return None
# ---- Loaders --------------------------------------------------------
def _load_dataset(self, path: str, feature_cols: List[str], label_col: str) -> Dict[str, Any]:
"""Tải dataset từ CSV/JSON/JSONL/NPY. Trả về {X, y}."""
ext = os.path.splitext(path)[1][1:].lower()
if ext not in DATASET_FORMATS:
raise ValueError(f"Unsupported dataset format: {ext}")
if ext == "csv":
with open(path, "r", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
rows = list(reader)
if not rows:
raise ValueError("Empty CSV")
if not label_col:
# Heuristic: lấy cột cuối / take last column as label
label_col = list(rows[0].keys())[-1]
if not feature_cols:
feature_cols = [c for c in rows[0].keys() if c != label_col]
X: List[List[float]] = []
y: List[Any] = []
for row in rows:
try:
X.append([float(row[c]) for c in feature_cols])
except (ValueError, KeyError):
continue
y.append(row[label_col])
return {"X": X, "y": y, "feature_cols": feature_cols, "label_col": label_col}
if ext == "json":
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
X = data.get("X", [])
y = data.get("y", data.get("labels", []))
else: # list of dicts
X = [[row.get(c) for c in feature_cols] for row in data]
y = [row.get(label_col) for row in data]
return {"X": X, "y": y, "feature_cols": feature_cols, "label_col": label_col}
if ext == "jsonl":
X = []
y = []
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
row = json.loads(line)
X.append([row.get(c) for c in feature_cols] or list(row.values())[:-1])
y.append(row.get(label_col) or list(row.values())[-1])
return {"X": X, "y": y, "feature_cols": feature_cols, "label_col": label_col}
# npy
try:
import numpy as np # type: ignore
arr = np.load(path, allow_pickle=True)
if arr.ndim == 2 and arr.shape[1] >= 2:
X = arr[:, :-1].tolist()
y = arr[:, -1].tolist()
else:
X = arr.tolist()
y = []
return {"X": X, "y": y, "feature_cols": feature_cols, "label_col": label_col}
except ImportError:
raise RuntimeError("numpy chưa cài để load .npy")
# ---- Model loading --------------------------------------------------
def _load_model(self, path: str, framework: str):
"""Tải model. Auto-detect theo extension nếu framework='auto'."""
ext = os.path.splitext(path)[1].lower()
if framework == "auto":
if ext in (".pt", ".pth"):
framework = "torch"
else:
framework = "sklearn"
if framework == "torch":
try:
import torch # type: ignore
except ImportError:
raise RuntimeError("torch chưa cài. Cài đặt: pip install torch")
try:
model = torch.load(path, map_location="cpu", weights_only=False)
except TypeError:
# PyTorch < 2.6 không có weights_only / older PyTorch
model = torch.load(path, map_location="cpu")
model.eval()
return ("torch", model)
# sklearn-style (pickle/joblib)
try:
import joblib # type: ignore
model = joblib.load(path)
return ("sklearn", model)
except ImportError:
import pickle
with open(path, "rb") as f:
return ("sklearn", pickle.load(f))
# ---- Predict --------------------------------------------------------
def _predict(self, backend: str, model: Any, X: List[List[float]], batch_size: int) -> List[Any]:
if backend == "torch":
import torch # type: ignore
preds: List[Any] = []
for i in range(0, len(X), batch_size):
chunk = torch.tensor(X[i:i + batch_size], dtype=torch.float32)
with torch.no_grad():
out = model(chunk)
# Argmax cho classification / raw output cho regression
if out.dim() > 1 and out.shape[1] > 1:
preds.extend(out.argmax(dim=1).tolist())
else:
preds.extend(out.squeeze(-1).tolist())
return preds
# sklearn predict
return list(model.predict(X))
# ---- Execute --------------------------------------------------------
def execute(self, args: Dict[str, Any], context: ToolContext) -> ToolResult:
model_path = args["model_path"]
dataset_path = args["dataset_path"]
task = args.get("task", "classification")
metrics = args.get("metrics", []) or []
feature_cols = args.get("feature_cols", []) or []
label_col = args.get("label_col", "")
framework = args.get("framework", "auto")
batch_size = int(args.get("batch_size", 64))
if context.dry_run:
return ToolResult(
success=True,
output=f"[dry-run] Sẽ evaluate model {model_path} trên {dataset_path} (task={task})",
metadata={"model_path": model_path, "dataset_path": dataset_path, "task": task, "dry_run": True},
)
if not os.path.exists(model_path):
return ToolResult(success=False, error=f"Model file không tồn tại: {model_path}", return_code=1)
if not os.path.exists(dataset_path):
return ToolResult(success=False, error=f"Dataset file không tồn tại: {dataset_path}", return_code=1)
try:
data = self._load_dataset(dataset_path, feature_cols, label_col)
except Exception as e:
return ToolResult(success=False, error=f"Load dataset failed: {e}", return_code=1)
if not data["X"]:
return ToolResult(success=False, error="Dataset rỗng hoặc không có features", return_code=1)
try:
backend, model = self._load_model(model_path, framework)
except Exception as e:
return ToolResult(success=False, error=f"Load model failed: {e}", return_code=1)
try:
preds = self._predict(backend, model, data["X"], batch_size)
except Exception as e:
return ToolResult(success=False, error=f"Inference failed: {e}", return_code=1)
# Tính metrics bằng ml_metrics_tool logic (reuse internal)
from .ml_metrics_tool import MLMetricsTool
metrics_tool = MLMetricsTool()
result = metrics_tool.execute(
{
"y_true": data["y"],
"y_pred": preds,
"task": task,
"metrics": metrics,
},
context,
)
if not result.success:
return result
# Bổ sung metadata của evaluator / attach evaluator metadata
result.metadata.update({
"model_path": model_path,
"dataset_path": dataset_path,
"framework": backend,
"n_samples": len(data["X"]),
"n_features": len(data["X"][0]) if data["X"] else 0,
"feature_cols": data["feature_cols"],
"label_col": data["label_col"],
"predictions": preds,
})
result.output = f"Evaluated {backend} model on {len(data['X'])} samples\n{result.output}"
return result
|