Download train.py from unixdevil/social-media-post: direct link, hf CLI and curl.
- Browser
- Download file 2.13 kB
-
https://huggingface.co/datasets/unixdevil/social-media-post/resolve/main/train.py
- Command line
-
hf download hf://datasets/unixdevil/social-media-post/train.py
-
curl -L -o train.py https://huggingface.co/datasets/unixdevil/social-media-post/resolve/main/train.py
2.13 kB
| from unsloth import FastLanguageModel | |
| from datasets import load_dataset | |
| from trl import SFTTrainer | |
| from transformers import TrainingArguments | |
| # ========================= | |
| # 1. Load Dataset | |
| # ========================= | |
| dataset = load_dataset("json", data_files="unsloth_dataset.jsonl", split="train") | |
| def format_prompt(example): | |
| return { | |
| "text": f"""### Instruction: | |
| {example['instruction']} | |
| ### Input: | |
| {example['input']} | |
| ### Response: | |
| {example['output']}""" | |
| } | |
| dataset = dataset.map(format_prompt) | |
| # ========================= | |
| # 2. Load Model (QLoRA) | |
| # ========================= | |
| model, tokenizer = FastLanguageModel.from_pretrained( | |
| model_name="unsloth/mistral-7b-bnb-4bit", | |
| max_seq_length=2048, | |
| dtype=None, | |
| load_in_4bit=True, | |
| ) | |
| model = FastLanguageModel.get_peft_model( | |
| model, | |
| r=16, # LoRA rank | |
| target_modules=[ | |
| "q_proj", "k_proj", "v_proj", "o_proj", | |
| "gate_proj", "up_proj", "down_proj" | |
| ], | |
| lora_alpha=16, | |
| lora_dropout=0.05, | |
| bias="none", | |
| use_gradient_checkpointing=True, | |
| ) | |
| # ========================= | |
| # 3. Training Arguments | |
| # ========================= | |
| training_args = TrainingArguments( | |
| output_dir="./outputs", | |
| # Core training | |
| per_device_train_batch_size=2, | |
| gradient_accumulation_steps=4, | |
| warmup_steps=50, | |
| max_steps=1000, | |
| # Optimisation | |
| learning_rate=2e-4, | |
| fp16=True, | |
| logging_steps=10, | |
| # Stability | |
| optim="adamw_8bit", | |
| weight_decay=0.01, | |
| lr_scheduler_type="cosine", | |
| # Saving | |
| save_steps=200, | |
| save_total_limit=3, | |
| # Misc | |
| report_to="none", | |
| ) | |
| # ========================= | |
| # 4. Trainer | |
| # ========================= | |
| trainer = SFTTrainer( | |
| model=model, | |
| tokenizer=tokenizer, | |
| train_dataset=dataset, | |
| dataset_text_field="text", | |
| max_seq_length=2048, | |
| packing=True, | |
| args=training_args, | |
| ) | |
| # ========================= | |
| # 5. Train | |
| # ========================= | |
| trainer.train() | |
| # ========================= | |
| # 6. Save Model | |
| # ========================= | |
| model.save_pretrained("lora_model") | |
| tokenizer.save_pretrained("lora_model") | |