{ "cells": [ { "cell_type": "code", "execution_count": 21, "id": "7018890b-b220-48a3-a1b8-d8f6c5483f6c", "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [] }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n", "To disable this warning, you can either:\n", "\t- Avoid using `tokenizers` before the fork if possible\n", "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Cloning into 'gpt-neo-125M'...\n", "remote: Enumerating objects: 65, done.\u001b[K\n", "remote: Counting objects: 100% (5/5), done.\u001b[K\n", "remote: Compressing objects: 100% (5/5), done.\u001b[K\n", "remote: Total 65 (delta 1), reused 0 (delta 0), pack-reused 60 (from 1)\u001b[K\n", "Unpacking objects: 100% (65/65), 1.11 MiB | 9.13 MiB/s, done.\n", "Filtering content: 100% (4/4), 1.93 GiB | 54.88 MiB/s, done.\n" ] } ], "source": [ "!git clone https://huggingface.co/EleutherAI/gpt-neo-125M" ] }, { "cell_type": "code", "execution_count": 1, "id": "36078c20-4185-4f45-84f2-d3e95e1dcac9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/nvfuser-0.2.13a0+0d33366-py3.12-linux-x86_64.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/dill-0.3.9-py3.12.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/lightning_utilities-0.11.8-py3.12.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/opt_einsum-3.4.0-py3.12.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/igraph-0.11.8-py3.12-linux-x86_64.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/lightning_thunder-0.2.0.dev0-py3.12.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/texttable-1.7.0-py3.12.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/looseversion-1.3.0-py3.12.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\n", "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.3.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.1.1\u001b[0m\n", "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython -m pip install --upgrade pip\u001b[0m\n" ] } ], "source": [ "!pip install accelerate>=0.26.0" ] }, { "cell_type": "code", "execution_count": 6, "id": "11d0a83e-391e-4590-9db6-6a2a3c140ae2", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n", "To disable this warning, you can either:\n", "\t- Avoid using `tokenizers` before the fork if possible\n", "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/nvfuser-0.2.13a0+0d33366-py3.12-linux-x86_64.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/dill-0.3.9-py3.12.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/lightning_utilities-0.11.8-py3.12.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/opt_einsum-3.4.0-py3.12.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/igraph-0.11.8-py3.12-linux-x86_64.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/lightning_thunder-0.2.0.dev0-py3.12.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/texttable-1.7.0-py3.12.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/looseversion-1.3.0-py3.12.egg is deprecated. pip 25.1 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n", "\u001b[0m\n", "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.3.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.1.1\u001b[0m\n", "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython -m pip install --upgrade pip\u001b[0m\n" ] } ], "source": [ "!pip install datasets transformers torch gradio --quiet" ] }, { "cell_type": "code", "execution_count": 1, "id": "7057ed8b-c98c-446e-b40b-2de8a800cb7c", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/usr/local/lib/python3.12/dist-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] } ], "source": [ "from transformers import AutoTokenizer, AutoModelForCausalLM\n", "import torch\n", "\n", "# Ścieżka do lokalnego modelu\n", "local_model_path = \"./gpt-neo-125M\"\n", "\n", "# Załaduj tokenizer i model w trybie offline\n", "tokenizer = AutoTokenizer.from_pretrained(local_model_path, local_files_only=True)\n", "tokenizer.pad_token = tokenizer.eos_token\n", "model = AutoModelForCausalLM.from_pretrained(local_model_path, local_files_only=True)\n" ] }, { "cell_type": "code", "execution_count": 17, "id": "3575956e-aa32-4173-8678-9a34b838ce3c", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Map: 100%|██████████| 20/20 [00:00<00:00, 1442.80 examples/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Dataset({\n", " features: ['input_ids', 'attention_mask'],\n", " num_rows: 20\n", "})\n", "Liczba próbek po tokenizacji: 20\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "from datasets import Dataset\n", "from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments, Trainer, DataCollatorForLanguageModeling\n", "\n", "# Ścieżka do lokalnego modelu\n", "local_model_path = \"./gpt-neo-125M\"\n", "\n", "# Tokenizer\n", "tokenizer = AutoTokenizer.from_pretrained(local_model_path, local_files_only=True)\n", "tokenizer.pad_token = tokenizer.eos_token # <-- wymagane do paddingu\n", "\n", "# Wczytanie danych z pliku\n", "with open(\"data.txt\", encoding=\"utf-8\") as f:\n", " lines = [line.strip() for line in f if line.strip()] # Usuwamy puste linie\n", "\n", "# Budujemy Dataset z listy słowników\n", "data = [{\"text\": line} for line in lines]\n", "raw_dataset = Dataset.from_list(data)\n", "\n", "# Funkcja tokenizująca\n", "def tokenize_function(example):\n", " return tokenizer(\n", " example[\"text\"],\n", " truncation=True,\n", " max_length=128,\n", " padding=\"max_length\"\n", " )\n", "\n", "# Tokenizacja datasetu\n", "tokenized_dataset = raw_dataset.map(tokenize_function, batched=True, remove_columns=[\"text\"])\n", "\n", "# Sprawdź czy dane są OK\n", "print(tokenized_dataset)\n", "print(f\"Liczba próbek po tokenizacji: {len(tokenized_dataset)}\")" ] }, { "cell_type": "code", "execution_count": 18, "id": "c5eedf83-e003-434e-af7c-a57d6efdd120", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_6455/2971221750.py:23: FutureWarning: `tokenizer` is deprecated and will be removed in version 5.0.0 for `Trainer.__init__`. Use `processing_class` instead.\n", " trainer = Trainer(\n" ] }, { "data": { "text/html": [ "\n", "
\n", " \n", " \n", " [60/60 00:12, Epoch 3/3]\n", "
\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
StepTraining Loss
502.103000

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "('./gpt-neo-finetuned/tokenizer_config.json',\n", " './gpt-neo-finetuned/special_tokens_map.json',\n", " './gpt-neo-finetuned/vocab.json',\n", " './gpt-neo-finetuned/merges.txt',\n", " './gpt-neo-finetuned/added_tokens.json',\n", " './gpt-neo-finetuned/tokenizer.json')" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Wczytanie modelu\n", "model = AutoModelForCausalLM.from_pretrained(local_model_path, local_files_only=True)\n", "\n", "# Collator (bez maskowania)\n", "data_collator = DataCollatorForLanguageModeling(\n", " tokenizer=tokenizer,\n", " mlm=False\n", ")\n", "\n", "# Argumenty treningowe\n", "training_args = TrainingArguments(\n", " output_dir=\"./gpt-neo-finetuned\",\n", " overwrite_output_dir=True,\n", " per_device_train_batch_size=1,\n", " num_train_epochs=3,\n", " save_steps=500,\n", " logging_steps=50,\n", " prediction_loss_only=True,\n", " fp16=True\n", ")\n", "\n", "# Tworzymy Trainer\n", "trainer = Trainer(\n", " model=model,\n", " args=training_args,\n", " train_dataset=tokenized_dataset, # <-- to była literówka, nie \"train_dataset\"\n", " tokenizer=tokenizer,\n", " data_collator=data_collator\n", ")\n", "\n", "# Start treningu\n", "trainer.train()\n", "\n", "# Zapis modelu i tokenizer\n", "trainer.save_model(\"./gpt-neo-finetuned\")\n", "tokenizer.save_pretrained(\"./gpt-neo-finetuned\")\n" ] }, { "cell_type": "code", "execution_count": 19, "id": "0d5c46d3-e115-4a68-9337-1f20b62a21a4", "metadata": {}, "outputs": [], "source": [ "model_path = \"./gpt-neo-finetuned\"\n", "\n", "tokenizer = AutoTokenizer.from_pretrained(model_path)\n", "model = AutoModelForCausalLM.from_pretrained(model_path)" ] }, { "cell_type": "code", "execution_count": 20, "id": "e656cc27-3748-4530-9ae5-05b2f8e9e105", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7863\n", "* Running on public URL: https://596aa820b4401f3637.gradio.live\n", "\n", "This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n" ] }, { "data": { "text/html": [ "

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import gradio as gr\n", "\n", "def chat(message, chat_history):\n", " if chat_history:\n", " prompt = chat_history + f\"\\nUser: {message}\\nAI:\"\n", " else:\n", " prompt = f\"User: {message}\\nAI:\"\n", " \n", " inputs = tokenizer(prompt, return_tensors=\"pt\")\n", " outputs = model.generate(\n", " **inputs,\n", " max_length=len(inputs[\"input_ids\"][0]) + 200,\n", " temperature=0.7,\n", " pad_token_id=tokenizer.eos_token_id,\n", " do_sample=True,\n", " top_p=0.9\n", " )\n", " full_response = tokenizer.decode(outputs[0], skip_special_tokens=True)\n", " response = full_response.split(\"AI:\")[-1].strip()\n", " chat_history += f\"\\nUser: {message}\\nAI: {response}\"\n", " return chat_history, chat_history\n", "\n", "# Gradio UI w trybie notebookowym\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\"### Lokalny Czat z GPT\")\n", " chatbot_output = gr.Textbox(label=\"Historia rozmowy\", lines=20, interactive=False)\n", " user_input = gr.Textbox(label=\"Twoje pytanie\", placeholder=\"Zadaj pytanie i naciśnij Enter\")\n", " state = gr.State(\"\")\n", "\n", " user_input.submit(chat, [user_input, state], [chatbot_output, state])\n", " user_input.submit(lambda: \"\", None, user_input) # Czyści input po wysłaniu\n", "\n", "demo.launch(inline=True,share=True)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.3" } }, "nbformat": 4, "nbformat_minor": 5 }