Instructions to use sjmoon21/SJ-ko with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use sjmoon21/SJ-ko with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf sjmoon21/SJ-ko # Run inference directly in the terminal: llama cli -hf sjmoon21/SJ-ko
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf sjmoon21/SJ-ko # Run inference directly in the terminal: llama cli -hf sjmoon21/SJ-ko
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf sjmoon21/SJ-ko # Run inference directly in the terminal: ./build/bin/llama cli -hf sjmoon21/SJ-ko
Use Docker
docker model run hf.co/sjmoon21/SJ-ko
- Llama new
- LM Studio
- Jan
- vLLM
How to use sjmoon21/SJ-ko with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "sjmoon21/SJ-ko" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "sjmoon21/SJ-ko", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/sjmoon21/SJ-ko
- Ollama
How to use sjmoon21/SJ-ko with Ollama:
ollama run hf.co/sjmoon21/SJ-ko
- Unsloth Desktop
- Docker Model Runner
How to use sjmoon21/SJ-ko with Docker Model Runner:
docker model run hf.co/sjmoon21/SJ-ko
- Lemonade
How to use sjmoon21/SJ-ko with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull sjmoon21/SJ-ko
Run and chat with the model
lemonade run user.SJ-ko-{{QUANT_TAG}}List all available models
lemonade list
- Atomic Chat
채팅 UI + 다중 턴 템플릿
Browse filesFiles changed (2)
- Modelfile+7-1
- serve_ollama.py+249-94
1223456789101112FROM ./sj-0.5.1si.ggufTEMPLATE """<|user|>{{ .Prompt }}<|assistant|>"""
# 다중 턴: .Messages를 순회해 <|user|>q<|assistant|>a<|endoftext|> 로 이어붙인다.# raw:true 로 직접 조립하면 특수 토큰이 문자열로 취급되므로 반드시 템플릿을 써야 한다.TEMPLATE """{{- range .Messages }}{{- if eq .Role "user" }}<|user|>{{ .Content }}<|assistant|>{{- else }}{{ .Content }}<|endoftext|>{{- end }}{{- end }}"""
# 이게 없으면 답변이 끝나도 멈추지 않는다.PARAMETER stop "<|endoftext|>"
PARAMETER temperature 0.7PARAMETER top_k 50PARAMETER repeat_penalty 1.211233456678910111213141516171819202122232425122627142829303119203233342 unmodified lines373839404142438 unmodified lines52535443445556575859606162634647484950515253545556575859606164656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011163646566676869112113114115116117118119120121122123124125126127128129130131132133134135136137138139727374757677787980818283140141142143144145146147148149150151152153858687154155156157158159160161162163164909192939495969798991651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082091051061071082102112122132141102152162172182191151162202212222232242252262272282292302312321182332342352362372382391251262402412422432442452462472481291302492502512521331341352532542551381391401411421431441451461471481491501512562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083097 unmodified lines317318319165166320321322323324170171172173174325326327328329330176331332333334"""웹 데모 (Ollama 백엔드) — 서버 배포용"""웹 채팅 UI (Ollama 백엔드) — 서버 배포용
python3 src/serve_ollama.py --model sj-0.5.1si --host 0.0.0.0 --port 3000 python3 serve_ollama.py --model sj-0.5.1si --host 0.0.0.0 --port 3000
의존성이 **표준 라이브러리뿐**이다. PyTorch도 numpy도 필요 없다.서버에는 Ollama만 있으면 되고, 모델은 GGUF 50MB 하나로 끝난다.서버에는 Ollama와 GGUF 하나만 있으면 된다.(src/serve.py는 PyTorch로 직접 추론한다 — 로컬 개발용)
────────────────────────────────────────────────────────────────다중 턴 — 왜 /api/chat 인가────────────────────────────────────────────────────────────────run15에서 다중 턴을 훈련했으므로 대화 이력을 넘길 수 있다. 그러려면`<|user|>q1<|assistant|>a1<|endoftext|><|user|>q2<|assistant|>` 형태가 필요한데:
raw:true 로 직접 조립 -> **안 된다.** 특수 토큰이 문자열로 취급된다 (실측: 컨텍스트에 5206/5207이 없고 27토큰으로 쪼개짐) /api/chat + 템플릿 -> 된다. Modelfile이 .Messages를 순회하게 해야 한다
Modelfile TEMPLATE: {{- range .Messages }}{{- if eq .Role "user" }}<|user|>{{ .Content }}<|assistant|> {{- else }}{{ .Content }}<|endoftext|>{{- end }}{{- end }}
────────────────────────────────────────────────────────────────공개 배포 시 반드시 지킬 것────────────────────────────────────────────────────────────────이 앱은 읽기 전용이다. GET / 과 POST /generate 뿐이고 모델을 바꾸는 길이 없다.이 앱은 읽기 전용이다. GET / 과 POST /chat 뿐이고 모델을 바꾸는 길이 없다.그러나 **Ollama API(11434)에는 인증이 없고 모델 삭제·교체가 가능하다.**반드시 localhost에만 묶어둘 것:
OLLAMA_HOST=127.0.0.1:11434 ollama serve
방화벽에서 11434를 외부에 열면 누구나 모델을 지울 수 있다.
간단한 IP별 속도 제한을 둔다. 인증은 없다 — 공개 데모 전제."""import argparseimport json2 unmodified linesimport urllib.requestfrom collections import defaultdict, dequefrom http.server import BaseHTTPRequestHandler, HTTPServer
try: # ThreadingHTTPServer는 Python 3.7+ from http.server import ThreadingHTTPServer as Serverexcept ImportError: # 3.6 (Rocky/RHEL 8 기본) — 직접 조립8 unmodified linesPAGE = """<!doctype html><meta charset="utf-8"><title>{name}</title><meta name=viewport content="width=device-width,initial-scale=1"><style>:root{{--bg:#0f1115;--fg:#e6e6e6;--dim:#8b93a7;--card:#171a21;--line:#2a2f3a;--acc:#6ea8fe}}@media(prefers-color-scheme:light){{:root{{--bg:#fafafa;--fg:#1a1a1a;--dim:#666;--card:#fff;--line:#ddd}}}}:root{{ --bg:#ffffff; --fg:#0d0d0d; --dim:#8f8f8f; --line:#e5e5e5; --bubble:#f4f4f4; --accent:#0d0d0d; --accent-fg:#ffffff; --field:#f4f4f4;}}@media(prefers-color-scheme:dark){{:root{{ --bg:#212121; --fg:#ececec; --dim:#9b9b9b; --line:#3a3a3a; --bubble:#303030; --accent:#ffffff; --accent-fg:#0d0d0d; --field:#303030;}}}}*{{box-sizing:border-box}}body{{margin:0;background:var(--bg);color:var(--fg); font:15px/1.7 -apple-system,BlinkMacSystemFont,"Apple SD Gothic Neo",sans-serif}}.wrap{{max-width:760px;margin:0 auto;padding:28px 20px 80px}}h1{{font-size:20px;margin:0 0 4px}}.sub{{color:var(--dim);font-size:12px;margin-bottom:20px}}textarea{{width:100%;height:78px;padding:12px;border-radius:9px;background:var(--card); color:var(--fg);border:1px solid var(--line);font:inherit;resize:vertical}}button{{padding:10px 20px;border:0;border-radius:8px;background:var(--acc);color:#08121f; font-weight:600;cursor:pointer;font-size:14px}}button:disabled{{opacity:.45;cursor:default}}.row{{display:flex;gap:10px;align-items:center;margin:12px 0;flex-wrap:wrap}}.out{{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:16px; min-height:90px;white-space:pre-wrap;word-break:break-word;margin:14px 0}}.stat{{color:var(--dim);font-size:12px}}.note{{background:var(--card);border-left:3px solid var(--acc);padding:10px 14px; border-radius:0 7px 7px 0;font-size:12px;color:var(--dim);margin-top:24px}}html,body{{height:100%}}body{{margin:0;background:var(--bg);color:var(--fg);display:flex;flex-direction:column; font:16px/1.65 -apple-system,BlinkMacSystemFont,"Apple SD Gothic Neo","Segoe UI",sans-serif}}
header{{border-bottom:1px solid var(--line);padding:11px 16px;display:flex; align-items:center;gap:10px;flex:0 0 auto}}header b{{font-size:15px;font-weight:600}}header .tag{{font-size:11px;color:var(--dim);border:1px solid var(--line); border-radius:20px;padding:2px 9px}}header button{{margin-left:auto;background:none;border:1px solid var(--line); color:var(--dim);border-radius:8px;padding:5px 11px;font-size:13px;cursor:pointer}}header button:hover{{color:var(--fg)}}
main{{flex:1 1 auto;overflow-y:auto}}.thread{{max-width:760px;margin:0 auto;padding:26px 16px 8px}}
.intro{{text-align:center;color:var(--dim);padding:56px 12px}}.intro h2{{color:var(--fg);font-size:23px;margin:0 0 10px;font-weight:600}}.intro p{{margin:0 auto;max-width:440px;font-size:14px}}.chips{{display:flex;gap:8px;flex-wrap:wrap;justify-content:center;margin-top:22px}}.chip{{border:1px solid var(--line);border-radius:11px;padding:9px 13px;font-size:13px; cursor:pointer;color:var(--fg);background:none}}.chip:hover{{background:var(--bubble)}}
.msg{{display:flex;margin:18px 0}}.msg.u{{justify-content:flex-end}}.msg .body{{white-space:pre-wrap;word-break:break-word}}.msg.u .body{{background:var(--bubble);border-radius:18px;padding:10px 16px;max-width:78%}}.msg.a .body{{max-width:100%}}.msg.a .who{{font-size:12px;color:var(--dim);margin-bottom:5px}}.err{{color:#d33}}
.dots span{{display:inline-block;width:6px;height:6px;margin-right:4px;border-radius:50%; background:var(--dim);animation:b 1.2s infinite}}.dots span:nth-child(2){{animation-delay:.2s}}.dots span:nth-child(3){{animation-delay:.4s}}@keyframes b{{0%,60%,100%{{opacity:.25}}30%{{opacity:1}}}}
footer{{flex:0 0 auto;padding:10px 16px 16px;background:var(--bg)}}.box{{max-width:760px;margin:0 auto;display:flex;align-items:flex-end;gap:8px; background:var(--field);border:1px solid var(--line);border-radius:24px;padding:8px 8px 8px 16px}}textarea{{flex:1;border:0;background:none;color:var(--fg);font:inherit;resize:none; outline:none;max-height:190px;padding:6px 0}}#send{{flex:0 0 auto;width:34px;height:34px;border:0;border-radius:50%; background:var(--accent);color:var(--accent-fg);cursor:pointer;font-size:17px;line-height:1}}#send:disabled{{opacity:.3;cursor:default}}.foot{{max-width:760px;margin:8px auto 0;text-align:center;font-size:11px;color:var(--dim)}}</style><div class=wrap><h1>{name}</h1><div class=sub>{info}</div><textarea id=q placeholder="질문을 입력하세요 (Cmd/Ctrl+Enter로 전송)"></textarea><div class=row><button id=go>보내기</button><span class=stat id=meta></span></div><div class=out id=out></div><div class=note>{note}</div></div>
<header> <b>{name}</b><span class=tag>{param}</span> <button id=reset>새 대화</button></header>
<main id=main><div class=thread id=thread> <div class=intro id=intro> <h2>{name}</h2> <p>{info}</p> <div class=chips> <button class=chip>너 누구야?</button> <button class=chip>27 + 145는 얼마야?</button> <button class=chip>블랙홀이 무엇인가요?</button> </div> </div></div></main>
<footer> <div class=box> <textarea id=q rows=1 placeholder="무엇이든 물어보세요"></textarea> <button id=send>↑</button> </div> <div class=foot>{note}</div></footer>
<script>const $=i=>document.getElementById(i);async function run(){{ const q=$('q').value.trim(); if(!q) return; $('go').disabled=true; $('out').textContent='...'; $('meta').textContent=''; const t0=performance.now(); try{{ const r=await fetch('/generate',{{method:'POST', headers:{{'Content-Type':'application/json'}},body:JSON.stringify({{prompt:q}})}}); const d=await r.json(); $('out').textContent = d.text || ('오류: '+d.error); if(d.text) $('meta').textContent=((performance.now()-t0)/1000).toFixed(1)+'초'; }}catch(e){{ $('out').textContent='요청 실패: '+e; }} $('go').disabled=false;const thread=$('thread'), main=$('main'), q=$('q');let history=[], busy=false;
function bubble(role, text){{ const d=document.createElement('div'); d.className='msg '+(role==='user'?'u':'a'); d.innerHTML = role==='user' ? '<div class=body></div>' : '<div class=body><div class=who>{name}</div><span class=t></span></div>'; (role==='user'? d.querySelector('.body') : d.querySelector('.t')).textContent=text; thread.appendChild(d); main.scrollTop=main.scrollHeight; return d;}}$('go').onclick=run;$('q').addEventListener('keydown',e=>{{if((e.metaKey||e.ctrlKey)&&e.key==='Enter')run();}});</script>"""function grow(){{ q.style.height='auto'; q.style.height=Math.min(q.scrollHeight,190)+'px'; }}
async function send(){{ const text=q.value.trim(); if(!text || busy) return; const intro=$('intro'); if(intro) intro.remove(); busy=true; $('send').disabled=true; q.value=''; grow(); bubble('user', text); history.push({{role:'user', content:text}});
def ollama(prompt, n): body = json.dumps({ "model": S['model'], "prompt": prompt, "stream": False, "options": {"num_predict": n, "temperature": 0.7, "top_k": 50, "repeat_penalty": 1.2}, }).encode() req = urllib.request.Request(S['ollama'] + "/api/generate", body, {"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=120) as r: return json.loads(r.read()).get('response', '') const holder=bubble('assistant',''); const slot=holder.querySelector('.t'); slot.innerHTML='<span class=dots><span></span><span></span><span></span></span>';
try{{ const r=await fetch('/chat',{{method:'POST', headers:{{'Content-Type':'application/json'}}, body:JSON.stringify({{messages:history}})}}); if(!r.ok){{ const e=await r.json().catch(()=>({{error:'요청 실패'}})); slot.className='t err'; slot.textContent=e.error||'오류'; history.pop(); }} else {{ const reader=r.body.getReader(), dec=new TextDecoder(); let acc=''; slot.textContent=''; while(true){{ const {{done,value}}=await reader.read(); if(done) break; acc+=dec.decode(value,{{stream:true}}); slot.textContent=acc; main.scrollTop=main.scrollHeight; }} history.push({{role:'assistant', content:acc}}); if(history.length>8) history=history.slice(-8); // 문맥 1024토큰 한계 }} }}catch(e){{ slot.className='t err'; slot.textContent='연결 실패: '+e; history.pop(); }} busy=false; $('send').disabled=false; q.focus();}}
$('send').onclick=send;q.addEventListener('input',grow);q.addEventListener('keydown',e=>{{ if(e.key==='Enter' && !e.shiftKey && !e.isComposing){{ e.preventDefault(); send(); }}}});$('reset').onclick=()=>{{ history=[]; thread.innerHTML=''; location.reload(); }};document.addEventListener('click',e=>{{ if(e.target.classList.contains('chip')){{ q.value=e.target.textContent; grow(); send(); }}}});q.focus();</script>"""
def allowed(ip): """IP별 속도 제한. 공개 데모라 인증은 없고, 자원 남용만 막는다.""" now = time.time() q = HITS[ip] while q and now - q[0] > 60: q.popleft() if len(q) >= S['rpm']: d = HITS[ip] while d and now - d[0] > 60: d.popleft() if len(d) >= S['rpm']: return False q.append(now) d.append(now) return True
class H(BaseHTTPRequestHandler): def _send(self, code, body, ctype='application/json; charset=utf-8'): b = body.encode() protocol_version = 'HTTP/1.1'
def handle_one_request(self): # keep-alive 연결에서 사용자가 창을 닫으면 http.server가 다음 요청을 # 읽다가 예외를 던진다. 공개 서버에서는 흔한 일이라 로그만 더럽힌다. try: BaseHTTPRequestHandler.handle_one_request(self) except (ConnectionResetError, BrokenPipeError, TimeoutError): self.close_connection = True
def _json(self, code, obj): b = json.dumps(obj, ensure_ascii=False).encode() self.send_response(code) self.send_header('Content-Type', ctype) self.send_header('Content-Type', 'application/json; charset=utf-8') self.send_header('Content-Length', str(len(b))) self.end_headers() self.wfile.write(b)
def do_GET(self): if self.path.split('?')[0] != '/': return self._send(404, '{"error":"not found"}') self._send(200, PAGE.format(**S['page']), 'text/html; charset=utf-8') return self._json(404, {"error": "not found"}) b = PAGE.format(**S['page']).encode() self.send_response(200) self.send_header('Content-Type', 'text/html; charset=utf-8') self.send_header('Content-Length', str(len(b))) self.end_headers() self.wfile.write(b)
def do_POST(self): if self.path != '/generate': return self._send(404, '{"error":"not found"}') if self.path != '/chat': return self._json(404, {"error": "not found"}) ip = self.headers.get('X-Forwarded-For', self.client_address[0]).split(',')[0].strip() if not allowed(ip): return self._send(429, json.dumps( {"error": "요청이 너무 잦습니다. 잠시 후 다시 시도해 주세요."}, ensure_ascii=False)) return self._json(429, {"error": "요청이 너무 잦습니다. 잠시 후 다시 시도해 주세요."}) try: n = int(self.headers.get('Content-Length', 0)) req = json.loads(self.rfile.read(min(n, 4096)) or b'{}') p = str(req.get('prompt', ''))[:500] # 입력 길이 제한 if not p.strip(): return self._send(400, '{"error":"빈 입력"}') t0 = time.time() text = ollama(p, S['npred']) print("[{:.1f}s] {} {!r} -> {}자".format( time.time() - t0, ip, p[:30], len(text)), flush=True) self._send(200, json.dumps({"text": text}, ensure_ascii=False)) except urllib.error.URLError as e: self._send(503, json.dumps({"error": "모델 서버에 연결할 수 없습니다"}, ensure_ascii=False)) except Exception as e: self._send(500, json.dumps({"error": str(e)[:120]}, ensure_ascii=False)) req = json.loads(self.rfile.read(min(n, 16384)) or b'{}') msgs = req.get('messages') or [] # 형식·길이 제한. 서버는 상태를 갖지 않는다 — 이력은 클라이언트가 보낸다. msgs = [{"role": m.get('role'), "content": str(m.get('content', ''))[:500]} for m in msgs[-8:] if m.get('role') in ('user', 'assistant') and m.get('content')] if not msgs or msgs[-1]['role'] != 'user': return self._json(400, {"error": "빈 입력"}) except Exception: return self._json(400, {"error": "잘못된 요청"})
body = json.dumps({"model": S['model'], "messages": msgs, "stream": True, "options": {"num_predict": S['npred'], "temperature": 0.7, "top_k": 50, "repeat_penalty": 1.2}}).encode() rq = urllib.request.Request(S['ollama'] + "/api/chat", body, {"Content-Type": "application/json"}) t0 = time.time() got = 0 try: up = urllib.request.urlopen(rq, timeout=180) except urllib.error.URLError: return self._json(503, {"error": "모델 서버에 연결할 수 없습니다"})
self.send_response(200) self.send_header('Content-Type', 'text/plain; charset=utf-8') self.send_header('Transfer-Encoding', 'chunked') self.end_headers() try: for line in up: # Ollama는 NDJSON으로 흘려보낸다 line = line.strip() if not line: continue try: d = json.loads(line) except ValueError: continue piece = (d.get('message') or {}).get('content', '') if piece: chunk = piece.encode() self.wfile.write(b"%x\r\n" % len(chunk) + chunk + b"\r\n") self.wfile.flush() got += len(piece) if d.get('done'): break self.wfile.write(b"0\r\n\r\n") except (BrokenPipeError, ConnectionResetError): pass # 사용자가 창을 닫은 경우 finally: up.close() print("[{:.1f}s] {} {!r} -> {}자".format( time.time() - t0, ip, msgs[-1]['content'][:30], got), flush=True)
def log_message(self, *a): pass7 unmodified lines help='공개하려면 0.0.0.0. Ollama는 localhost에 두어야 한다') ap.add_argument('--port', type=int, default=3000) ap.add_argument('--ollama', default='http://127.0.0.1:11434') ap.add_argument('--npred', type=int, default=180) ap.add_argument('--rpm', type=int, default=20, help='IP당 분당 요청 수') ap.add_argument('--npred', type=int, default=200) ap.add_argument('--rpm', type=int, default=30, help='IP당 분당 요청 수') a = ap.parse_args()
S.update(model=a.model, ollama=a.ollama, npred=a.npred, rpm=a.rpm, page=dict(name=a.name, info="11M 파라미터 한국어 GPT · 밑바닥부터 직접 구현", note="학습 목적으로 만든 11M 모델입니다. 사실 관계는 신뢰할 수 " "없고 같은 구절을 반복하기도 합니다. " "huggingface.co/sjmoon21/SJ-ko")) page=dict(name=a.name, param="11M", info="밑바닥부터 직접 만든 11M 파라미터 한국어 언어모델입니다. " "무엇이든 물어보세요.", note="학습 목적으로 만든 작은 모델입니다. 사실 관계는 신뢰할 수 " "없습니다 · huggingface.co/sjmoon21/SJ-ko")) print("{} · ollama={} · http://{}:{}".format(a.model, a.ollama, a.host, a.port)) print("IP당 분당 {}회 제한 · 입력 500자 · 생성 {}토큰".format(a.rpm, a.npred)) print("IP당 분당 {}회 · 입력 500자 · 이력 8턴 · 생성 {}토큰".format(a.rpm, a.npred)) Server((a.host, a.port), H).serve_forever()
Modelfile+7-1
serve_ollama.py+249-94