2025-02-26 07:15:18 -05:00
|
|
|
|
import os
|
|
|
|
|
|
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
|
|
|
|
|
2025-02-26 06:16:11 -05:00
|
|
|
|
import torch
|
2025-02-26 07:00:07 -05:00
|
|
|
|
import faiss
|
|
|
|
|
|
import numpy as np
|
2025-02-26 06:16:11 -05:00
|
|
|
|
from sentence_transformers import SentenceTransformer
|
|
|
|
|
|
from datasets import Dataset
|
|
|
|
|
|
from peft import LoraConfig, get_peft_model
|
2025-02-26 07:15:18 -05:00
|
|
|
|
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer, DataCollatorForLanguageModeling
|
2025-02-26 06:16:11 -05:00
|
|
|
|
|
2025-02-26 07:00:07 -05:00
|
|
|
|
# 1️⃣ Inicjalizacja modelu do embeddingów
|
2025-02-26 06:16:11 -05:00
|
|
|
|
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
|
|
|
|
|
|
|
|
|
|
|
|
# 2️⃣ Dodanie dokumentów i embeddingów
|
2025-02-26 07:53:34 -05:00
|
|
|
|
def read_documents_from_file(file_path):
|
|
|
|
|
|
with open(file_path, 'r', encoding='utf-8') as file:
|
|
|
|
|
|
content = file.read()
|
|
|
|
|
|
articles = content.split('\n\n')
|
|
|
|
|
|
documents = []
|
|
|
|
|
|
for article in articles:
|
|
|
|
|
|
if article.strip().startswith('Art.'):
|
|
|
|
|
|
documents.append(article.strip())
|
|
|
|
|
|
return documents
|
|
|
|
|
|
#documents = [
|
|
|
|
|
|
# "Jak założyć firmę w Polsce?",
|
|
|
|
|
|
# "Jak rozliczyć podatek VAT?",
|
|
|
|
|
|
# "Procedura składania reklamacji w e-sklepie.",
|
|
|
|
|
|
# "Jakie dokumenty są potrzebne do rejestracji działalności?"
|
|
|
|
|
|
#]
|
|
|
|
|
|
file_path = './docs/kodekspracy.txt' # Zmień na właściwą ścieżkę
|
|
|
|
|
|
documents = read_documents_from_file(file_path)
|
2025-02-26 07:00:07 -05:00
|
|
|
|
embeddings = embed_model.encode(documents)
|
2025-02-26 06:16:11 -05:00
|
|
|
|
|
2025-02-26 07:00:07 -05:00
|
|
|
|
# 3️⃣ Inicjalizacja FAISS i dodanie wektorów
|
2025-02-26 07:15:18 -05:00
|
|
|
|
dim = embeddings.shape[1]
|
|
|
|
|
|
index = faiss.IndexFlatL2(dim)
|
|
|
|
|
|
index.add(np.array(embeddings, dtype=np.float32))
|
2025-02-26 06:16:11 -05:00
|
|
|
|
|
2025-02-26 07:00:07 -05:00
|
|
|
|
# 4️⃣ Przygotowanie danych treningowych
|
2025-02-26 06:16:11 -05:00
|
|
|
|
def create_training_data():
|
2025-02-26 07:00:07 -05:00
|
|
|
|
data = {
|
|
|
|
|
|
"text": documents,
|
|
|
|
|
|
"embedding": embeddings.tolist()
|
|
|
|
|
|
}
|
|
|
|
|
|
return Dataset.from_dict(data)
|
2025-02-26 06:16:11 -05:00
|
|
|
|
|
|
|
|
|
|
dataset = create_training_data()
|
|
|
|
|
|
|
2025-02-26 07:25:17 -05:00
|
|
|
|
# Podział danych na treningowe i ewaluacyjne
|
|
|
|
|
|
split_dataset = dataset.train_test_split(test_size=0.25)
|
|
|
|
|
|
train_dataset = split_dataset["train"]
|
|
|
|
|
|
eval_dataset = split_dataset["test"]
|
|
|
|
|
|
|
|
|
|
|
|
# 5️⃣ Ładowanie modelu Gemma 2B
|
2025-02-26 06:16:11 -05:00
|
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu"
|
2025-02-26 07:19:09 -05:00
|
|
|
|
model_name = "google/gemma-2-2b"
|
2025-02-26 06:16:11 -05:00
|
|
|
|
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16).to(device)
|
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
|
|
|
|
|
|
2025-02-26 07:25:17 -05:00
|
|
|
|
# 6️⃣ Konfiguracja LoRA
|
2025-02-26 06:16:11 -05:00
|
|
|
|
lora_config = LoraConfig(
|
|
|
|
|
|
r=8, lora_alpha=32, lora_dropout=0.1, bias="none", task_type="CAUSAL_LM"
|
|
|
|
|
|
)
|
|
|
|
|
|
model = get_peft_model(model, lora_config)
|
|
|
|
|
|
|
2025-02-26 07:00:07 -05:00
|
|
|
|
# 7️⃣ Tokenizacja danych
|
2025-02-26 08:07:49 -05:00
|
|
|
|
max_length = 384
|
2025-02-26 07:15:18 -05:00
|
|
|
|
|
2025-02-26 06:16:11 -05:00
|
|
|
|
def tokenize_function(examples):
|
2025-02-26 07:15:18 -05:00
|
|
|
|
return tokenizer(
|
|
|
|
|
|
examples["text"],
|
|
|
|
|
|
padding="max_length",
|
|
|
|
|
|
truncation=True,
|
|
|
|
|
|
max_length=max_length
|
|
|
|
|
|
)
|
2025-02-26 06:16:11 -05:00
|
|
|
|
|
2025-02-26 07:25:17 -05:00
|
|
|
|
tokenized_train = train_dataset.map(tokenize_function, batched=True)
|
|
|
|
|
|
tokenized_eval = eval_dataset.map(tokenize_function, batched=True)
|
2025-02-26 06:16:11 -05:00
|
|
|
|
|
2025-02-26 07:00:07 -05:00
|
|
|
|
# 8️⃣ Parametry treningu
|
2025-02-26 06:16:11 -05:00
|
|
|
|
training_args = TrainingArguments(
|
|
|
|
|
|
output_dir="./results",
|
2025-02-26 07:25:17 -05:00
|
|
|
|
eval_strategy="steps", # Ewaluacja co określoną liczbę kroków
|
|
|
|
|
|
eval_steps=500, # Ewaluacja co 500 kroków
|
|
|
|
|
|
save_strategy="steps", # Zapis modelu co określoną liczbę kroków
|
|
|
|
|
|
save_steps=500, # Zapis modelu co 500 kroków
|
2025-02-26 07:56:35 -05:00
|
|
|
|
learning_rate=1e-5,
|
2025-02-26 06:16:11 -05:00
|
|
|
|
per_device_train_batch_size=2,
|
2025-02-26 07:17:57 -05:00
|
|
|
|
per_device_eval_batch_size=2,
|
2025-02-26 07:56:48 -05:00
|
|
|
|
num_train_epochs=16,
|
2025-02-26 07:17:57 -05:00
|
|
|
|
weight_decay=0.01,
|
2025-02-26 07:25:17 -05:00
|
|
|
|
load_best_model_at_end=True, # Wczytaj najlepszy model na końcu
|
|
|
|
|
|
metric_for_best_model="loss", # Kryterium wyboru najlepszego modelu
|
|
|
|
|
|
greater_is_better=False, # Niższy loss = lepszy model
|
2025-02-26 07:15:18 -05:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# 9️⃣ Data Collator
|
|
|
|
|
|
data_collator = DataCollatorForLanguageModeling(
|
|
|
|
|
|
tokenizer=tokenizer,
|
|
|
|
|
|
mlm=False
|
2025-02-26 06:16:11 -05:00
|
|
|
|
)
|
|
|
|
|
|
|
2025-02-26 07:15:18 -05:00
|
|
|
|
# 🔟 Trening modelu
|
2025-02-26 06:16:11 -05:00
|
|
|
|
trainer = Trainer(
|
|
|
|
|
|
model=model,
|
|
|
|
|
|
args=training_args,
|
2025-02-26 07:25:17 -05:00
|
|
|
|
train_dataset=tokenized_train,
|
|
|
|
|
|
eval_dataset=tokenized_eval, # Dodany zestaw ewaluacyjny
|
2025-02-26 07:15:18 -05:00
|
|
|
|
data_collator=data_collator,
|
2025-02-26 06:16:11 -05:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
trainer.train()
|
|
|
|
|
|
|
2025-02-26 07:25:17 -05:00
|
|
|
|
# 1️⃣1️⃣ Zapis modelu
|
2025-02-26 06:16:11 -05:00
|
|
|
|
model.save_pretrained("./trained_model/gemma")
|
|
|
|
|
|
tokenizer.save_pretrained("./trained_model/gemma")
|
|
|
|
|
|
|
2025-02-26 07:25:17 -05:00
|
|
|
|
print("✅ Model został wytrenowany i zapisany!")
|