QyupyTzy commited on
Commit
45c06f7
·
verified ·
1 Parent(s): 59843f0

Upload 2 files

Browse files
Files changed (2) hide show
  1. README.md +130 -0
  2. server.py +155 -0
README.md ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: Qwen/Qwen3-4B
4
+ tags:
5
+ - unsloth
6
+ - text-generation
7
+ - education
8
+ - game-generation
9
+ language:
10
+ - id
11
+ pipeline_tag: text-generation
12
+ ---
13
+
14
+ # Panduan Deployment SR4 di RunPod
15
+
16
+ Model ini (`ub-sr04-qwen3.5-4b-cpt2-sft-game`) adalah LLM game content generator untuk platform Sekolah Rakyat. Dijalankan sebagai inference server OpenAI-compatible menggunakan **Unsloth** — bukan vLLM (arsitektur hybrid Qwen3 tidak kompatibel dengan vLLM).
17
+
18
+ > File `server.py` sudah tersedia di repo ini — ikut ter-download bersama model.
19
+
20
+ ---
21
+
22
+ ## Kebutuhan Hardware
23
+
24
+ | GPU | VRAM | Mode |
25
+ |---|---|---|
26
+ | A100 40GB | 40 GB | bfloat16 (~9 GB dipakai) |
27
+ | L4 24GB | 24 GB | bfloat16 atau 4-bit (~3 GB) |
28
+ | T4 16GB | 16 GB | Harus 4-bit |
29
+
30
+ **Storage:** minimal 20 GB · **RAM:** minimal 16 GB CPU
31
+
32
+ ---
33
+
34
+ ## Setup di RunPod
35
+
36
+ ### 1. Buat Pod
37
+
38
+ Di [runpod.io](https://runpod.io) → Deploy:
39
+ - Template: **RunPod PyTorch**
40
+ - Container Disk: 20 GB · Volume: 20 GB (mount ke `/workspace`)
41
+ - Expose port yang diinginkan (default: `8081`)
42
+
43
+ ### 2. Download Model + Server Script
44
+
45
+ ```bash
46
+ huggingface-cli login # butuh token HF dengan akses ke repo ini
47
+
48
+ huggingface-cli download aitf-ub-2026/ub-sr04-qwen3.5-4b-cpt2-sft-game \
49
+ --local-dir /workspace/models/sr4
50
+ ```
51
+
52
+ `server.py` ikut ter-download ke `/workspace/models/sr4/server.py`.
53
+ Model tersimpan di volume persistent — tidak perlu download ulang setelah restart pod.
54
+
55
+ ### 3. Install Dependencies
56
+
57
+ ```bash
58
+ pip install --upgrade pip
59
+ pip install unsloth unsloth_zoo accelerate bitsandbytes
60
+ pip install fastapi "uvicorn[standard]"
61
+ pip install git+https://github.com/huggingface/transformers.git
62
+ ```
63
+
64
+ > `torch` sudah tersedia di RunPod PyTorch template — tidak perlu install ulang.
65
+ > `bitsandbytes` diperlukan untuk mode `--4bit`.
66
+
67
+ ### 4. Jalankan Server
68
+
69
+ ```bash
70
+ # bfloat16 (default)
71
+ python /workspace/models/sr4/server.py --model /workspace/models/sr4 --port 8081
72
+
73
+ # 4-bit — untuk GPU VRAM terbatas (L4, T4)
74
+ python /workspace/models/sr4/server.py --model /workspace/models/sr4 --port 8081 --4bit
75
+ ```
76
+
77
+ Server siap saat muncul log:
78
+ ```
79
+ [SR4] Model loaded — GPU X.X / XX.X GB
80
+ [SR4] Serving on http://0.0.0.0:8081
81
+ ```
82
+
83
+ ### Auto-start setelah Restart
84
+
85
+ RunPod tidak auto-restart service. Tambahkan ke crontab:
86
+
87
+ ```bash
88
+ crontab -e
89
+ # tambahkan:
90
+ @reboot sleep 30 && python /workspace/models/sr4/server.py --model /workspace/models/sr4 --port 8081
91
+ ```
92
+
93
+ ---
94
+
95
+ ## API
96
+
97
+ ### Endpoints
98
+
99
+ ```
100
+ GET /health → {"status": "ok", "model": "..."}
101
+ GET /v1/models → daftar model tersedia
102
+ POST /v1/chat/completions → generate (OpenAI-compatible)
103
+ ```
104
+
105
+ ### Contoh Request
106
+
107
+ ```bash
108
+ curl -X POST http://localhost:8081/v1/chat/completions \
109
+ -H "Content-Type: application/json" \
110
+ -d '{
111
+ "model": "sr4-game",
112
+ "messages": [
113
+ {"role": "system", "content": "...system prompt..."},
114
+ {"role": "user", "content": "{\"difficulty\": 1, \"atps\": [...], \"bacaan\": \"...\"}"}
115
+ ],
116
+ "max_tokens": 3500,
117
+ "temperature": 0.0
118
+ }'
119
+ ```
120
+
121
+ Response field `choices[0].message.content` berisi game JSON (sudah di-strip dari markdown fence dan thinking block).
122
+
123
+ ---
124
+
125
+ ## Catatan
126
+
127
+ - **Chat template:** ChatML (`<|im_start|>` / `<|im_end|>`)
128
+ - **Max seq length:** 4096 token
129
+ - **Thinking dinonaktifkan** — output langsung JSON tanpa blok `<think>`
130
+ - **Log "MISSING: model.visual.\*"** dari Unsloth adalah normal — model ini pure text, tidak ada vision encoder yang aktif saat inference
server.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ scripts/sr4_server.py — SR4 Standalone Inference Server
3
+ Diadaptasi dari docs/aset/SR4_LLM_Coder_Test_Colab(SFT+CPT).ipynb
4
+
5
+ Jalankan:
6
+ python scripts/sr4_server.py --model /workspace/models/sr4 --port 8081
7
+ python scripts/sr4_server.py --model /workspace/models/sr4 --port 8081 --4bit
8
+ """
9
+ import argparse
10
+ import gc
11
+ import json
12
+ import re
13
+ import sys
14
+
15
+ import torch
16
+ import uvicorn
17
+ from fastapi import FastAPI, Request
18
+ from fastapi.responses import JSONResponse
19
+
20
+ parser = argparse.ArgumentParser()
21
+ parser.add_argument("--model", default="/workspace/models/sr4")
22
+ parser.add_argument("--port", type=int, default=8081)
23
+ parser.add_argument("--4bit", dest="load_4bit", action="store_true",
24
+ help="Load in 4-bit quantization (untuk GPU VRAM terbatas, misal L4 24GB)")
25
+ args = parser.parse_args()
26
+
27
+ print(f"[SR4] Loading model dari {args.model} ...", flush=True)
28
+
29
+ from unsloth import FastLanguageModel # noqa: E402 (import setelah argparse)
30
+ from unsloth.chat_templates import get_chat_template # noqa: E402
31
+
32
+ model, tokenizer = FastLanguageModel.from_pretrained(
33
+ model_name =args.model,
34
+ max_seq_length=4096,
35
+ dtype =None,
36
+ load_in_4bit =args.load_4bit,
37
+ )
38
+ FastLanguageModel.for_inference(model)
39
+ tokenizer = get_chat_template(tokenizer, chat_template="chatml")
40
+ _tok = tokenizer.tokenizer if hasattr(tokenizer, "tokenizer") else tokenizer
41
+
42
+ used_gb = torch.cuda.memory_allocated() / 1e9
43
+ total_gb = torch.cuda.get_device_properties(0).total_memory / 1e9
44
+ print(f"[SR4] Model loaded — GPU {used_gb:.1f} / {total_gb:.1f} GB", flush=True)
45
+
46
+ app = FastAPI(title="SR4 Inference Server")
47
+
48
+
49
+ def _strip_thinking(text: str) -> str:
50
+ """Hapus blok <think>...</think> jika model mengeluarkannya."""
51
+ return re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
52
+
53
+
54
+ def _parse_json(text: str):
55
+ """Coba ekstrak JSON object dari teks bebas."""
56
+ text = _strip_thinking(text)
57
+ text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text, flags=re.MULTILINE).strip()
58
+ text = re.sub(r",\s*([}\]])", r"\1", text)
59
+ first = text.find("{")
60
+ if first == -1:
61
+ return None
62
+ try:
63
+ obj, _ = json.JSONDecoder().raw_decode(text, first)
64
+ return obj
65
+ except Exception:
66
+ return None
67
+
68
+
69
+ @app.get("/health")
70
+ def health():
71
+ return {"status": "ok", "model": args.model}
72
+
73
+
74
+ @app.get("/v1/models")
75
+ def list_models():
76
+ return {
77
+ "object": "list",
78
+ "data": [{"id": "sr4-game", "object": "model"}],
79
+ }
80
+
81
+
82
+ @app.post("/v1/chat/completions")
83
+ async def chat_completions(request: Request):
84
+ gc.collect()
85
+ torch.cuda.empty_cache()
86
+
87
+ body = await request.json()
88
+ messages_raw = body.get("messages", [])
89
+ max_tokens = body.get("max_tokens", 3500)
90
+ temperature = body.get("temperature", 0.0)
91
+
92
+ # Konversi content string JSON → dict (sesuai format training)
93
+ messages = []
94
+ for m in messages_raw:
95
+ content = m["content"]
96
+ if isinstance(content, str):
97
+ try:
98
+ content = json.loads(content)
99
+ except Exception:
100
+ pass
101
+ messages.append({"role": m["role"], "content": content})
102
+
103
+ text = _tok.apply_chat_template(
104
+ messages,
105
+ tokenize =False,
106
+ add_generation_prompt=True,
107
+ enable_thinking =False,
108
+ )
109
+
110
+ inputs = _tok(text, return_tensors="pt", add_special_tokens=False).to(model.device)
111
+ prompt_len = inputs["input_ids"].shape[1]
112
+
113
+ eos_ids = [_tok.eos_token_id]
114
+ im_end_id = _tok.convert_tokens_to_ids("<|im_end|>")
115
+ if im_end_id and im_end_id != _tok.eos_token_id:
116
+ eos_ids.append(im_end_id)
117
+
118
+ with torch.no_grad():
119
+ outputs = model.generate(
120
+ **inputs,
121
+ max_new_tokens =max_tokens,
122
+ do_sample =temperature > 0,
123
+ temperature =temperature if temperature > 0 else None,
124
+ repetition_penalty=1.15,
125
+ pad_token_id =_tok.eos_token_id,
126
+ eos_token_id =eos_ids,
127
+ )
128
+
129
+ new_tokens = outputs[0][prompt_len:]
130
+ raw_text = _tok.decode(new_tokens, skip_special_tokens=True).strip()
131
+ completion_len = len(new_tokens)
132
+
133
+ parsed = _parse_json(raw_text)
134
+ response_text = json.dumps(parsed, ensure_ascii=False) if parsed else raw_text
135
+
136
+ return JSONResponse({
137
+ "id": "chatcmpl-sr4",
138
+ "object": "chat.completion",
139
+ "model": "sr4-game",
140
+ "choices": [{
141
+ "index": 0,
142
+ "message": {"role": "assistant", "content": response_text},
143
+ "finish_reason": "stop",
144
+ }],
145
+ "usage": {
146
+ "prompt_tokens": prompt_len,
147
+ "completion_tokens": completion_len,
148
+ "total_tokens": prompt_len + completion_len,
149
+ },
150
+ })
151
+
152
+
153
+ if __name__ == "__main__":
154
+ print(f"[SR4] Serving on http://0.0.0.0:{args.port}", flush=True)
155
+ uvicorn.run(app, host="0.0.0.0", port=args.port, log_level="warning")