Logo de Ai Llm Inference

Ai Llm Inference

Comunidade
vasilyu1983
ai-llm-inference

Padrões de inferência de LLMs para latência, processamento em lotes, cache, quantização, roteamento e infraestrutura de serving. Use para otimizar throughput, latência de cauda ou custo de serving.

Add to TypingMind

Visão geral

Publicado porvasilyu1983
RepositórioAI-Agents-public
Nome da habilidadeai-llm-inference
Estrelas
87
Forks
19
Arquivos incluídos
41
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Arquivos incluídos: 41

    Scripts, templates e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente para leitura e nunca são executados.

  • Código aberto

    Publicada por vasilyu1983 no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Ai Llm Inference no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/vasilyu1983/AI-Agents-public/tree/main/frameworks/shared-skills/skills/ai-llm-inference
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/vasilyu1983/AI-Agents-public.git /tmp/AI-Agents-public
mkdir -p .claude/skills
cp -r /tmp/AI-Agents-public/frameworks/shared-skills/skills/ai-llm-inference .claude/skills/ai-llm-inference
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Ai Llm Inference em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Ai Llm Inference automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Ai Llm Inference não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

LLM Inference Production Skill Hub

Operational guidance for choosing and tuning modern inference stacks. Focus on runtime fit, routing, output guarantees, adapter loading, multimodal serving, and measured performance under load.

Use current primary sources for volatile facts such as versions, hardware support, benchmarks, pricing, and release status.

ASCII Flow

text
serving workload
  |
  v
intake
  model + modality + context + QPS + latency SLO + hardware + output contract
  |
  v
serving design
  engine + router + batching + cache + quantization + structured outputs
  |
  v
benchmark
  TTFT + ITL + throughput + error rate + quality floor
  |
  v
production serving path
  capacity plan + rollout + monitoring + rollback thresholds

When to Use This Skill

Use this skill when the user asks for:

  • inference engine selection or stack comparison
  • latency, TTFT, ITL, or throughput optimization
  • cache-aware routing or control-plane design
  • quantization strategy by runtime and hardware
  • multi-GPU or multi-node serving
  • structured outputs or constrained decoding at serve time
  • multimodal or encoder-decoder serving patterns
  • LoRA or multi-adapter serving
  • cost reduction for self-hosted or API inference
  • benchmarking, profiling, or capacity planning
  • CPU or edge deployment with GGUF or llama.cpp, or on-device NPU (per-tensor scales, static shapes)

Scope Boundaries

Quick Reference

DecisionPrimary QuestionDefault Starting PointEscalate When
EngineWhich runtime should execute tokens?vLLM for general text servingNeed stronger KV reuse, multimodal split, or NVIDIA-specific kernels
RouterHow should requests be placed?Simple replica pool firstMultiple replicas, sticky prefixes, multi-LoRA, or mixed workloads
Output controlMust responses obey a schema?Use native structured outputsJSON validity or grammar constraints are part of the SLA
MultimodalIs there a separate encoder path?Keep colocated firstEncoder saturation differs from decode saturation
AdaptersWill many LoRAs or tenants share the base model?Use native multi-LoRA supportCold-load latency or adapter churn affects p95
QuantizationWhich precision is safe in this runtime?Runtime-native FP8 or weight-only pathHardware support or model quality is uncertain
DisaggregationShould prefill/encoder/decode be split?Only after colocated baselineQueueing interference or resource asymmetry is proven

Intake Checklist (Required)

Collect or infer these inputs before recommending changes:

  • model family, size, context length, tokenizer, modality, and adapter usage
  • request contract: streaming, tool use, reasoning mode, schema or grammar constraints
  • prompt and output length distribution, concurrency, QPS, and burst profile
  • prompt reuse patterns: prefix reuse, session reuse, retrieval reuse, LoRA reuse
  • current engine, version, router, autoscaler, and cache settings
  • hardware and topology: GPU SKU, VRAM, interconnect, node count, CPU and RAM
  • SLOs: TTFT, ITL, end-to-end latency, availability, and error budget
  • acceptance criteria: quality floor, JSON validity, long-context accuracy, rollback window

Workflow

  1. Collect the workload shape, runtime contract, hardware, and SLOs before recommending changes.
  2. Route prompt strategy, RAG design, or platform operations to the adjacent skill when inference tuning is not the primary problem.
  3. Choose the serving stack, routing policy, quantization path, and output-control strategy from the decision flow.
  4. Benchmark the baseline, change one lever at a time, and compare throughput, latency, and quality against the acceptance criteria.
  5. Verify volatile engine, hardware, and release facts with the navigation sources before final recommendations.

