Here’s a step-by-step implementation plan for fine-tuning Phi-3 (Microsoft’s small but powerful language model) for table reasoning tasks (classification/regression). The plan includes data prep, training, evaluation, and deployment.
🚀 Phi-3 Fine-Tuning Implementation Plan
Objective : Fine-tune Phi-3 (e.g., phi-3-mini-4k-instruct) for table-based tasks (classification, regression, or QA).
Phase 1: Setup & Data Preparation
📌 Step 1: Install Dependencies
bash Copy code
pip install torch transformers datasets pandas accelerate peft bitsandbytes scikit-learn
📌 Step 2: Load & Preprocess Data
Input Format : Tables (CSV/JSON/Markdown) + questions + answers.
Example Dataset Structure :
python Copy code
{
"table": "| Name | Age | Salary |\n|------|-----|--------|\n| Alice | 30 | 70k |",
"question": "What is Alice's salary?",
"answer": "70k"
}
Preprocessing :
Convert tables to structured text (Markdown or flattened rows).
Tokenize using Phi-3’s tokenizer.
📌 Step 3: Tokenization
python Copy code
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
tokenizer.pad_token = tokenizer.eos_token # Set pad token
def preprocess_function(examples):
inputs = [f"Table: {table}\nQuestion: {question}\nAnswer:" for table, question in zip(examples["table"], examples["question"])]
model_inputs = tokenizer(inputs, max_length=512, truncation=True, padding="max_length")
labels = tokenizer(examples["answer"], max_length=128, truncation=True, padding="max_length")
model_inputs["labels"] = labels["input_ids"]
return model_inputs
Phase 2: Model Training
📌 Step 4: Load Phi-3 with QLoRA (Efficient Fine-Tuning)
python Copy code
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
import torch
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16,
)
model = AutoModelForCausalLM.from_pretrained(
"microsoft/phi-3-mini-4k-instruct",
quantization_config=bnb_config,
device_map="auto",
trust_remote_code=True
)
📌 Step 5: Apply PEFT (LoRA)
python Copy code
from peft import LoraConfig, get_peft_model
peft_config = LoraConfig(
r=16,
lora_alpha=32,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM"
)
model = get_peft_model(model, peft_config)
model.print_trainable_parameters() # Check trainable params
📌 Step 6: Training Setup
python Copy code
from transformers import TrainingArguments, Trainer
training_args = TrainingArguments(
output_dir="./phi3-table-reasoning",
per_device_train_batch_size=4,
gradient_accumulation_steps=2,
learning_rate=2e-5,
num_train_epochs=3,
logging_steps=10,
save_strategy="epoch",
fp16=True,
optim="paged_adamw_8bit"
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset["train"],
eval_dataset=tokenized_dataset["test"],
tokenizer=tokenizer,
)
📌 Step 7: Start Training
python Copy code
trainer.train()
trainer.save_model("phi3-table-reasoning-finetuned")
Phase 3: Evaluation & Inference
📌 Step 8: Evaluate on Test Set
python Copy code
import numpy as np
from sklearn.metrics import accuracy_score, mean_squared_error
def compute_metrics(eval_preds):
logits, labels = eval_preds
predictions = np.argmax(logits, axis=-1)
return {"accuracy": accuracy_score(labels, predictions)}
📌 Step 9: Run Inference
python Copy code
from transformers import pipeline
pipe = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
device_map="auto"
)
table = "| Name | Age | Salary |\n|------|-----|--------|\n| Alice | 30 | 70k |"
question = "What is Alice's salary?"
input_text = f"Table: {table}\nQuestion: {question}\nAnswer:"
output = pipe(input_text, max_new_tokens=50, do_sample=False)
print(output[0]["generated_text"])
Phase 4: Optimization & Deployment
📌 Step 10: Quantize & Export
python Copy code
model.save_pretrained("./phi3-table-reasoning-quantized", save_quantized=True)
📌 Step 11: Deploy via FastAPI
python Copy code
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Query(BaseModel):
table: str
question: str
@app.post("/predict")
def predict(query: Query):
input_text = f"Table: {query.table}\nQuestion: {query.question}\nAnswer:"
output = pipe(input_text, max_new_tokens=50)
return {"answer": output[0]["generated_text"]}
Run with:
bash Copy code
uvicorn app:app --reload
📅 Timeline
Phase Tasks Time Estimate Setup Install deps, data prep 1 day Training Fine-tune with QLoRA 2-4 hours/epoch Evaluation Test metrics, debug 1 day Deployment Quantize, API, demo 1 day
🛠 Tools Used
Model : microsoft/phi-3-mini-4k-instruct
Quantization : bitsandbytes (4-bit)
Efficient FT : peft (LoRA)
Training : transformers.Trainer
Deployment : FastAPI / Gradio
🔥 Expected Output
A lightweight Phi-3 variant specialized in table reasoning.
Demo: Accepts tables + questions → returns answers.
Metrics: Accuracy (~90%+ for classification, low RMSE for regression).
Would you like a Colab notebook with this implementation? I can adapt it for your specific dataset!