RU

runtime-skills

A technical guide for configuring and optimizing ML inference servers using PyTorch, Transformers, and FastAPI.

Install

mkdir -p .claude/skills/runtime-skills && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/6044" && unzip -o skill.zip -d .claude/skills/runtime-skills && rm skill.zip

Installs to .claude/skills/runtime-skills

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Universal Runtime best practices for PyTorch inference, Transformers models, and FastAPI serving. Covers device management, model loading, memory optimization, and performance tuning.
183 charsno explicit “when” trigger
Advanced

Key capabilities

  • Manage device-aware tensor operations for PyTorch
  • Implement double-checked locking for model loading
  • Handle TTL-based model caching and cleanup
  • Execute blocking operations using thread pools
  • Apply performance tuning for FastAPI serving

How it works

The runtime uses a centralized model cache with TTL, device-aware tensor management, and thread-safe loading patterns to serve ML models via FastAPI.

Inputs & outputs

You give it
Model ID and task type
You get back
Loaded model instance or inference result

When to use runtime-skills

  • Optimizing PyTorch memory usage
  • Setting up Transformers for inference
  • Reviewing FastAPI performance tuning
  • Managing device allocation for ML

About this skill

Universal Runtime Skills

Best practices and code review checklists for the Universal Runtime - LlamaFarm's local ML inference server.

Overview

The Universal Runtime provides OpenAI-compatible endpoints for HuggingFace models:

  • Text generation (Causal LMs: GPT, Llama, Mistral, Qwen)
  • Text embeddings (BERT, sentence-transformers, ModernBERT)
  • Classification, NER, and reranking
  • OCR and document understanding
  • Anomaly detection

Directory: runtimes/universal/ Python: 3.11+ Key Dependencies: PyTorch, Transformers, FastAPI, llama-cpp-python

Links to Shared Skills

This skill extends the shared Python practices. Always apply these first:

TopicFilePriority
Patternspython-skills/patterns.mdMedium
Asyncpython-skills/async.mdHigh
Typingpython-skills/typing.mdMedium
Testingpython-skills/testing.mdMedium
Errorspython-skills/error-handling.mdHigh
Securitypython-skills/security.mdCritical

Runtime-Specific Checklists

TopicFileKey Points
PyTorchpytorch.mdDevice management, dtype, memory cleanup
Transformerstransformers.mdModel loading, tokenization, inference
FastAPIfastapi.mdAPI design, streaming, lifespan
Performanceperformance.mdBatching, caching, optimizations

Architecture

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/

Key Patterns

1. Model Loading with Double-Checked Locking

_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. Device-Aware Tensor Operations

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-Based Model Caching

_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. Async Generation with Thread Pools

# 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)

Review Priority

When reviewing Universal Runtime code:

  1. Critical - Security

    • Path traversal prevention in file endpoints
    • Input sanitization for model IDs
  2. High - Memory & Device

    • Proper CUDA/MPS cache clearing on unload
    • torch.no_grad() for inference
    • Correct dtype for device
  3. Medium - Performance

    • Model caching patterns
    • Batch processing where applicable
    • Streaming implementation
  4. Low - Code Style

    • Consistent with patterns.md
    • Proper type hints

When not to use it

  • When the runtime environment is not Python 3.11+

Prerequisites

Python 3.11+PyTorchTransformersFastAPI

Limitations

  • Requires adherence to specific directory structure
  • Requires manual implementation of security and performance checklists

How it compares

It centralizes runtime best practices and device management patterns specifically for local ML inference, rather than relying on generic server implementations.

Compared to similar skills

runtime-skills side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
runtime-skills (this skill)17moNo flagsAdvanced
fastapi-async-patterns01moNo flagsAdvanced
fastapi-templates5202moNo flagsIntermediate
fastapi-pro794moNo flagsAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

fastapi-async-patterns

hydrosdesenvolvimento

Use for deep FastAPI concurrency, event-loop safety, async I/O, and performance patterns after a service structure already exists. Not a general FastAPI bootstrap skill; pair with fastapi-expert or fastapi-templates when needed.

00

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

5201,086

fastapi-pro

sickn33

Build high-performance async APIs with FastAPI, SQLAlchemy 2.0, and Pydantic V2. Master microservices, WebSockets, and modern Python async patterns. Use PROACTIVELY for FastAPI development, async optimization, or API architecture.

79181

python-pro

sickn33

Master Python 3.12+ with modern features, async programming, performance optimization, and production-ready practices. Expert in the latest Python ecosystem including uv, ruff, pydantic, and FastAPI. Use PROACTIVELY for Python development, optimization, or advanced Python patterns.

2358

python-configuration

wshobson

Python configuration management via environment variables and typed settings. Use when externalizing config, setting up pydantic-settings, managing secrets, or implementing environment-specific behavior.

542

fastapi-router-py

microsoft

Create FastAPI routers with CRUD operations, authentication dependencies, and proper response models. Use when building REST API endpoints, creating new routes, implementing CRUD operations, or adding authenticated endpoints in FastAPI applications.

525

Search skills

Search the agent skills registry