ably.do/gemma.py

77 lines
2.4 KiB
Python
Raw Normal View History

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
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer
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
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?"
]
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
dim = embeddings.shape[1] # Wymiary wektorów
index = faiss.IndexFlatL2(dim) # Tworzymy indeks FAISS dla metryki L2
index.add(np.array(embeddings, dtype=np.float32)) # Dodajemy wektory do indeksu FAISS
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
# Pobranie dokumentów (możesz połączyć je z odpowiednimi embeddingami, jeśli trzeba)
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:00:07 -05:00
# 5⃣ Ładowanie modelu Gemma 2 7B
2025-02-26 06:16:11 -05:00
device = "cuda" if torch.cuda.is_available() else "cpu"
model_name = "google/gemma-7b"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16).to(device)
tokenizer = AutoTokenizer.from_pretrained(model_name)
2025-02-26 07:00:07 -05:00
# 6⃣ Konfiguracja LoRA dla efektywnego treningu
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 06:16:11 -05:00
def tokenize_function(examples):
return tokenizer(examples["text"], padding="max_length", truncation=True)
tokenized_dataset = dataset.map(tokenize_function, batched=True)
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",
per_device_train_batch_size=2,
num_train_epochs=3,
logging_dir="./logs",
save_strategy="epoch"
)
2025-02-26 07:00:07 -05:00
# 9⃣ Trening modelu
2025-02-26 06:16:11 -05:00
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
)
trainer.train()
2025-02-26 07:00:07 -05:00
# 🔟 Zapisanie dostrojonego 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:00:07 -05:00
print("✅ Model został wytrenowany i zapisany!")