Update all_in_one.py
Browse files- all_in_one.py +114 -114
all_in_one.py
CHANGED
|
@@ -1,115 +1,115 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import torch
|
| 3 |
-
|
| 4 |
-
from
|
| 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 |
-
plt.
|
| 88 |
-
plt.
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
"Write a Python
|
| 101 |
-
]
|
| 102 |
-
|
| 103 |
-
for prompt in prompts:
|
| 104 |
-
inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=128).to(device)
|
| 105 |
-
outputs = model.generate(
|
| 106 |
-
**inputs,
|
| 107 |
-
max_length=200,
|
| 108 |
-
num_return_sequences=1,
|
| 109 |
-
pad_token_id=tokenizer.eos_token_id,
|
| 110 |
-
do_sample=True,
|
| 111 |
-
temperature=0.7,
|
| 112 |
-
top_p=0.9
|
| 113 |
-
)
|
| 114 |
-
generated_code = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 115 |
print(f"Prompt: {prompt}\nGenerated Code:\n{generated_code}\n{'-'*50}")
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import json
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, TrainingArguments, DataCollatorForLanguageModeling, TrainerCallback
|
| 5 |
+
from datasets import Dataset
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
|
| 8 |
+
# Set Hugging Face token (replace with your actual token)
|
| 9 |
+
os.environ["HF_TOKEN"] = "hf_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" # Replace with your HF_TOKEN
|
| 10 |
+
|
| 11 |
+
# Download model and tokenizer
|
| 12 |
+
model_name = "Salesforce/codegen-350M-multi"
|
| 13 |
+
local_model_path = "./codegen_model"
|
| 14 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, cache_dir=local_model_path)
|
| 15 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float32, cache_dir=local_model_path)
|
| 16 |
+
|
| 17 |
+
# Set padding token
|
| 18 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 19 |
+
|
| 20 |
+
# Move model to CPU
|
| 21 |
+
device = torch.device("cpu")
|
| 22 |
+
model.to(device)
|
| 23 |
+
|
| 24 |
+
# Load custom dataset from JSONL
|
| 25 |
+
dataset_path = "./custom_dataset.jsonl"
|
| 26 |
+
data = []
|
| 27 |
+
with open(dataset_path, 'r', encoding='utf-8') as f:
|
| 28 |
+
for line in f:
|
| 29 |
+
data.append(json.loads(line.strip()))
|
| 30 |
+
dataset = Dataset.from_list(data)
|
| 31 |
+
|
| 32 |
+
# Tokenize dataset
|
| 33 |
+
def tokenize_function(examples):
|
| 34 |
+
inputs = [f"{prompt}\n{code}" for prompt, code in zip(examples["prompt"], examples["code"])]
|
| 35 |
+
return tokenizer(inputs, truncation=True, padding="max_length", max_length=128)
|
| 36 |
+
|
| 37 |
+
tokenized_dataset = dataset.map(tokenize_function, batched=True, remove_columns=["prompt", "code"])
|
| 38 |
+
|
| 39 |
+
# Data collator for language modeling
|
| 40 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
|
| 41 |
+
|
| 42 |
+
# Define training arguments
|
| 43 |
+
training_args = TrainingArguments(
|
| 44 |
+
output_dir="./finetuned_codegen",
|
| 45 |
+
overwrite_output_dir=True,
|
| 46 |
+
num_train_epochs=3,
|
| 47 |
+
per_device_train_batch_size=1,
|
| 48 |
+
gradient_accumulation_steps=4,
|
| 49 |
+
save_steps=500,
|
| 50 |
+
save_total_limit=2,
|
| 51 |
+
logging_steps=100,
|
| 52 |
+
learning_rate=5e-5,
|
| 53 |
+
fp16=False,
|
| 54 |
+
no_cuda=True,
|
| 55 |
+
dataloader_pin_memory=False,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# Custom callback to store training loss
|
| 59 |
+
class LossCallback(TrainerCallback):
|
| 60 |
+
def __init__(self):
|
| 61 |
+
self.losses = []
|
| 62 |
+
|
| 63 |
+
def on_log(self, args, state, control, logs=None, **kwargs):
|
| 64 |
+
if logs and "loss" in logs:
|
| 65 |
+
self.losses.append(logs["loss"])
|
| 66 |
+
|
| 67 |
+
loss_callback = LossCallback()
|
| 68 |
+
|
| 69 |
+
# Initialize Trainer
|
| 70 |
+
trainer = Trainer(
|
| 71 |
+
model=model,
|
| 72 |
+
args=training_args,
|
| 73 |
+
train_dataset=tokenized_dataset,
|
| 74 |
+
data_collator=data_collator,
|
| 75 |
+
callbacks=[loss_callback],
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
# Start fine-tuning
|
| 79 |
+
print("Starting fine-tuning...")
|
| 80 |
+
trainer.train()
|
| 81 |
+
|
| 82 |
+
# Save fine-tuned model
|
| 83 |
+
model.save_pretrained("./finetuned_codegen")
|
| 84 |
+
tokenizer.save_pretrained("./finetuned_codegen")
|
| 85 |
+
|
| 86 |
+
# Plot training loss
|
| 87 |
+
plt.plot(loss_callback.losses, label="Training Loss")
|
| 88 |
+
plt.xlabel("Steps")
|
| 89 |
+
plt.ylabel("Loss")
|
| 90 |
+
plt.title("Fine-Tuning Loss Curve")
|
| 91 |
+
plt.legend()
|
| 92 |
+
plt.savefig("./finetuned_codegen/loss_plot.png")
|
| 93 |
+
plt.show()
|
| 94 |
+
|
| 95 |
+
print("Fine-tuning completed. Model saved to ./finetuned_codegen. Loss plot saved to ./finetuned_codegen/loss_plot.png")
|
| 96 |
+
|
| 97 |
+
# Test fine-tuned model
|
| 98 |
+
print("\nTesting fine-tuned model...")
|
| 99 |
+
prompts = [
|
| 100 |
+
"Write a Python program to print 'Hello, World!'"
|
| 101 |
+
]
|
| 102 |
+
|
| 103 |
+
for prompt in prompts:
|
| 104 |
+
inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=128).to(device)
|
| 105 |
+
outputs = model.generate(
|
| 106 |
+
**inputs,
|
| 107 |
+
max_length=200,
|
| 108 |
+
num_return_sequences=1,
|
| 109 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 110 |
+
do_sample=True,
|
| 111 |
+
temperature=0.7,
|
| 112 |
+
top_p=0.9
|
| 113 |
+
)
|
| 114 |
+
generated_code = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 115 |
print(f"Prompt: {prompt}\nGenerated Code:\n{generated_code}\n{'-'*50}")
|