A conversational assistant produced by fine-tuning
TinyLlama-1.1B-Chat-v1.0
on the
tatsu-lab/alpaca
instruction dataset (52 K English instruction–response pairs) using
LoRA (rank 16) via TRL's SFTTrainer on a Kaggle Dual T4 GPU environment.
1from transformers import AutoModelForCausalLM, AutoTokenizer
2import torch
3
4model = AutoModelForCausalLM.from_pretrained(
5 "Havoc999/tiny-chatbot",
6 torch_dtype=torch.float16,
7 device_map="auto",
8)
9tokenizer = AutoTokenizer.from_pretrained("Havoc999/tiny-chatbot")
10
11prompt = (
12 "Below is an instruction that describes a task. "
13 "Write a response that appropriately completes the request.\n\n"
14 "### Instruction:\n"
15 "Explain the water cycle in simple terms.\n\n"
16 "### Response:\n"
17)
18
19inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
20output = model.generate(
21 **inputs,
22 max_new_tokens=256,
23 temperature=0.7,
24 top_p=0.9,
25 do_sample=True,
26 repetition_penalty=1.15,
27)
28response = tokenizer.decode(output[0, inputs.input_ids.shape[1]:], skip_special_tokens=True)
29print(response)
1from transformers import pipeline
2
3pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
4
5messages = [
6 {"role": "user", "content": "What is photosynthesis?"},
7]
8
9# TinyLlama-Chat supports the built-in chat template
10prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
11print(pipe(prompt, max_new_tokens=200)[0]["generated_text"])
All benchmarks were evaluated after fine-tuning, using greedy decoding unless otherwise noted.
1# Install dependencies
2# pip install transformers datasets peft trl accelerate bitsandbytes huggingface_hub
3
4from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments
5from peft import LoraConfig, get_peft_model, TaskType
6from trl import SFTTrainer, DataCollatorForCompletionOnlyLM
7from datasets import load_dataset
8
9# 1. Load dataset
10dataset = load_dataset("tatsu-lab/alpaca", split="train")
11
12# 2. Format examples
13def format_alpaca(ex):
14 input_section = f"### Input:\n{ex['input']}\n\n" if ex["input"].strip() else ""
15 return {
16 "text": (
17 "Below is an instruction that describes a task. "
18 "Write a response that appropriately completes the request.\n\n"
19 f"### Instruction:\n{ex['instruction']}\n\n"
20 f"{input_section}"
21 f"### Response:\n{ex['output']}"
22 )
23 }
24
25dataset = dataset.map(format_alpaca, batched=False)
26
27# 3. Load model + LoRA
28tokenizer = AutoTokenizer.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0")
29tokenizer.pad_token = tokenizer.eos_token
30
31model = AutoModelForCausalLM.from_pretrained(
32 "TinyLlama/TinyLlama-1.1B-Chat-v1.0",
33 torch_dtype="auto",
34 device_map={"": 0},
35)
36model.config.use_cache = False
37model.enable_input_require_grads()
38
39lora_config = LoraConfig(
40 r=16, lora_alpha=32, lora_dropout=0.05,
41 bias="none", task_type=TaskType.CAUSAL_LM,
42 target_modules=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"],
43)
44model = get_peft_model(model, lora_config)
45
46# 4. Train
47trainer = SFTTrainer(
48 model=model, tokenizer=tokenizer,
49 train_dataset=dataset,
50 dataset_text_field="text",
51 max_seq_length=512,
52 data_collator=DataCollatorForCompletionOnlyLM("### Response:\n", tokenizer=tokenizer),
53 args=TrainingArguments(
54 output_dir="./chatbot-lora",
55 num_train_epochs=3,
56 per_device_train_batch_size=4,
57 gradient_accumulation_steps=4,
58 learning_rate=2e-4,
59 fp16=True,
60 gradient_checkpointing=True,
61 save_strategy="steps", save_steps=200, save_total_limit=3,
62 eval_strategy="no",
63 ),
64)
65trainer.train()
This model is released under the
Apache 2.0 license, consistent with the
TinyLlama base model
and the
Alpaca dataset.
See
LICENSE for full terms.