Decision Flow

text
Need to improve inference:
    |
    |- Is the workload text-only?
    |   |- No -> evaluate multimodal runtime support and encoder separation
    |   `- Yes -> continue
    |
    |- Is schema validity or constrained decoding part of the SLA?
    |   |- Yes -> prefer runtimes with native structured outputs
    |   `- No -> continue
    |
    |- Are there multiple replicas, tenants, or adapters?
    |   |- Yes -> design routing and placement explicitly
    |   `- No -> simple replica pool may be enough
    |
    |- Is there high prefix or session reuse?
    |   |- Yes -> prefer KV-aware routing and native prefix reuse
    |   `- No -> standard load balancing is acceptable
    |
    |- Are long prompts or mixed prompt lengths hurting p95?
    |   |- Yes -> test admission control first, then prefill or encoder disaggregation
    |   `- No -> keep colocated
    |
    |- Is this a MoE model (DeepSeek-V3/V4, Qwen3-MoE, Kimi-K2, Mixtral)?
    |   |- Yes -> assess EP degree, EPLB support, and all-to-all topology
    |   |         see references/moe-expert-parallelism.md
    |   `- No -> continue
    |
    `- Does the model fit latency and cost targets at current precision?
        |- Yes -> keep the simpler stack
        `- No -> walk the lever ladder in order, cheapest and least lossy first:
            1. roofline diagnosis: memory-bandwidth-bound or compute-bound?
               (the answer decides which of the rungs below can help at all)
            2. batching / admission control      (lossless)
            3. KV-cache quantization             (lossy -> eval gate)
            4. speculative decoding              (lossless only with rejection-sampling
                                                    verification; gate Medusa-style)
            5. weight quantization               (lossy -> eval gate)
            6. pruning / distillation            (lossy -> eval gate, retrain cost)
            Each lossy rung gets its own eval gate and rollback window.
            Change one rung at a time; stacking them hides the regression.

Stack Guidance

vLLM

  • Good default for OpenAI-compatible text serving, structured outputs, LoRA serving, and broad quantization support.
  • Strong fit for teams that want one runtime for text inference plus production router patterns.
  • Official docs now expose separate pages for structured outputs, disaggregated prefilling, disaggregated encoder serving, LoRA, and quantization. Treat those features independently instead of assuming one toggle solves all performance issues.
  • Important caveat: disaggregated prefilling is documented as experimental and does not improve throughput by itself; use it only after measuring real queueing or resource contention.

SGLang

  • Strong fit for chat, agents, repeated prefixes, multimodal serving, and adapter-heavy workloads.
  • Current docs emphasize RadixAttention, HiCache, PD and EPD disaggregation, Model Gateway, DP Router, structured outputs for reasoning models, and LoRA serving.
  • Prefer SGLang when prompt reuse, multimodal encoder pressure, or adapter churn is the main bottleneck rather than raw kernel speed alone.

TensorRT-LLM

  • Strong fit for NVIDIA-only deployments where explicit precision control, KV cache reuse, and low-latency GPU execution matter more than portability.
  • Current docs expose precision-specific guidance, KV cache reuse, disaggregated serving, and trtllm-serve.
  • Treat precision recommendations as runtime-scoped: TensorRT-LLM documents more INT8 and low-bit paths than a blanket hardware-only rule suggests.

Router And Control Plane

  • Separate token generation from request placement once you have more than a single box or a single replica.
  • Use routing-and-control-planes.md for cache-aware routing, sticky placement, multi-LoRA request steering, and control-plane selection.
  • vLLM-centric clusters: start with vLLM Router or the vLLM Production Stack.
  • Kubernetes and cache-aware scale-out: evaluate llm-d.
  • SGLang-centric clusters: use Model Gateway or DP Router patterns.
  • Multi-cloud or on-premise data-center environments: consider Dynamo (open-source Apache 2.0, supports AWS EKS, GKE, and NVIDIA hardware; confirmed 2026-05-17 via github.com/ai-dynamo/dynamo).

Quantization Rules

  • Choose quantization inside the runtime you will actually deploy, not from a generic hardware table.
  • On vLLM, prefer the runtime-native path first. Current docs expose FP8, INT4 W4A16, AWQ, GPTQ, and INT8 W8A8, with INT8 W8A8 explicitly excluding Blackwell (compute capability >= 10.0) in vLLM docs — FP8 is the documented Blackwell substitute.
  • On TensorRT-LLM, select from the precision modes the engine documents for that stack: FP8, INT8 SmoothQuant, weight-only INT4 or INT8, GPTQ or AWQ, and NVFP4 for supported Blackwell flows.
  • On SGLang, verify model-specific quantizer support in current docs before committing to FP4, FP8, AWQ, GPTQ, or quantized KV cache.
  • For CPU or edge deployment, use GGUF with llama.cpp and tune quant level, thread count, and n_gpu_layers explicitly.
  • On-device NPU is not CPU/edge: most NPU runtimes want INT8/INT4 with per-tensor scales and static shapes, not group-scaled formats — see the NPU row in references/quantization-patterns.md.
  • After any quantization change, re-run latency, long-context, and structured-output validation before rollout.

