Text Generation
PEFT
Safetensors
English
instruction-tuning
qlora
code-llama
conversational
mingyue0101 commited on
Commit
d0a43a5
·
verified ·
1 Parent(s): 06ecae2

Update README.md

Browse files

update the script.

Files changed (1) hide show
  1. README.md +103 -22
README.md CHANGED
@@ -58,36 +58,117 @@ Users are encouraged to use safety filters when deploying this model in producti
58
  Use the code below to load the model in 4-bit precision:
59
 
60
  ```python
 
61
  import torch
62
- from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
63
- from peft import PeftModel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- model_id = "codellama/CodeLlama-7b-Instruct-hf"
66
- peft_model_id = "mingyue0101/codellama-7b-matplotlib-assistant"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
- # Load 4-bit configuration
69
- bnb_config = BitsAndBytesConfig(
70
- load_in_4bit=True,
71
- bnb_4bit_quant_type="nf4",
72
- bnb_4bit_compute_dtype=torch.float16,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  )
74
 
75
- # Load base model and tokenizer
76
- tokenizer = AutoTokenizer.from_pretrained(model_id)
77
- base_model = AutoModelForCausalLM.from_pretrained(
78
- model_id,
79
- quantization_config=bnb_config,
80
- device_map="auto"
 
 
 
 
 
 
81
  )
82
 
83
- # Load the fine-tuned adapter
84
- model = PeftModel.from_pretrained(base_model, peft_model_id)
85
 
86
- # Inference
87
- prompt = "Write a Python function to sort a list."
88
- inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
89
- outputs = model.generate(**inputs, max_new_tokens=128)
90
- print(tokenizer.decode(outputs[0], skip_special_tokens=True))
91
  ```
92
  ## Training Details
93
  ### Training Data
 
58
  Use the code below to load the model in 4-bit precision:
59
 
60
  ```python
61
+ import os
62
  import torch
63
+ from datasets import load_dataset
64
+ from transformers import (
65
+ AutoModelForCausalLM,
66
+ AutoTokenizer,
67
+ BitsAndBytesConfig,
68
+ TrainingArguments,
69
+ pipeline,
70
+ logging,
71
+ )
72
+ from peft import LoraConfig
73
+ from trl import SFTTrainer
74
+
75
+ # ==========================================
76
+ # 1. Global Parameter Configuration
77
+ # ==========================================
78
+ base_model = "codeparrot/codeparrot" # Base model ID on Hugging Face
79
+ new_dataset = "mingyue0101/prompts_modi" # Fine-tuning dataset ID
80
+ new_model = "codeparrot_ming03" # Directory name for saving the fine-tuned model
81
+
82
+ # ==========================================
83
+ # 2. Dataset Loading
84
+ # ==========================================
85
+ dataset = load_dataset(new_dataset, split="train")
86
+
87
+ # ==========================================
88
+ # 3. QLoRA 4-bit Quantization Configuration
89
+ # ==========================================
90
+ compute_dtype = getattr(torch, "float16")
91
+ quant_config = BitsAndBytesConfig(
92
+ load_in_4bit=True, # Enable 4-bit quantization storage
93
+ bnb_4bit_quant_type="nf4", # Use NormalFloat4 for better precision than FP4
94
+ bnb_4bit_compute_dtype=compute_dtype, # Cast to Float16 during matrix multiplication
95
+ bnb_4bit_use_double_quant=False, # Disable double quantization
96
+ )
97
 
98
+ # ==========================================
99
+ # 4. Load Base Model with Optimizations
100
+ # ==========================================
101
+ model = AutoModelForCausalLM.from_pretrained(
102
+ base_model,
103
+ quantization_config=quant_config,
104
+ device_map={"": 0} # Force load the model onto the first GPU (GPU 0)
105
+ )
106
+ model.config.use_cache = False # Must disable KV cache during training to avoid backprop conflicts
107
+ model.config.pretraining_tp = 1 # Set tensor parallelism to 1 for single-GPU training
108
+
109
+ # ==========================================
110
+ # 5. Tokenizer Configuration & Alignment
111
+ # ==========================================
112
+ tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)
113
+ tokenizer.pad_token = tokenizer.eos_token # Causal LMs usually have no pad_token; reuse eos_token
114
+ tokenizer.padding_side = "right" # Pad on the right to maintain proper causal attention masks
115
+
116
+ # ==========================================
117
+ # 6. PEFT (Lora) Adapter Hyperparameters
118
+ # ==========================================
119
+ peft_params = LoraConfig(
120
+ r=64, # LoRA rank, controlling the number of trainable parameters
121
+ lora_alpha=16, # Scaling factor for LoRA weights
122
+ lora_dropout=0.1, # Dropout probability to prevent overfitting in the adapter
123
+ bias="none", # Do not train bias parameters
124
+ task_type="CAUSAL_LM", # Explicitly declare the task type as Causal LM
125
+ fan_in_fan_out="True"
126
+ )
127
 
128
+ # ==========================================
129
+ # 7. Training Arguments
130
+ # ==========================================
131
+ training_params = TrainingArguments(
132
+ output_dir="./results", # Output directory for checkpoints and logs
133
+ num_train_epochs=1, # Number of training epochs
134
+ per_device_train_batch_size=4, # Batch size per device during training
135
+ gradient_accumulation_steps=1, # Number of updates steps to accumulate gradients
136
+ optim="paged_adamw_32bit", # Use QLoRA paged optimizer to prevent Out-Of-Memory (OOM)
137
+ save_steps=25, # Save checkpoint every 25 steps
138
+ logging_steps=25, # Log training metrics every 25 steps
139
+ learning_rate=2e-4, # Initial learning rate
140
+ weight_decay=0.001, # Weight decay coefficient
141
+ fp16=False, # Disable standard fp16 (handled by the quantization kernel)
142
+ bf16=False,
143
+ max_grad_norm=0.3, # Max gradient norm for gradient clipping
144
+ max_steps=-1, # Rely on epochs instead of max_steps to control training length
145
+ warmup_ratio=0.03, # Linear warmup ratio over training steps
146
+ group_by_length=True, # Group sequences of similar lengths into batches to speed up training
147
+ lr_scheduler_type="constant", # Learning rate schedule type
148
+ report_to="tensorboard" # Use TensorBoard to log training progress
149
  )
150
 
151
+ # ==========================================
152
+ # 8. Start Supervised Fine-Tuning (SFT) & Save
153
+ # ==========================================
154
+ trainer = SFTTrainer(
155
+ model=model,
156
+ train_dataset=dataset,
157
+ peft_config=peft_params,
158
+ dataset_text_field="column0", # Name of the column containing text data in the dataset
159
+ max_seq_length=None, # Use default maximum sequence length
160
+ tokenizer=tokenizer,
161
+ args=training_params,
162
+ packing=False, # Disable sample packing (combining multiple examples into one sequence)
163
  )
164
 
165
+ # Launch the training process
166
+ trainer.train()
167
 
168
+ # Save the trained LoRA adapter weights and tokenizer files
169
+ trainer.model.save_pretrained(new_model)
170
+ trainer.tokenizer.save_pretrained(new_model)
171
+ print(f"Training complete! Finetuned weights successfully saved to: {new_model}")
 
172
  ```
173
  ## Training Details
174
  ### Training Data