Views
No views yet
codellama/CodeLlama-7b-Instruct-hf designed to enhance instruction-following capabilities. It was developed as part of a Master's thesis project.codellama-7b-matplotlib-assistant model is a large language model fine-tuned using the QLoRA (4-bit Quantization + LoRA) technique. The goal of this model was to adapt the base CodeLlama model to better follow user instructions while maintaining its coding and reasoning capabilities.parquet02), it might exhibit limitations when handling domains outside of its training distribution. Users should expect potential hallucinations in complex reasoning tasks.1import os
2import torch
3from datasets import load_dataset
4from transformers import (
5 AutoModelForCausalLM,
6 AutoTokenizer,
7 BitsAndBytesConfig,
8 TrainingArguments,
9 pipeline,
10 logging,
11)
12from peft import LoraConfig
13from trl import SFTTrainer
14
15# ==========================================
16# 1. Global Parameter Configuration
17# ==========================================
18base_model = "codeparrot/codeparrot" # Base model ID on Hugging Face
19new_dataset = "mingyue0101/prompts_modi" # Fine-tuning dataset ID
20new_model = "codeparrot_ming03" # Directory name for saving the fine-tuned model
21
22# ==========================================
23# 2. Dataset Loading
24# ==========================================
25dataset = load_dataset(new_dataset, split="train")
26
27# ==========================================
28# 3. QLoRA 4-bit Quantization Configuration
29# ==========================================
30compute_dtype = getattr(torch, "float16")
31quant_config = BitsAndBytesConfig(
32 load_in_4bit=True, # Enable 4-bit quantization storage
33 bnb_4bit_quant_type="nf4", # Use NormalFloat4 for better precision than FP4
34 bnb_4bit_compute_dtype=compute_dtype, # Cast to Float16 during matrix multiplication
35 bnb_4bit_use_double_quant=False, # Disable double quantization
36)
37
38# ==========================================
39# 4. Load Base Model with Optimizations
40# ==========================================
41model = AutoModelForCausalLM.from_pretrained(
42 base_model,
43 quantization_config=quant_config,
44 device_map={"": 0} # Force load the model onto the first GPU (GPU 0)
45)
46model.config.use_cache = False # Must disable KV cache during training to avoid backprop conflicts
47model.config.pretraining_tp = 1 # Set tensor parallelism to 1 for single-GPU training
48
49# ==========================================
50# 5. Tokenizer Configuration & Alignment
51# ==========================================
52tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)
53tokenizer.pad_token = tokenizer.eos_token # Causal LMs usually have no pad_token; reuse eos_token
54tokenizer.padding_side = "right" # Pad on the right to maintain proper causal attention masks
55
56# ==========================================
57# 6. PEFT (Lora) Adapter Hyperparameters
58# ==========================================
59peft_params = LoraConfig(
60 r=64, # LoRA rank, controlling the number of trainable parameters
61 lora_alpha=16, # Scaling factor for LoRA weights
62 lora_dropout=0.1, # Dropout probability to prevent overfitting in the adapter
63 bias="none", # Do not train bias parameters
64 task_type="CAUSAL_LM", # Explicitly declare the task type as Causal LM
65 fan_in_fan_out="True"
66)
67
68# ==========================================
69# 7. Training Arguments
70# ==========================================
71training_params = TrainingArguments(
72 output_dir="./results", # Output directory for checkpoints and logs
73 num_train_epochs=1, # Number of training epochs
74 per_device_train_batch_size=4, # Batch size per device during training
75 gradient_accumulation_steps=1, # Number of updates steps to accumulate gradients
76 optim="paged_adamw_32bit", # Use QLoRA paged optimizer to prevent Out-Of-Memory (OOM)
77 save_steps=25, # Save checkpoint every 25 steps
78 logging_steps=25, # Log training metrics every 25 steps
79 learning_rate=2e-4, # Initial learning rate
80 weight_decay=0.001, # Weight decay coefficient
81 fp16=False, # Disable standard fp16 (handled by the quantization kernel)
82 bf16=False,
83 max_grad_norm=0.3, # Max gradient norm for gradient clipping
84 max_steps=-1, # Rely on epochs instead of max_steps to control training length
85 warmup_ratio=0.03, # Linear warmup ratio over training steps
86 group_by_length=True, # Group sequences of similar lengths into batches to speed up training
87 lr_scheduler_type="constant", # Learning rate schedule type
88 report_to="tensorboard" # Use TensorBoard to log training progress
89)
90
91# ==========================================
92# 8. Start Supervised Fine-Tuning (SFT) & Save
93# ==========================================
94trainer = SFTTrainer(
95 model=model,
96 train_dataset=dataset,
97 peft_config=peft_params,
98 dataset_text_field="column0", # Name of the column containing text data in the dataset
99 max_seq_length=None, # Use default maximum sequence length
100 tokenizer=tokenizer,
101 args=training_params,
102 packing=False, # Disable sample packing (combining multiple examples into one sequence)
103)
104
105# Launch the training process
106trainer.train()
107
108# Save the trained LoRA adapter weights and tokenizer files
109trainer.model.save_pretrained(new_model)
110trainer.tokenizer.save_pretrained(new_model)
111print(f"Training complete! Finetuned weights successfully saved to: {new_model}")mingyue0101/parquet02 dataset. This dataset contains instruction-response pairs formatted for Supervised Fine-Tuning (SFT).