Here's a detailed implementation plan for fine-tuning Phi-3 (a small but powerful language model by Microsoft) for table reasoning tasks like classification, regression, and question-answering over tabular data.
Objective
Fine-tune Phi-3-mini (or Phi-3-small) on a table reasoning dataset to:
Predict labels (classification) from tabular data.
Predict numerical values (regression) from tabular data.
Answer questions based on table content (QA).
Prerequisites
Hardware :
GPU : NVIDIA A100 / V100 / RTX 3090 (at least 16GB VRAM).
RAM : 32GB+ (64GB ideal for large datasets).
Storage : 1TB SSD (for datasets and checkpoints).
Software :
Python 3.10+
PyTorch 2.1+ (with CUDA support)
Hugging Face Transformers (pip install transformers datasets accelerate)
Pandas for data manipulation
Scikit-learn for evaluation metrics
Access to Phi-3 :
Ensure you have access to the Phi-3 model via Hugging Face Model Hub:
Model Names :
microsoft/Phi-3-mini-4k-instruct
microsoft/Phi-3-mini-128k-instruct (if longer contexts needed)
Accept terms on Hugging Face Phi-3 page .
Step 1: Environment Setup (15 mins)
bash Copy code
# Create a virtual environment
python -m venv phi3_finetune
source phi3_finetune/bin/activate # (On Windows: phi3_finetune\Scripts\activate)
# Install required libraries
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
pip install transformers datasets pandas scikit-learn accelerate
# Verify PyTorch GPU support
python -c "import torch; print(torch.cuda.is_available())" # Should return True
Step 2: Data Preparation (1–2 hours)
We'll use WikiTableQuestions for QA and TabFact for classification. You can substitute these with your custom dataset.
Dataset Structure :
Each sample should look like:
json Copy code
{
"table": "| Name | Age | Salary |\n| Alice | 30 | 70k |\n| Bob | 45 | 90k |",
"question": "What is Bob's salary?",
"answer": "90000" # For QA/Regression
"label": 1 # For Classification (e.g., True/False in TabFact)
}
Load & Preprocess Data :
python Copy code
import pandas as pd
from datasets import Dataset, DatasetDict
# Load data (example: WikiTableQuestions)
train_df = pd.read_json("WikiTableQuestions/train.json")
test_df = pd.read_json("WikiTableQuestions/test.json")
# Convert to Hugging Face Dataset
train_dataset = Dataset.from_pandas(train_df[["table", "question", "answer"]])
test_dataset = Dataset.from_pandas(test_df[["table", "question", "answer"]])
dataset = DatasetDict({"train": train_dataset, "test": test_dataset})
# Rename columns (if needed) and add "labels" for classification tasks
dataset = dataset.rename_column("answer", "labels")
Step 3: Tokenization & Prompt Formatting (30 mins)
Phi-3 uses a chat-inspired template . Format inputs like:
text Copy code
<|user|>Given this table: {table_text}\nQuestion: {question}<|end|>\n<|assistant|>{answer}<|end|>
Tokenization Script :
python Copy code
from transformers import AutoTokenizer
model_name = "microsoft/Phi-3-mini-4k-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_name)
def format_prompt(table, question, answer=None):
prompt = f"<|user|>Given this table:\n{table}\nQuestion: {question}<|end|>\n<|assistant|>"
if answer is not None:
prompt += f"{answer}<|end|>"
return prompt
def preprocess(examples):
inputs = [
format_prompt(t, q, a) for t, q, a in zip(examples["table"], examples["question"], examples["labels"])
]
model_inputs = tokenizer(inputs, truncation=True, max_length=2048, padding="max_length")
model_inputs["labels"] = tokenizer(
[str(a) for a in examples["labels"]], truncation=True, max_length=128, padding="max_length"
)["input_ids"]
return model_inputs
dataset = dataset.map(preprocess, batched=True, num_proc=8)
Step 4: Fine-Tuning Phi-3 (4–12 hours)
python Copy code
from transformers import AutoModelForCausalLM, TrainingArguments, Trainer
# Load Phi-3 model
model = AutoModelForCausalLM.from_pretrained(
model_name,
device_map="auto", # Uses GPU(s) automatically
torch_dtype=torch.bfloat16, # Saves VRAM
)
# Training Args
training_args = TrainingArguments(
output_dir="./phi3_table_reasoning",
num_train_epochs=3,
per_device_train_batch_size=4, # Reduce if OOM
per_device_eval_batch_size=8,
warmup_steps=100,
weight_decay=0.01,
logging_steps=50,
evaluation_strategy="epoch",
save_strategy="epoch",
learning_rate=5e-5,
bf16=True, # Faster training
gradient_accumulation_steps=2, # Simulate larger batch size
)
# Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=dataset["train"],
eval_dataset=dataset["test"],
tokenizer=tokenizer,
)
# Start Fine-Tuning
trainer.train()
Tips :
If OOM (Out of Memory) , reduce batch_size or use gradient_checkpointing=True.
Monitor loss in TensorBoard: tensorboard --logdir ./phi3_table_reasoning/runs
Step 5: Evaluation (30 mins)
python Copy code
# Evaluate on test set
eval_results = trainer.evaluate()
print(eval_results)
# Predict on sample data
sample = dataset["test"][0]
input_ids = tokenizer(sample["table"] + "\n" + sample["question"], return_tensors="pt").input_ids.to("cuda")
outputs = model.generate(input_ids, max_new_tokens=50)
predicted_answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
print("Predicted:", predicted_answer)
print("True Answer:", sample["labels"])
Metrics :
For QA : Token overlap (exact match, F1-score)
For Classification : Accuracy, F1-score
For Regression : MAE, R²
python Copy code
from sklearn.metrics import accuracy_score, f1_score, mean_absolute_error
def compute_metrics(pred):
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
acc = accuracy_score(labels, preds)
f1 = f1_score(labels, preds, average="weighted")
return {"accuracy": acc, "f1": f1}
Step 6: Optimize & Deploy (1–2 hours)
Quantization (Reduce Size from 2GB to ~500MB) :
python Copy code
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("./phi3_table_reasoning/checkpoint-final")
quantized_model = torch.quantization.quantize_dynamic(
model, {torch.nn.Linear}, dtype=torch.qint8
)
quantized_model.save_pretrained("./phi3_quantized")
Export to ONNX for Inference :
bash Copy code
python -m transformers.onnx --model=./phi3_quantized --feature causal-lm phi3_onnx/
Deploy with FastAPI :
python Copy code
from fastapi import FastAPI
from transformers import pipeline
app = FastAPI()
nlp_pipe = pipeline("text-generation", model="./phi3_quantized", device=0)
@app.post("/predict")
def predict(table: str, question: str):
prompt = f"<|user|>Given this table:\n{table}\nQuestion: {question}<|end|>\n<|assistant|>"
result = nlp_pipe(prompt, max_new_tokens=50)
return {"answer": result[0]["generated_text"].split("<|assistant|>")[-1].strip()}
Run: uvicorn app:app --host 0.0.0.0 --port 8000
Timeline
Task Time Estimate Environment Setup 15 mins Data Prep & Tokenization 2 hours Fine-Tuning Phi-3 4–12 hours Evaluation 30 mins Optimization & Deploy 1–2 hours Total ~10–18 hours
Cost Breakdown
Resource Cost (Approx.) A100 GPU (AWS) $3–5 / hour Colab Pro+ GPU $50 / month Hugging Face Hub Free (Phi-3 access) Total (12 hrs) $36–60 (A100)
Troubleshooting Tips
OOM : Reduce batch size or enable gradient_checkpointing.
Slow Training : Use bf16=True and gradient_accumulation.
Model Not Converging : Increase epochs or tweak LR (e.g., 1e-5).
Start with a small subset of data (e.g., 1,000 samples) to test the pipeline, then scale up! 🚀
Happy fine-tuning! 😊 Let me know if you need a Colab notebook starter !