Expert Judgment: When Quantization Actually Hurts Quality

  • Quality risk is not evenly distributed across formats. Weight-only formats (AWQ, GPTQ, INT4 W4A16) rarely move task accuracy more than a point or two on general chat/instruct evals, but they degrade disproportionately on: long-context retrieval (needle-in-haystack style tasks), multi-step arithmetic and code, and low-resource languages — test those specifically, not just a generic eval average.
  • W8A8 and other activation-quantized paths carry outlier risk that weight-only paths do not: a small number of hidden-state channels can dominate the error budget (see SmoothQuant calibration in architecture-and-attention-serving.md §6). If the calibration set does not match production traffic, W8A8 can look fine on a benchmark and fail on production long-tail inputs — calibrate on production-representative samples, not generic corpora.
  • KV cache quantization (FP8/INT8 KV) is usually safer than weight quantization for quality, because it compresses an intermediate activation rather than model parameters — but it interacts with speculative decoding and long-context RoPE scaling in ways that are runtime-specific; validate the combination, not each piece alone.
  • Structured-output and tool-call validity are often the first thing to regress under aggressive quantization, before generic quality metrics move — treat schema-valid rate as a leading indicator, not an afterthought.
  • Stacking quantization changes (weight format + KV dtype + speculative decoding) in one rollout makes root-causing a regression nearly impossible. Change one lever, measure, then stack.
  • If quality regresses only on a narrow task class (e.g., code, non-English, long documents) rather than broadly, the fix is usually a mixed-precision or per-layer scheme, not a wholesale rollback to full precision — check whether the runtime supports keeping specific layers or the LM head at higher precision.

Expert Judgment: Batching vs Latency

  • Continuous batching raises throughput almost for free until the GPU crosses from memory-bandwidth-bound to compute-bound decode (see the roofline model in architecture-and-attention-serving.md §3). Below that crossover, adding concurrency barely changes per-token latency — above it, added concurrency directly inflates TTFT and inter-token latency because requests now queue for compute, not just memory bandwidth.
  • The practical tell: if p50 latency is flat while p95/p99 climb as load increases, the batch scheduler is admitting more concurrent sequences than the compute budget supports at the target latency SLO — cap max_num_seqs / concurrent-request limits rather than tuning kernels first.
  • Do not chase throughput by raising batch or concurrency caps without a latency budget attached — throughput-optimal and latency-optimal operating points are different points on the same curve, and the "best" batch size is an SLO decision, not a hardware-maximization decision.
  • Mixed short/long prompt traffic in one queue is the most common cause of p99 collapse that looks like a batching bug but is actually a scheduling/admission-control gap — bucket by prompt-length class or add chunked prefill before concluding the engine is misconfigured.
  • When a stakeholder asks for "lower latency and higher throughput" without a concurrency ceiling, push back: those two goals trade off past the compute-bound crossover, and the SLO (not the engine) has to decide where the line sits.

