mcpField
M
ml-model-integration

ml-model-integration

github.com/itallstartedwithaidea开发4475 次安装28 周前更新
代码仓库

关于 ml-model-integration

ml-model-integration 是一套用于从 HuggingFace Hub 查找、评估和部署机器学习模型的 Agent Skills 工作流。它面向构建推理或微调流程的开发者,涵盖从模型选择到部署的指导。

主要功能

  1. 01按任务搜索模型
  2. 02按许可证和模型大小筛选
  3. 03使用基准数据评估候选模型
  4. 04配置本地或 API 推理
  5. 05使用 LoRA 微调

适用场景

  1. 01为指定机器学习任务选择模型
  2. 02使用自定义数据评估候选模型
  3. 03部署推理流程
  4. 04将预训练模型适配领域数据

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/itallstartedwithaidea/agent-skills --skill ml-model-integration

安装后在 Claude Code 中输入/ml-model-integration确认已加载。

详细介绍

ML 模型集成

Agent Skills™ 的一部分,由 googleadsagent.ai™ 提供

描述

ML 模型集成提供了从 HuggingFace Hub 发现、评估和部署机器学习模型的工作流。Agent 会按任务类型搜索模型注册表,在基准数据集上评估候选模型,为本地或基于 API 的执行配置推理流水线,并为领域适配编排微调工作流。

HuggingFace Hub 托管着 500,000 多个模型,涵盖数百种任务类型:文本生成、图像分类、目标检测、语音识别、翻译、摘要等。要驾驭这片领域,需要了解模型架构、许可证兼容性、硬件要求和基准性能。这项技能将这些知识编码其中,帮助 Agent 根据任务和成本选择合适的模型。

这项技能覆盖完整的模型生命周期:发现(按任务搜索,按许可证和规模筛选)、评估(在测试数据上运行推理,测量延迟和质量)、部署(本地 Transformers 流水线、HuggingFace Inference API,或使用 TGI/vLLM 自托管),以及微调(使用 LoRA 适配器,以最少的训练数据进行领域专属定制)。

适用场景

  • 为特定 ML 任务(分类、生成、检测)选择模型
  • 在本地或通过 API 设置推理流水线
  • 使用领域专属数据微调预训练模型
  • 根据自定义基准评估模型质量
  • 通过优化服务将模型部署到生产环境
  • 用户询问 HuggingFace、Transformers 或模型选择相关问题

工作原理

graph TD
    A[Task Definition] --> B[Search HuggingFace Hub]
    B --> C[Filter: License, Size, Downloads]
    C --> D[Shortlist Top-3 Candidates]
    D --> E[Evaluate on Benchmark Data]
    E --> F{Quality Sufficient?}
    F -->|Yes| G[Deploy as Inference Pipeline]
    F -->|No| H[Fine-tune with LoRA]
    H --> I[Evaluate Fine-tuned Model]
    I --> G
    G --> J{Deployment Target}
    J -->|Local| K[Transformers Pipeline]
    J -->|API| L[HuggingFace Inference API]
    J -->|Self-Hosted| M[TGI / vLLM Server]

工作流从定义任务开始,而不是选择模型。Agent 会搜索符合任务要求的模型,评估候选模型,只有在现成模型的性能不足时才会进行微调。

实现

from transformers import pipeline, AutoModelForSequenceClassification, AutoTokenizer
from huggingface_hub import HfApi, ModelFilter
from peft import LoraConfig, get_peft_model, TaskType
import torch

def discover_models(task: str, min_downloads: int = 1000, license: str = "apache-2.0") -> list[dict]:
    api = HfApi()
    models = api.list_models(
        filter=ModelFilter(task=task, library="transformers"),
        sort="downloads",
        direction=-1,
        limit=20,
    )
    results = []
    for m in models:
        if m.downloads >= min_downloads:
            results.append({
                "id": m.modelId,
                "downloads": m.downloads,
                "likes": m.likes,
                "tags": m.tags,
                "pipeline_tag": m.pipeline_tag,
            })
    return results[:10]

def setup_inference(model_id: str, task: str, device: str = "auto") -> pipeline:
    return pipeline(
        task=task,
        model=model_id,
        device_map=device,
        torch_dtype=torch.float16,
    )

def evaluate_model(pipe, test_data: list[dict], label_key: str = "label") -> dict:
    correct = 0
    total = len(test_data)
    latencies = []

    for item in test_data:
        import time
        start = time.time()
        pred = pipe(item["text"])
        latencies.append((time.time() - start) * 1000)

        if pred[0]["label"] == item[label_key]:
            correct += 1

    return {
        "accuracy": correct / total,
        "avg_latency_ms": sum(latencies) / len(latencies),
        "p95_latency_ms": sorted(latencies)[int(0.95 * len(latencies))],
        "total_samples": total,
    }

def finetune_lora(
    base_model: str,
    train_dataset,
    output_dir: str,
    num_epochs: int = 3,
    lora_rank: int = 16,
):
    model = AutoModelForSequenceClassification.from_pretrained(base_model)
    tokenizer = AutoTokenizer.from_pretrained(base_model)

    lora_config = LoraConfig(
        task_type=TaskType.SEQ_CLS,
        r=lora_rank,
        lora_alpha=32,
        lora_dropout=0.1,
        target_modules=["q_proj", "v_proj"],
    )
    model = get_peft_model(model, lora_config)
    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
    total = sum(p.numel() for p in model.parameters())
    print(f"Trainable: {trainable:,} / {total:,} ({100 * trainable / total:.1f}%)")

    from transformers import Trainer, TrainingArguments
    args = TrainingArguments(
        output_dir=output_dir,
        num_train_epochs=num_epochs,
        per_device_train_batch_size=8,
        learning_rate=2e-4,
        save_strategy="epoch",
        logging_steps=50,
        fp16=True,
    )
    trainer = Trainer(model=model, args=args, train_dataset=train_dataset, tokenizer=tokenizer)
    trainer.train()
    model.save_pretrained(output_dir)

最佳实践

  • 始终先定义任务,再搜索模型——不要先选一个模型再为它寻找任务
  • 在评估性能前,按许可证兼容性(Apache-2.0、MIT)筛选
  • 使用自己的数据进行评估,而不只是参考已发布的基准——领域很重要
  • 使用 LoRA 进行微调,与完整微调相比可降低 90% 的训练成本
  • 对模型进行量化(GPTQ、AWQ、bitsandbytes),以便在消费级硬件上进行推理
  • 使用提交哈希固定模型修订版本,确保推理可复现

平台兼容性

平台支持情况备注
Cursor完全支持Python + Transformers
VS Code完全支持Jupyter + ML 工具
Windsurf完全支持支持 ML 工作流
Claude Code完全支持生成流水线脚本
Cline完全支持模型集成
aider部分支持仅代码生成

相关技能

关键词

huggingface transformers model-selection inference-pipeline fine-tuning lora model-evaluation ml-deployment


© 2026 googleadsagent.ai™ | Agent Skills™ | MIT 许可证

评论

支持 Markdown