AI Hints
Home›Fine-Tuning LLMs Tutorial›Interview Questions and Cheat Sheets
Fine-Tuning LLMs · Lesson 116 of 120

Cheat Sheet: Code

The lines you will reuse.

⏱ 2 min read▶ Video at 2:56:31🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

Here are the lines of code you'll use again and again. Pause the video, and take a screenshot, if it helps.

  • The lines you'll reuse
  • Pause the video
  • Take a screenshot

Training with LoRA

Here's training. Load the tokenizer, and the model. Configure LoRA. Configure training, with the epochs, learning rate, and batch size. Create the SFT trainer, with train, and eval data. Train, and save the adapter.

train.pypython
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig

tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME)
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
                  target_modules="all-linear", task_type="CAUSAL_LM")
args = SFTConfig(output_dir="my-lora", num_train_epochs=3, learning_rate=2e-4,
                 per_device_train_batch_size=8, eval_strategy="epoch")
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
                     eval_dataset=data["test"], processing_class=tok, peft_config=lora)
trainer.train()
trainer.save_model("my-lora")

Using and merging

And here's using the model. Load the base model, with the adapter. Call eval. Apply the chat template, and generate. Decode only the new tokens. Then merge, and save the final model, with its tokenizer.

use.pypython
from peft import PeftModel

model = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(NAME), "my-lora")
model.eval()
ids = tok.apply_chat_template(messages, add_generation_prompt=True,
                              return_dict=True, return_tensors="pt")
out = model.generate(**ids, max_new_tokens=50, do_sample=False)
print(tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True))

merged = model.merge_and_unload()
merged.save_pretrained("my-model")
tok.save_pretrained("my-model")

Summary

Let's recap. Load, configure LoRA, configure training, train, and save. Then load the adapter, call eval, generate, and merge. Next, a cheat sheet of settings.

Key takeaways
  • LoraConfig + SFTConfig
  • SFTTrainer.train()
  • eval, generate, merge
Next up: Cheat Sheet: Settings — good starting values