File size: 9,796 Bytes
4720e70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wDmLkBbZmJvB"
      },
      "outputs": [],
      "source": [
        "# ===============================\n",
        "# 1. ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์„ค์น˜ (Google Colab)\n",
        "# ===============================\n",
        "!pip install unsloth xformers faiss-gpu-cu12 -U\n",
        "!pip install --no-deps --upgrade \"flash-attn>=2.6.3\"\n",
        "!pip install -U hf_transfer"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# ===============================\n",
        "# 2. ํ™˜๊ฒฝ ์„ค์ •\n",
        "# ===============================\n",
        "import os\n",
        "import torch\n",
        "import numpy as np\n",
        "import faiss\n",
        "import json\n",
        "import ast\n",
        "from transformers import TextStreamer\n",
        "from sentence_transformers import SentenceTransformer\n",
        "from unsloth import FastLanguageModel\n",
        "from huggingface_hub import hf_hub_download\n",
        "\n",
        "os.environ[\"HF_HUB_ENABLE_HF_TRANSFER\"] = \"1\""
      ],
      "metadata": {
        "id": "OsEBB0aKmhBy"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# ===============================\n",
        "# 3. ๋ชจ๋ธ ๋กœ๋“œ\n",
        "# ===============================\n",
        "model, tokenizer = FastLanguageModel.from_pretrained(\n",
        "    model_name=\"Austin9/gemma-2-9b-it-Ko-RAG\",\n",
        "    max_seq_length=8192,\n",
        "    dtype=torch.float16,\n",
        "    load_in_4bit=True\n",
        ")\n",
        "FastLanguageModel.for_inference(model)"
      ],
      "metadata": {
        "id": "ENT1FgZZmizd"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# ===============================\n",
        "# 4. FAISS ์ธ๋ฑ์Šค ๋กœ๋“œ (Hugging Face Hub์—์„œ ์ง์ ‘ ๋‹ค์šด๋กœ๋“œ)\n",
        "# ===============================\n",
        "repo_id = \"Austin9/gemma-2-9b-it-Ko-RAG\"  # ํ—ˆ๊น…ํŽ˜์ด์Šค ์ €์žฅ์†Œ ID\n",
        "filename = \"chunked_data_vectors.npz\"  # ์ €์žฅ๋œ npz ํŒŒ์ผ ์ด๋ฆ„\n",
        "\n",
        "vector_db_path = hf_hub_download(repo_id=repo_id, filename=filename)\n",
        "data = np.load(vector_db_path)\n",
        "vectors, texts, titles = data[\"vectors\"], data[\"texts\"], data[\"titles\"]\n",
        "\n",
        "gpu_resources = faiss.StandardGpuResources()\n",
        "faiss_index = faiss.GpuIndexFlatL2(gpu_resources, vectors.shape[1])\n",
        "faiss_index.add(vectors)"
      ],
      "metadata": {
        "id": "9H7Xcc9GmkQ8"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# ===============================\n",
        "# 5. ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋“œ\n",
        "# ===============================\n",
        "embedding_model = SentenceTransformer(\"nlpai-lab/KURE-v1\", device=\"cuda\").to(torch.float16)"
      ],
      "metadata": {
        "id": "EwpMV0kXmpSX"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# ===============================\n",
        "# 6. JSON ํŒŒ์‹ฑ ํ•จ์ˆ˜\n",
        "# ===============================\n",
        "def robust_parse_json(response_text):\n",
        "    response_text = response_text.strip().strip(\"'\").strip('\"').replace(\"'\", '\"')\n",
        "    try:\n",
        "        return json.loads(response_text)\n",
        "    except:\n",
        "        try:\n",
        "            return ast.literal_eval(response_text)\n",
        "        except:\n",
        "            return {\"search\": \"\"}\n",
        "\n",
        "# ===============================\n",
        "# 7. ๊ฒ€์ƒ‰ ์ฟผ๋ฆฌ ์ƒ์„ฑ (QCR ๋‹จ๊ณ„)\n",
        "# ===============================\n",
        "def generate_search_query(conversation_history, user_input):\n",
        "    instruction = (\n",
        "        \"๋‹ค์Œ์€ ๋Œ€ํ™” ๊ธฐ๋ก(Context)์™€ ์‚ฌ์šฉ์ž์˜ ์งˆ๋ฌธ(Input)์ž…๋‹ˆ๋‹ค. \"\n",
        "        \"์‚ฌ์šฉ์ž์˜ ์งˆ๋ฌธ์— ๋‹ต์„ ์ œ๊ณตํ•˜๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ๋‹จ์ผ ๋ฌธ์ž์—ด ๊ฒ€์ƒ‰ ์ฟผ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•˜์„ธ์š”. \"\n",
        "        \"๊ฒ€์ƒ‰์ด ํ•„์š”ํ•˜์ง€ ์•Š๊ฑฐ๋‚˜ ๊ฒ€์ƒ‰์ด ๋ถˆํ•„์š”ํ•œ ๊ฒฝ์šฐ(์ธ์‚ฌ๋‚˜, ๊ฒ‰์น˜๋ ˆ, ๋†๋‹ด) ๋นˆ ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜ํ•˜์„ธ์š”.\\n\\n\"\n",
        "        \"์ตœ์ข… ์ถœ๋ ฅ ํ˜•์‹์€ {'search': '<๊ฒ€์ƒ‰ ์ฟผ๋ฆฌ>'}์ž…๋‹ˆ๋‹ค.\"\n",
        "    )\n",
        "    prompt = f\"\"\"\n",
        "    # Query Rewriter\n",
        "    ### Instruction:\n",
        "    {instruction}\n",
        "    ### Conversation:\n",
        "    {'\\n'.join([f'{role}: {msg}' for role, msg in conversation_history])}\n",
        "    ### Input:\n",
        "    {user_input}\n",
        "    ### Response:\n",
        "    \"\"\"\n",
        "\n",
        "    inputs = tokenizer([prompt], return_tensors=\"pt\").to(\"cuda\")\n",
        "    output_tokens = model.generate(**inputs, max_new_tokens=300)\n",
        "    response_text = tokenizer.decode(output_tokens[0], skip_special_tokens=True).split(\"### Response:\")[-1].strip()\n",
        "    return robust_parse_json(response_text).get(\"search\", \"\")\n",
        "\n",
        "# ===============================\n",
        "# 8. FAISS ๊ฒ€์ƒ‰\n",
        "# ===============================\n",
        "def search_documents(query, k=3):\n",
        "    if not query:\n",
        "        return \"\"\n",
        "    query_vector = embedding_model.encode([query])[0]\n",
        "    _, indices = faiss_index.search(np.array([query_vector]), k)\n",
        "    return \"\\n\\n\".join([f\"# Index [{i+1}]: {titles[idx]}\\n{texts[idx]}\" for i, idx in enumerate(indices[0])])\n",
        "\n",
        "# ===============================\n",
        "# 9. ๋‹ต๋ณ€ ์ƒ์„ฑ\n",
        "# ===============================\n",
        "def generate_response(conversation_history, context, user_input):\n",
        "    instruction = (\n",
        "        \"๋‹น์‹ ์€ ์™ธ๋ถ€๊ฒ€์ƒ‰์„ ์ด์šฉํ•˜์—ฌ ์‚ฌ์šฉ์ž์—๊ฒŒ ๋„์›€์„ ์ฃผ๋Š” ์ธ๊ณต์ง€๋Šฅ ์กฐ์ˆ˜์ž…๋‹ˆ๋‹ค.\\n\"\n",
        "        \"- Context๋Š” ์™ธ๋ถ€๊ฒ€์ƒ‰์„ ํ†ตํ•ด ๋ฐ˜ํ™˜๋œ ์‚ฌ์šฉ์ž ์š”์ฒญ๊ณผ ๊ด€๋ จ๋œ ์ •๋ณด๋“ค์ž…๋‹ˆ๋‹ค.\\n\"\n",
        "        \"- Context๋ฅผ ํ™œ์šฉํ•  ๋•Œ ๋ฌธ์žฅ ๋์— ์‚ฌ์šฉํ•œ ๋ฌธ์„œ ์กฐ๊ฐ์˜ [Index]๋ฅผ ๋ถ™์ด๊ณ  ์ž์—ฐ์Šค๋Ÿฌ์šด ๋‹ต๋ณ€์„ ์ž‘์„ฑํ•˜์„ธ์š”. (e.g. [1])\\n\"\n",
        "        \"- Context์˜ ์ •๋ณด๊ฐ€ ์‚ฌ์šฉ์ž ์š”์ฒญ๊ณผ ๊ด€๋ จ์ด ์—†๊ฑฐ๋‚˜ ๋„์›€์ด ์•ˆ๋ ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. ๊ด€๋ จ์žˆ๋Š” ์ •๋ณด๋งŒ ํ™œ์šฉํ•˜๊ณ , ์—†๋Š” ์ •๋ณด๋ฅผ ์ ˆ๋Œ€ ์ง€์–ด๋‚ด์ง€ ๋งˆ์„ธ์š”.\\n\"\n",
        "        \"- ๋˜๋„๋ก์ด๋ฉด ์ผ๋ฐ˜ ์ง€์‹์œผ๋กœ ๋‹ต๋ณ€ํ•˜์ง€๋ง๊ณ , ์ตœ๋Œ€ํ•œ Context๋ฅผ ํ†ตํ•ด์„œ ๋‹ต๋ณ€์„ ํ•˜๋ ค๊ณ  ํ•˜์„ธ์š”. Context์— ์—†์„ ๊ฒฝ์šฐ์—๋Š” ์ด ์ ์„ ์–ธ๊ธ‰ํ•˜๋ฉฐ ์‚ฌ์ฃ„ํ•˜๊ณ  ๋‹ค๋ฅธ ์ฃผ์ œ๋‚˜ ์งˆ๋ฌธ์„ ์ถ”์ฒœํ•ด์ฃผ์„ธ์š”.\\n\"\n",
        "        \"- ์‚ฌ์šฉ์ž ์š”์ฒญ์— ์•Œ๋งž๋Š” ์ž์—ฐ์Šค๋Ÿฌ์šด ๋Œ€ํ™”๋ฅผ ํ•˜์„ธ์š”.\\n\"\n",
        "        \"- ํ•ญ์ƒ ์กด๋Œ“๋ง๋กœ ๋‹ต๋ณ€ํ•˜์„ธ์š”.\"\n",
        "    )\n",
        "\n",
        "    prompt = f\"\"\"\n",
        "    # Generator\n",
        "    ### Instruction:\n",
        "    {instruction}\n",
        "    ### Conversation:\n",
        "    {'\\n'.join([f'{role}: {msg}' for role, msg in conversation_history])}\n",
        "    ### Context:\n",
        "    {context}\n",
        "    ### Input:\n",
        "    {user_input}\n",
        "    ### Response:\n",
        "    \"\"\"\n",
        "\n",
        "    inputs = tokenizer([prompt], return_tensors=\"pt\").to(\"cuda\")\n",
        "    output_tokens = model.generate(**inputs, max_new_tokens=2500, do_sample=True)\n",
        "    return tokenizer.decode(output_tokens[0], skip_special_tokens=True).split(\"### Response:\")[-1].strip()"
      ],
      "metadata": {
        "id": "Nsv2Xp2kmp1S"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# ===============================\n",
        "# 10. ๋Œ€ํ™” ๋ฃจํ”„\n",
        "# ===============================\n",
        "def chat_loop():\n",
        "    conversation_history = []\n",
        "    print(\"๋Œ€ํ™”๋ฅผ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค. 'exit' ์ž…๋ ฅ ์‹œ ์ข…๋ฃŒ.\")\n",
        "\n",
        "    while True:\n",
        "        user_input = input(\"\\nUser> \").strip()\n",
        "        if user_input.lower() in [\"exit\", \"quit\"]:\n",
        "            print(\"๋Œ€ํ™”๋ฅผ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.\")\n",
        "            break\n",
        "\n",
        "        print(\"\\n[๊ฒ€์ƒ‰ ์ฟผ๋ฆฌ ์ƒ์„ฑ ์ค‘...]\")\n",
        "        search_query = generate_search_query(conversation_history, user_input)\n",
        "        context = search_documents(search_query, k=5) if search_query else \"\"\n",
        "\n",
        "        print(\"\\n[๋‹ต๋ณ€ ์ƒ์„ฑ ์ค‘...]\")\n",
        "        response = generate_response(conversation_history, context, user_input)\n",
        "\n",
        "        conversation_history.append((\"User\", user_input))\n",
        "        conversation_history.append((\"Assistant\", response))\n",
        "        print(f\"\\nAssistant> {response}\")\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    chat_loop()"
      ],
      "metadata": {
        "id": "4XD0UDZImsuE"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}