Expert Judgment: Capacity Planning Heuristics

  • Do not size GPUs from raw parameter count alone. Size from three numbers together: weight memory at the target precision, KV cache memory at the target max-context × max-concurrency, and headroom for activations and framework overhead (roughly 10-20% of the total, verify against your runtime's actual footprint) — KV cache, not weights, is usually the first thing that runs out at real concurrency and long context.
  • Treat "GPUs needed" as a queueing problem, not a peak-throughput division problem: use Little's Law and expected burst behavior (see queueing-theory-applied.md) to size for the tail, not the mean, or the fleet will meet average-load SLOs and fail every burst.
  • A colocated baseline sized correctly beats a disaggregated topology sized on guesswork — get capacity numbers from the simple deployment first, then decide whether splitting phases is what actually buys back headroom.
  • Reserve explicit capacity margin for cold-start and adapter-load events (autoscaling lag, LoRA cold loads, MoE weight loading) — steady-state utilization targets that ignore these events under-provision for real p99 behavior.

Operational Rules

Do

  • Measure TTFT, ITL, end-to-end latency, queueing delay, tokens per second, and schema-valid rate under realistic load.
  • Cap queue depth and concurrency at the API boundary.
  • Keep routing logic explicit once prefix reuse or adapter locality matters.
  • Treat multimodal encoder saturation separately from decode saturation.
  • Log request IDs, model ID, precision, cache hit data, and overload reason.

Avoid

  • Avoid universal claims about the "best" engine without a workload profile.
  • Avoid using stale benchmark ratios as architecture proof.
  • Avoid disaggregation before proving colocated interference.
  • Avoid switching precision without a rollback plan and eval set.
  • Avoid generic round-robin when prefix or adapter locality drives most of the cost.

Known Traps

  • Benchmarking with synthetic prompts that do not match production prefix reuse, output length, schema-validity requirements, or concurrency bursts.
  • Introducing prefill or encoder disaggregation before tightening queue limits, admission control, and placement policy on a colocated baseline.
  • Optimizing only tokens/sec while TTFT, structured-output validity, or long-context quality regresses.
  • Swapping engines or tokenizer stacks without validating compatibility for stop conditions, function/tool contracts, and schema-constrained decoding.
  • Treating quantization as a pure hardware choice instead of a runtime-specific capability with quality and feature caveats.

Common Anti-Patterns

  • Chasing headline benchmark deltas as if they transfer directly to a different workload shape.
  • Using round-robin routing on prefix-heavy or multi-LoRA workloads where locality determines most of the latency and cost.
  • Mixing many prompt-length classes in one queue with no admission-control policy, then blaming the runtime for p95 collapse.
  • Rolling out a new precision or kernel path without a schema-validity suite, long-context checks, and an explicit rollback window.

Accuracy Protocol (Required)

  • Treat benchmark ratios as workload-specific unless you have a current primary source and comparable conditions.
  • State runtime assumptions whenever recommending hardware or precision changes.
  • Mark experimental or beta features explicitly.
  • Prefer official docs and release notes over secondary blogs whenever both exist.

Navigation

Core References

Applied Foundations

  • Queueing Theory Applied - continuous batching, KV-cache sizing, admission control, disaggregation, multi-tenant isolation, and token-budget backpressure — grounded in foundations-queueing-theory primitives (Little's Law, M/M/c, Erlang-C, Kingman, P-K)
  • Reliability Theory Applied - SLO budget allocation across cascaded models, hedged requests, provider failover, cascading-failure prevention, KV-cache corruption rollback, and spec-decode rollback semantics — grounded in foundations-reliability-theory primitives (MTBF/MTTR, error budgets, FTA, redundancy math)

Templates

Scripts

ScriptPurpose
scripts/latency_benchmark.pyIssue N concurrent requests against an OpenAI-compatible /v1/chat/completions endpoint and report p50/p95/p99 latency and throughput. stdlib-only (urllib + threading).

Data

Trend Awareness Protocol

When the user asks for the latest, best, current, recommended, or still-relevant inference tooling:

  • use available browsing or web search
  • prefer official runtime docs, release notes, and vendor docs
  • verify feature status before recommending it
  • report dated assumptions and runtime-specific caveats

Check at least these source types before final recommendations:

  • engine docs for vLLM, SGLang, TensorRT-LLM, or llama.cpp
  • router or control-plane docs when request placement matters
  • vendor precision docs when hardware or quantization is involved
  • current pricing docs when cost decisions depend on managed APIs

Related Skills

Fact-Checking

  • Known bugs, regressions, framework/compiler/runtime footguns, and version-specific crash or workaround guidance must be verified against current primary web sources before being treated as current fact.
  • Verify current external facts, versions, pricing, and hardware support before final answers.
  • Prefer primary sources and include links for volatile recommendations.
  • If browsing is unavailable, label time-sensitive guidance as unverified.

Learnings Loop

Before applying this skill on a non-trivial task, read learnings.consolidated.md in this directory (and learnings.md if present).

After applying it, if you encountered a pattern worth remembering, a mistake worth preventing, or a domain fact that surprised you, append one dated bullet to learnings.md via agents-skills-feedback-loop/scripts/append_learning.py. Do not modify SKILL.md itself.

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Ai Llm Inference faz?

Padrões de inferência de LLMs para latência, processamento em lotes, cache, quantização, roteamento e infraestrutura de serving. Use para otimizar throughput, latência de cauda ou custo de serving.

Por que usar Ai Llm Inference no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Ai Llm Inference é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Ai Llm Inference no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/vasilyu1983/AI-Agents-public/tree/main/frameworks/shared-skills/skills/ai-llm-inference. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Ai Llm Inference?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Ai Llm Inference?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Ai Llm Inference com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Ai Llm Inference é gratuita?

Sim. A habilidade é publicada no GitHub por vasilyu1983 sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