{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# KJH-Judge-4B-ko 빠른 테스트\n", "\n", "허깅페이스에 올린 모델을 내려받아 판정해 봅니다.\n", "\n", "- **GPU 런타임**에서 실행하세요 (Colab: 런타임 → 런타임 유형 변경 → T4 GPU). CPU에서는 판정 한 번에 수십 초 이상 걸리고 메모리도 16GB 넘게 필요합니다.\n", "- 모델 내려받기에 몇 분 걸립니다 (약 8GB).\n", "- 결과는 모두 `{'choice': 고른 보기, 'confidence': 그 확률, 'probabilities': 보기별 확률}` 모양입니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%pip install -q -U \"transformers>=5\" accelerate\n", "# Colab에서 transformers 가 이미 4.x 로 깔려 있었다면, 설치 후 '런타임 → 세션 다시 시작'을 한 번 하고 아래 셀부터 실행하세요." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "저장소가 **비공개**라면 아래 셀의 주석을 풀고 토큰으로 로그인하세요 (Colab은 왼쪽 열쇠 아이콘의 보안 비밀에 `HF_TOKEN`을 넣어 두면 자동으로 씁니다)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# from huggingface_hub import login\n", "# login()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch\n", "from transformers import pipeline\n", "\n", "gpu = torch.cuda.is_available()\n", "print(\"GPU:\", torch.cuda.get_device_name(0) if gpu else \"없음 (CPU, 매우 느림)\")\n", "\n", "judge = pipeline(model=\"coderecode95/KJH-Judge-4B-ko\", trust_remote_code=True,\n", " device=0 if gpu else -1, dtype=\"bfloat16\" if gpu else \"float32\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. 자주 쓰는 판정 — 메서드 하나로\n", "\n", "학습 때와 같은 지침·보기가 자동으로 들어갑니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "judge.sentiment(\"배송은 느렸지만 물건은 정말 마음에 들어요\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(judge.nli(\"흡연자분들은 발코니가 있는 방이면 발코니에서 흡연이 가능합니다.\", \"어떤 방에서도 흡연은 금지됩니다.\"))\n", "print(judge.topic(\"손흥민, 시즌 10호골…토트넘 3연승 이끌어\"))\n", "print(judge.hate(\"연기 진짜 많이 늘었다 다음 작품도 기대됨\"))\n", "print(judge.yes_no(\"콜라독립 815는 코카콜라에서 만들었나요?\",\n", " \"콜라독립 815는 코카콜라를 라이선스로 만들어 오던 범양식품이 1998년에 출시한 탄산음료다.\"))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 에이전트의 다음 행동: 필수 정보가 빠졌으면 ASK, 다 있으면 CALL, 도구가 필요 없으면 RESPOND\n", "tools = [\n", " {\"type\": \"function\", \"function\": {\"name\": \"call_taxi\", \"description\": \"택시를 호출한다\",\n", " \"parameters\": {\"type\": \"object\", \"properties\": {\"pickup\": {\"type\": \"string\"}, \"destination\": {\"type\": \"string\"}}, \"required\": [\"pickup\", \"destination\"]}}},\n", " {\"type\": \"function\", \"function\": {\"name\": \"get_weather\", \"description\": \"지역의 현재 날씨를 알려준다\",\n", " \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\"}}, \"required\": [\"city\"]}}},\n", "]\n", "for msg in [\"택시 좀 불러줘\", \"강남역에서 서울역까지 택시 불러줘\", \"부산 날씨 어때?\", \"고마워!\"]:\n", " r = judge.next_action(msg, tools)\n", " print(f\"{r['choice']:<18} {r['confidence']:.1%} ← {msg}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 리스트를 넣으면 여러 개를 한 번에\n", "headlines = [\"손흥민, 시즌 10호골…토트넘 3연승 이끌어\", \"코스피 2,700 돌파…외국인 순매수\", \"새 스마트폰 공개, AI 기능 강화\", \"국회 본회의서 예산안 통과\"]\n", "for h, r in zip(headlines, judge.topic(headlines)):\n", " print(f\"{r['choice']:<5} {r['confidence']:.1%} {h}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. 내 판정 만들기 — JEV 형식\n", "\n", "상황(`state`) 하나에 이름 붙인 질문 여러 개를 한 번에 묻습니다. `criteria`의 키(ID)가 결과로 돌아옵니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "judge.decide(\n", " state={\"고객 문의\": \"지난달 요금이 두 번 빠져나갔어요. 오늘 안에 처리해 주세요.\"},\n", " questions={\n", " \"부서\": {\n", " \"instructions\": \"고객 문의를 담당 부서로 분류한다.\",\n", " \"criteria\": {\"billing\": \"결제·환불\", \"delivery\": \"배송\", \"account\": \"계정·로그인\", \"other\": \"기타\"},\n", " },\n", " \"긴급\": {\n", " \"instructions\": \"고객이 즉시 처리를 요구하는지 판단한다.\",\n", " \"criteria\": {\"urgent\": \"즉시 처리 요구\", \"normal\": \"일반 문의\"},\n", " },\n", " },\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. 확신이 낮으면 사람에게 넘기기\n", "\n", "기준값(여기서는 0.7)은 실제로 쓸 데이터에서 다시 맞추는 것이 좋습니다. 학습하지 않은 데이터에서는 확신이 정확도보다 조금 높게 나옵니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "reviews = [\"배송 참 빠르네요. 2주 걸렸어요\", \"가격 대비 괜찮아요\", \"다시는 안 삽니다\", \"그냥 그래요\"]\n", "for t, r in zip(reviews, judge.sentiment(reviews)):\n", " print(f\"{r['choice']} {r['confidence']:.1%} {'자동 처리' if r['confidence'] >= 0.7 else '→ 사람 검토':<8} {t}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. 한 줄로 직접 해 보기" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "judge(\"이 앱 로그인이 계속 안 돼요. 비밀번호를 바꿔도 똑같아요.\",\n", " choices=[\"결제·환불\", \"배송\", \"계정·로그인\", \"제품 문의\", \"기타\"],\n", " instruction=\"고객 문의를 담당 부서로 분류한다.\")" ] } ], "metadata": { "accelerator": "GPU", "colab": { "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 0 }