| |
| |
| |
| |
| |
| |
| |
| |
|
|
| import os |
| import torch |
| from datasets import load_dataset |
| from transformers import ( |
| AutoModelForCausalLM, |
| AutoTokenizer, |
| BitsAndBytesConfig, |
| TrainingArguments, |
| ) |
| from peft import LoraConfig, PeftModel |
| from trl import SFTTrainer |
|
|
| |
| |
| base_model_name = "Qwen/Qwen2.5-Coder-3B-Instruct" |
| |
| dataset_name = "corrected_syntax_dataset.jsonl" |
| |
| adapter_model_name = "Syntax-Copilot-adapter" |
| |
| final_model_name = "Syntax-Copilot" |
|
|
| |
| lora_r = 64 |
| lora_alpha = 16 |
| lora_dropout = 0.1 |
|
|
| |
| use_4bit = True |
| bnb_4bit_compute_dtype = "float16" |
| bnb_4bit_quant_type = "nf4" |
| use_nested_quant = False |
|
|
| |
| output_dir = "./training_results" |
| num_train_epochs = 1 |
| |
| bf16 = True |
| per_device_train_batch_size = 4 |
| gradient_accumulation_steps = 1 |
| gradient_checkpointing = True |
| max_grad_norm = 0.3 |
| learning_rate = 2e-4 |
| weight_decay = 0.001 |
| optim = "paged_adamw_32bit" |
| lr_scheduler_type = "cosine" |
| max_steps = -1 |
| warmup_ratio = 0.03 |
| group_by_length = True |
| save_steps = 50 |
| logging_steps = 10 |
|
|
| |
| max_seq_length = 1024 |
| packing = False |
| device_map = {"": 0} |
|
|
| |
|
|
| def main(): |
| |
| print("Loading dataset...") |
| dataset = load_dataset('json', data_files=dataset_name, split="train") |
| print(f"Dataset loaded with {len(dataset)} examples.") |
|
|
| |
| print(f"Loading base model '{base_model_name}'...") |
| |
| compute_dtype = getattr(torch, bnb_4bit_compute_dtype) |
| bnb_config = BitsAndBytesConfig( |
| load_in_4bit=use_4bit, |
| bnb_4bit_quant_type=bnb_4bit_quant_type, |
| bnb_4bit_compute_dtype=compute_dtype, |
| bnb_4bit_use_double_quant=use_nested_quant, |
| ) |
|
|
| model = AutoModelForCausalLM.from_pretrained( |
| base_model_name, |
| quantization_config=bnb_config, |
| device_map=device_map, |
| trust_remote_code=True |
| ) |
| model.config.use_cache = False |
| model.config.pretraining_tp = 1 |
|
|
| tokenizer = AutoTokenizer.from_pretrained(base_model_name, trust_remote_code=True) |
| tokenizer.pad_token = tokenizer.eos_token |
| tokenizer.padding_side = "right" |
|
|
| |
| def format_chat_template(example): |
| |
| |
| return {"text": tokenizer.apply_chat_template(example["messages"], tokenize=False)} |
|
|
| print("Formatting dataset with chat template...") |
| formatted_dataset = dataset.map(format_chat_template) |
| print("Dataset formatted.") |
|
|
| |
| peft_config = LoraConfig( |
| lora_alpha=lora_alpha, |
| lora_dropout=lora_dropout, |
| r=lora_r, |
| bias="none", |
| task_type="CAUSAL_LM", |
| target_modules=[ |
| "q_proj", "k_proj", "v_proj", "o_proj", |
| "gate_proj", "up_proj", "down_proj" |
| ], |
| ) |
|
|
| |
| training_arguments = TrainingArguments( |
| output_dir=output_dir, |
| num_train_epochs=num_train_epochs, |
| per_device_train_batch_size=per_device_train_batch_size, |
| gradient_accumulation_steps=gradient_accumulation_steps, |
| optim=optim, |
| save_steps=save_steps, |
| logging_steps=logging_steps, |
| learning_rate=learning_rate, |
| weight_decay=weight_decay, |
| fp16=False, |
| bf16=bf16, |
| max_grad_norm=max_grad_norm, |
| max_steps=max_steps, |
| warmup_ratio=warmup_ratio, |
| group_by_length=group_by_length, |
| lr_scheduler_type=lr_scheduler_type, |
| report_to="tensorboard" |
| ) |
|
|
| |
| trainer = SFTTrainer( |
| model=model, |
| train_dataset=formatted_dataset, |
| peft_config=peft_config, |
| dataset_text_field="text", |
| max_seq_length=max_seq_length, |
| tokenizer=tokenizer, |
| args=training_arguments, |
| packing=packing, |
| ) |
|
|
| |
| print("Starting model training...") |
| trainer.train() |
| print("Training complete.") |
|
|
| |
| print(f"Saving fine-tuned adapter model to '{adapter_model_name}'...") |
| trainer.model.save_pretrained(adapter_model_name) |
| print("Adapter model saved.") |
|
|
| |
| print("Merging the base model with the adapter to create the final model...") |
| |
| |
| base_model_for_merging = AutoModelForCausalLM.from_pretrained( |
| base_model_name, |
| low_cpu_mem_usage=True, |
| return_dict=True, |
| torch_dtype=torch.float16, |
| device_map=device_map, |
| trust_remote_code=True |
| ) |
|
|
| |
| merged_model = PeftModel.from_pretrained(base_model_for_merging, adapter_model_name) |
| |
| merged_model = merged_model.merge_and_unload() |
| print("Model merged.") |
|
|
| |
| print(f"Saving final merged model to '{final_model_name}'...") |
| merged_model.save_pretrained(final_model_name, safe_serialization=True) |
| tokenizer.save_pretrained(final_model_name) |
| print(f"Final model '{final_model_name}' saved successfully.") |
|
|
| print("\n--- Fine-tuning process complete ---") |
| print(f"LoRA adapter model is in: '{adapter_model_name}'") |
| print(f"Final merged model is in: '{final_model_name}'") |
|
|
| if __name__ == "__main__": |
| main() |
|
|