|
| 1 | +# 🦄 Fine-Tune Llama-3.8B to Write Pirate Jokes & Shakespearean Sonnets |
| 2 | +# Using bitsandbytes 4-bit + torch.compile 🏴☠️ |
| 3 | + |
| 4 | +# !pip install -qU "unsloth[colab] @ git+https://github.com/unslothai/unsloth.git" \ |
| 5 | +# transformers==4.40.0 accelerate==0.30.0 bitsandbytes==0.43.0 |
| 6 | + |
| 7 | +from datasets import load_dataset |
| 8 | +import torch |
| 9 | +from unsloth import FastLanguageModel |
| 10 | + |
| 11 | +# 1. Load Pre-Quantized Model with bitsandbytes 🎯 |
| 12 | +model, tokenizer = FastLanguageModel.from_pretrained( |
| 13 | + model_name="unsloth/llama-3-8B-bnb-4bit", |
| 14 | + max_seq_length=2048, |
| 15 | + dtype=torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16, |
| 16 | + load_in_4bit=True, |
| 17 | + quantization_config={ |
| 18 | + "bnb_4bit_quant_type": "nf4", |
| 19 | + "bnb_4bit_compute_dtype": torch.bfloat16, |
| 20 | + "bnb_4bit_use_double_quant": True, |
| 21 | + }, |
| 22 | +) |
| 23 | + |
| 24 | +# 2. Prepare Creative Dataset 🎭 |
| 25 | +pirate_dataset = load_dataset( |
| 26 | + "json", |
| 27 | + data_files={"train": "https://huggingface.co/datasets/jondurbin/pirate-jokes/resolve/main/pirate_jokes.json"}, |
| 28 | +) |
| 29 | + |
| 30 | + |
| 31 | +def format_creative_prompt(sample): |
| 32 | + return f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|> |
| 33 | + You are a swashbuckling pirate poet. Respond ONLY in pirate speak or Shakespearean verse.<|eot_id|> |
| 34 | + <|start_header_id|>user<|end_header_id|> |
| 35 | + {sample['prompt']}<|eot_id|> |
| 36 | + <|start_header_id|>assistant<|end_header_id|> |
| 37 | + {sample['response']}<|eot_id|>""" |
| 38 | + |
| 39 | + |
| 40 | +dataset = pirate_dataset.map(format_creative_prompt) |
| 41 | + |
| 42 | +# 3. Configure QLoRA with torch.compile Diagnostics 🔍 |
| 43 | +model = FastLanguageModel.get_peft_model( |
| 44 | + model, |
| 45 | + r=32, |
| 46 | + target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], |
| 47 | + lora_alpha=64, |
| 48 | + lora_dropout=0.1, |
| 49 | + bias="none", |
| 50 | + use_gradient_checkpointing=True, |
| 51 | + torch_compile={ |
| 52 | + "mode": "reduce-overhead", |
| 53 | + "fullgraph": False, # Allow partial compilation initially |
| 54 | + "dynamic": True, |
| 55 | + }, |
| 56 | + random_state=3407, # For reproducibility of creative outputs |
| 57 | +) |
| 58 | + |
| 59 | + |
| 60 | +# 4. Custom Training Loop with Graph Break Analysis 🕵️♂️ |
| 61 | +def detect_graph_breaks(): |
| 62 | + import torch._dynamo |
| 63 | + |
| 64 | + original_verbose = torch._dynamo.config.verbose |
| 65 | + torch._dynamo.config.verbose = True |
| 66 | + |
| 67 | + # Trigger compilation with sample input |
| 68 | + sample_input = tokenizer("Arrr! Tell me about yer treasure...", return_tensors="pt").to("cuda") |
| 69 | + compiled_model = torch.compile(model) |
| 70 | + _ = compiled_model(**sample_input) |
| 71 | + |
| 72 | + torch._dynamo.config.verbose = original_verbose |
| 73 | + |
| 74 | + |
| 75 | +detect_graph_breaks() # Initial graph break detection |
| 76 | + |
| 77 | + |
| 78 | +# 5. Creative Generation During Training 🎩 |
| 79 | +class PirateStreamer: |
| 80 | + def __init__(self, tokenizer): |
| 81 | + self.tokenizer = tokenizer |
| 82 | + self.prompt = "Yarrr! Why did the pirate's chicken cross the road?" |
| 83 | + |
| 84 | + def __call__(self, input_ids, *args, **kwargs): |
| 85 | + if random.random() < 0.1: # 10% chance to generate during training |
| 86 | + with torch.no_grad(): |
| 87 | + outputs = model.generate( |
| 88 | + input_ids=self.tokenizer(self.prompt, return_tensors="pt").to("cuda").input_ids, |
| 89 | + max_new_tokens=50, |
| 90 | + temperature=0.7, |
| 91 | + repetition_penalty=1.1, |
| 92 | + ) |
| 93 | + print("\n🏴☠️ Crew's Update:", self.tokenizer.decode(outputs[0])) |
| 94 | + return input_ids |
| 95 | + |
| 96 | + |
| 97 | +# 6. Launch Training with Progressive Compilation 🚀 |
| 98 | +trainer = SFTTrainer( |
| 99 | + model=model, |
| 100 | + train_dataset=dataset, |
| 101 | + dataset_text_field="text", |
| 102 | + max_seq_length=1024, |
| 103 | + packing=True, |
| 104 | + callbacks=[PirateStreamer(tokenizer)], |
| 105 | + args=TrainingArguments( |
| 106 | + per_device_train_batch_size=2, |
| 107 | + gradient_accumulation_steps=4, |
| 108 | + warmup_steps=10, |
| 109 | + max_steps=100, |
| 110 | + learning_rate=3e-5, |
| 111 | + fp16=not torch.cuda.is_bf16_supported(), |
| 112 | + bf16=torch.cuda.is_bf16_supported(), |
| 113 | + logging_steps=1, |
| 114 | + optim="paged_adamw_8bit", |
| 115 | + weight_decay=0.01, |
| 116 | + lr_scheduler_type="cosine", |
| 117 | + output_dir="pirate-poet", |
| 118 | + report_to="none", |
| 119 | + ), |
| 120 | +) |
| 121 | + |
| 122 | +# Progressive compilation strategy |
| 123 | +trainer.train_step = torch.compile( |
| 124 | + trainer.train_step, |
| 125 | + mode="reduce-overhead", |
| 126 | + fullgraph=False, # Start with partial graphs |
| 127 | + dynamic=True, |
| 128 | +) |
| 129 | + |
| 130 | +print("🏁 Starting training - watch for graph breaks and pirate wisdom!") |
| 131 | +trainer.train() |
0 commit comments