关于 runtime-skills
runtime-skills 是面向 LlamaFarm Universal Runtime(本地 ML 推理服务器)的开发与代码审查技能,提供模型处理、设备管理、性能和安全方面的专用清单与实践。
主要功能
- 01运行时代码审查清单
- 02模型加载与缓存模式
- 03设备感知张量处理指引
- 04异步生成实践
- 05安全与性能检查重点
适用场景
- 01审查 Universal Runtime 代码变更
- 02实现模型加载和缓存
- 03检查推理代码中的设备与安全问题
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ llama-farm/ llamafarm --skill runtime-skills安装后在 Claude Code 中输入/runtime-skills确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
fastapi.mdperformance.mdpytorch.mdtransformers.md详细介绍
Universal Runtime 技能
Universal Runtime 的最佳实践和代码审查清单——LlamaFarm 的本地 ML 推理服务。
概述
Universal Runtime 为 HuggingFace 模型提供与 OpenAI 兼容的端点:
- 文本生成(因果语言模型:GPT、Llama、Mistral、Qwen)
- 文本嵌入(BERT、sentence-transformers、ModernBERT)
- 分类、NER 和重排序
- OCR 和文档理解
- 异常检测
目录:runtimes/universal/
Python:3.11+
主要依赖项:PyTorch、Transformers、FastAPI、llama-cpp-python
共享技能链接
此技能扩展了共享 Python 实践。请始终先应用以下内容:
| 主题 | 文件 | 优先级 |
|---|---|---|
| 模式 | python-skills/patterns.md | 中 |
| 异步 | python-skills/async.md | 高 |
| 类型标注 | python-skills/typing.md | 中 |
| 测试 | python-skills/testing.md | 中 |
| 错误 | python-skills/error-handling.md | 高 |
| 安全 | python-skills/security.md | 严重 |
运行时专用清单
| 主题 | 文件 | 要点 |
|---|---|---|
| PyTorch | pytorch.md | 设备管理、dtype、内存清理 |
| Transformers | transformers.md | 模型加载、分词、推理 |
| FastAPI | fastapi.md | API 设计、流式传输、生命周期 |
| 性能 | performance.md | 批处理、缓存、优化 |
架构
runtimes/universal/
├── server.py # FastAPI app, model caching, endpoints
├── core/
│ └── logging.py # UniversalRuntimeLogger (structlog)
├── models/
│ ├── base.py # BaseModel ABC with device management
│ ├── language_model.py # Transformers text generation
│ ├── gguf_language_model.py # llama-cpp-python for GGUF
│ ├── encoder_model.py # Embeddings, classification, NER, reranking
│ └── ... # OCR, anomaly, document models
├── routers/
│ └── chat_completions/ # Chat completions with streaming
├── utils/
│ ├── device.py # Device detection (CUDA/MPS/CPU)
│ ├── model_cache.py # TTL-based model caching
│ ├── model_format.py # GGUF vs transformers detection
│ └── context_calculator.py # GGUF context size computation
└── tests/
关键模式
1. 使用双重检查锁定加载模型
_model_load_lock = asyncio.Lock()
async def load_encoder(model_id: str, task: str = "embedding"):
cache_key = f"encoder:{task}:{model_id}"
if cache_key not in _models:
async with _model_load_lock:
# Double-check after acquiring lock
if cache_key not in _models:
model = EncoderModel(model_id, device, task=task)
await model.load()
_models[cache_key] = model
return _models.get(cache_key)
2. 设备感知的张量操作
class BaseModel(ABC):
def get_dtype(self, force_float32: bool = False):
if force_float32:
return torch.float32
if self.device in ("cuda", "mps"):
return torch.float16
return torch.float32
def to_device(self, tensor: torch.Tensor, dtype=None):
# Don't change dtype for integer tensors
if tensor.dtype in (torch.int32, torch.int64, torch.long):
return tensor.to(device=self.device)
dtype = dtype or self.get_dtype()
return tensor.to(device=self.device, dtype=dtype)
3. 基于 TTL 的模型缓存
_models: ModelCache[BaseModel] = ModelCache(ttl=300) # 5 min TTL
async def _cleanup_idle_models():
while True:
await asyncio.sleep(CLEANUP_CHECK_INTERVAL)
for cache_key, model in _models.pop_expired():
await model.unload()
4. 使用线程池进行异步生成
# GGUF models use blocking llama-cpp, run in executor
self._executor = ThreadPoolExecutor(max_workers=1)
async def generate(self, messages, max_tokens=512, ...):
loop = asyncio.get_running_loop()
return await loop.run_in_executor(self._executor, self._generate_sync)
审查优先级
审查 Universal Runtime 代码时:
-
严重 - 安全
- 防止文件端点中的路径遍历
- 对模型 ID 进行输入清理
-
高 - 内存与设备
- 卸载时正确清理 CUDA/MPS 缓存
- 推理时使用 torch.no_grad()
- 为设备选择正确的 dtype
-
中 - 性能
- 模型缓存模式
- 在适用时进行批处理
- 流式传输实现
-
低 - 代码风格
- 与 patterns.md 保持一致
- 使用恰当的类型提示
评论
支持 Markdown