dspy-finetune-bootstrap
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "dspy-finetune-bootstrap":https://skillpi.com/zh/skills/deepskill-9b88dfda243d1a4df4885dffc9f592030ea8c393cc5104d19a23540bbc754b4d。安装前核对上游来源和版本:https://github.com/OmidZamani/dspy-skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
用于 BootstrapFinetune、DSPy 模型微调、师生蒸馏、权重优化以及低成本部署。
介绍来源: third_party · OmidZamani · 1.0.0 参考来源
SkillPi 解读
- 能完成的任务
- 翻译待完成,请参阅来源文档。
- 适合谁
- 翻译待完成,请参阅来源文档。
- 输入和输出
- 翻译待完成,请参阅来源文档。
- 软件、账号及付费要求
- 来源文档未说明。
- 限制与区别
- 翻译待完成,请参阅来源文档。
- 实测状态
- 未测试
文件浏览
Frontmatter
name: dspy-finetune-bootstrap
version: "1.0.0"
dspy-compatibility: "3.2.1"
tags: ["optimizer", "production"]
requires-extras: []
description: Use for BootstrapFinetune, fine-tuning DSPy models, teacher-student distillation, weight optimization, and lower-cost deployment.
allowed-tools:
- Read
- Write
- Glob
- GrepDSPy BootstrapFinetune Optimizer
Goal
Distill a DSPy program into fine-tuned model weights for efficient production deployment.
When to Use
- You have a working DSPy program with a large model
- Need to reduce inference costs
- Want faster responses (smaller model)
- Deploying to resource-constrained environments
Inputs
| Input | Type | Description |
|---|---|---|
program |
dspy.Module |
Teacher program to distill |
trainset |
list[dspy.Example] |
Training examples |
metric |
callable |
Validation metric (optional) |
train_kwargs |
dict |
Training hyperparameters |
Outputs
| Output | Type | Description |
|---|---|---|
finetuned_program |
dspy.Module |
Program with fine-tuned weights |
model_path |
str |
Path to saved model |
Workflow
Phase 1: Prepare Teacher Program
import dspy
# Configure with strong teacher model
dspy.configure(lm=dspy.LM("openai/gpt-4o"))
class TeacherQA(dspy.Module):
def __init__(self):
self.cot = dspy.ChainOfThought("question -> answer")
def forward(self, question):
return self.cot(question=question)
Phase 2: Configure Fine-Tuning
Assign the LM directly to predictors before fine-tuning:
import dspy
from dspy.teleprompt import BootstrapFinetune
optimizer = BootstrapFinetune(
metric=lambda gold, pred, trace=None: gold.answer.lower() in pred.answer.lower(),
train_kwargs={
'learning_rate': 5e-5,
'num_train_epochs': 3,
'per_device_train_batch_size': 4,
'warmup_ratio': 0.1
}
)
Phase 3: Fine-tune Student Model
teacher = TeacherQA()
teacher.set_lm(dspy.settings.lm)
finetuned = optimizer.compile(teacher, trainset=trainset)
Phase 4: Deploy
# Save the fine-tuned model (saves state-only by default)
finetuned.save("finetuned_qa_model.json")
# Load and use (must recreate architecture first)
loaded = TeacherQA()
loaded.load("finetuned_qa_model.json")
result = loaded(question="What is machine learning?")
Production Example
import dspy
from dspy.teleprompt import BootstrapFinetune
from dspy.evaluate import Evaluate
import logging
import os
logger = logging.getLogger(__name__)
class ClassificationSignature(dspy.Signature):
"""Classify text into categories."""
text: str = dspy.InputField()
label: str = dspy.OutputField(desc="Category: positive, negative, neutral")
class TextClassifier(dspy.Module):
def __init__(self):
self.classify = dspy.Predict(ClassificationSignature)
def forward(self, text):
return self.classify(text=text)
def classification_metric(gold, pred, trace=None):
"""Exact label match."""
gold_label = gold.label.lower().strip()
pred_label = pred.label.lower().strip() if pred.label else ""
return gold_label == pred_label
def finetune_classifier(trainset, devset, output_dir="./finetuned_model"):
"""Full fine-tuning pipeline."""
# Configure teacher (strong model)
dspy.configure(lm=dspy.LM("openai/gpt-4o"))
teacher = TextClassifier()
teacher.set_lm(dspy.settings.lm)
# Evaluate teacher
evaluator = Evaluate(devset=devset, metric=classification_metric, num_threads=8)
teacher_score = evaluator(teacher)
logger.info(f"Teacher score: {teacher_score:.2%}")
# Fine-tune (train_kwargs passed to constructor)
optimizer = BootstrapFinetune(
metric=classification_metric,
train_kwargs={
'learning_rate': 2e-5,
'num_train_epochs': 3,
'per_device_train_batch_size': 8,
'gradient_accumulation_steps': 2,
'warmup_ratio': 0.1,
'weight_decay': 0.01,
'logging_steps': 10,
'save_strategy': 'epoch',
'output_dir': output_dir
}
)
finetuned = optimizer.compile(
teacher,
trainset=trainset
)
# Evaluate fine-tuned model
student_score = evaluator(finetuned)
logger.info(f"Student score: {student_score:.2%}")
# Save (state-only as JSON)
finetuned.save(os.path.join(output_dir, "final_model.json"))
return {
"teacher_score": teacher_score,
"student_score": student_score,
"model_path": os.path.join(output_dir, "final_model.json")
}
# For RAG fine-tuning
class RAGClassifier(dspy.Module):
"""RAG pipeline that can be fine-tuned."""
def __init__(self, num_passages=3):
self.retrieve = dspy.Retrieve(k=num_passages)
self.classify = dspy.ChainOfThought("context, text -> label")
def forward(self, text):
context = self.retrieve(text).passages
return self.classify(context=context, text=text)
def finetune_rag_classifier(trainset, devset):
"""Fine-tune a RAG-based classifier."""
# Configure retriever and LM
colbert = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.configure(
lm=dspy.LM("openai/gpt-4o"),
rm=colbert
)
rag = RAGClassifier()
rag.set_lm(dspy.settings.lm)
# Fine-tune (train_kwargs in constructor)
optimizer = BootstrapFinetune(
metric=classification_metric,
train_kwargs={
'learning_rate': 1e-5,
'num_train_epochs': 5
}
)
finetuned = optimizer.compile(
rag,
trainset=trainset
)
return finetuned
Training Arguments Reference
| Argument | Description | Typical Value |
|---|---|---|
learning_rate |
Learning rate | 1e-5 to 5e-5 |
num_train_epochs |
Training epochs | 3-5 |
per_device_train_batch_size |
Batch size | 4-16 |
gradient_accumulation_steps |
Gradient accumulation | 2-8 |
warmup_ratio |
Warmup proportion | 0.1 |
weight_decay |
L2 regularization | 0.01 |
max_grad_norm |
Gradient clipping | 1.0 |
Best Practices
- Strong teacher - Use GPT-4 or Claude as teacher
- Quality data - Teacher traces are only as good as training examples
- Validate improvement - Compare student to teacher on held-out set
- Start with more epochs - Fine-tuning often needs 3-5 epochs
- Monitor overfitting - Track validation loss during training
Limitations
- Requires a provider and model that support fine-tuning
- Training requires GPU resources
- Student may not match teacher quality on all inputs
- Fine-tuning takes hours/days depending on data size
- Model size reduction may cause capability loss
Official Documentation
- DSPy Documentation: https://dspy.ai/
- DSPy GitHub: https://github.com/stanfordnlp/dspy
- BootstrapFinetune API: https://dspy.ai/api/optimizers/BootstrapFinetune/
- Fine-tuning Guide: https://dspy.ai/tutorials/classification_finetuning/
当前收录版本
1.0.0
安全与评测信息
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- 提供 DSPy 模型微调、师生蒸馏、权重优化等生产级功能
- 解决推理成本、响应速度、资源约束等明确痛点
- 面向实际部署场景,具有高实用价值
亮点
- description 完整且精准,覆盖 BootstrapFinetune、微调、蒸馏、优化、部署等核心功能
- 边界清晰,无歧义或重叠风险
亮点
- Phase 划分清晰(Prepare/Configure/Fine-tune/Deploy)
- 包含端到端生产示例和完整 frontmatter
- 单文件长度适中,结构规范
亮点
- 工具来源明确(dspy、BootstrapFinetune)
- 参数设置合理,覆盖主要异常处理
- save/load 机制明确,支持生产部署
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
-
保存或修改文件
先确认输出目录和同名文件是否会被覆盖;重要文件保留备份,优先写入新的输出目录。
主文档提及 · 第 93, 170 行
文档引用的域名或地址
这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。
- 20.102.90.50
- dspy.ai
- github.com
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
来源文档未说明。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。