71 / LOCAL LLM · SELF-HOSTED MODELS / MODEL INFRASTRUCTURE
71 / SPECIALIZED / PRIVATE INFERENCE · LOCAL DEPLOYMENT · HARDWARE · OPERATIONS

LOCAL LLM
/ SELF-HOSTED MODELS.

Local LLM / Self-Hosted Models — стратегия, при которой организация сама владеет inference deployment: model artifacts, runtime, hardware, network boundary, обновлениями, capacity и эксплуатацией. Это может быть ноутбук с одной моделью, workstation с GPU, private server, on-prem cluster или полностью air-gapped среда.

Главный принцип: self-hosting — не «бесплатная альтернатива API». Вы меняете provider bill на hardware + energy + operations + availability + security + model lifecycle + benchmarking. Он оправдан, когда контроль над данными, offline requirements, предсказуемая загрузка, latency, кастомные модели или unit economics перевешивают operational burden.
00. ARCHITECTURAL STATUS

SELF-HOSTING — НЕ DEFAULT, А ОСОЗНАННЫЙ DEPLOYMENT CHOICE

Hosted API often wins for fast start, bursty low volume and strongest frontier models. Self-hosting becomes attractive where data cannot leave a boundary, workload is large/stable, offline operation matters, latency to cloud is unacceptable, provider dependence is undesirable or the organization needs its own adapted model artifact.
TYPESPECIALIZEDDeployment / ownership strategy.
DEFAULTCONDITIONALDo not self-host automatically.
ENABLE WHENPRIVACY / CONTROL / ECONOMICS / OFFLINEOr custom model requirement.
SEPARATE COMPONENTYESPrivate model deployment/pool.
LIVES INMODEL ROUTER + MODEL INFRASTRUCTURELocal targets register into R09.
COMPLEXITYLOW → VERY HIGHDesktop → production GPU cluster.
IMPLEMENT: ONLY WITH A CLEAR DRIVER
Минимум 80% ценности: one approved model artifact, exact license/revision/checksum, one controlled runtime, private endpoint behind №65 Gateway, realistic hardware benchmark, VRAM/RAM capacity profile, bounded serving limits, local artifact cache, update/rollback procedure, logs without sensitive payloads, network isolation, health monitoring and cloud fallback only when data policy explicitly permits it.
01A. ARCHITECTURE BOUNDARIES & OPERATIONS

EXPLICIT SYSTEM CONTRACT

A. BOUNDARY WITH NEIGHBORS

№70 Model Serving & Inference владеет batching/KV/scheduler/throughput/latency mechanics; №71 владеет deployment choice, hardware topology, artifact ownership, private network, operations and economics. №65 Model Gateway & Routing выбирает local/cloud target и скрывает endpoint details from application. №72 Quantization меняет precision/representation of model weights; №71 decides which artifact to deploy but does not own quantization algorithms. №39 Fine-Tuning/LoRA/Distillation creates adapted weights/adapters; №71 hosts approved resulting artifacts. №76 Governance sets data residency/privacy rules; №71 is one way to satisfy them, not governance itself.

B. PREREQUISITES / CROSS-REFERENCES

Prerequisites: №39 Fine-Tuning/LoRA/Distillation, №46 Observability, №51 Permissions & Secrets, №63 Resilience, №64 Limits/Budgets, №65 Model Gateway, №70 Model Serving. Forward references: №72 Quantization, №73 Multimodal AI, №76 Data Governance, №77 Production AI Architecture.

C. PLANE PLACEMENT

REQUEST-TIME: local inference target selected by №65; №70 executes. CONTROL PLANE: approved models, licenses, hardware topology, deployment configs, network/data policy, update channel. DATA PLANE: inference traffic, model weights in memory, local KV/cache and runtime telemetry. OFFLINE: artifact acquisition, verification, benchmark, rollout, capacity planning, patching, license/security review and disaster recovery testing.

D. FAILURE & OPERATIONS CONTRACT

Success: approved model revision is served within declared SLO/capacity/privacy boundary. Retryable: replica/runtime restart, transient device/runtime fault, private endpoint overload. Permanent: model artifact incompatible with hardware/runtime, insufficient memory, invalid license/policy, corrupted artifact. Persist: model/tokenizer revision, artifact hash, license, deployment config, hardware class, runtime version, benchmark profile, rollout status. Security: model artifacts and serving endpoints are trusted infrastructure assets, not arbitrary files/URLs chosen by model/user.

E. WHAT THIS TOPIC DOES NOT OWN

№71 не владеет inference scheduling internals, model routing policy generally, quantization methods, fine-tuning, prompt architecture or data governance. Она владеет THE DECISION, TOPOLOGY AND OPERATIONS OF RUNNING MODEL DEPLOYMENTS UNDER YOUR OWN INFRASTRUCTURE CONTROL.

01. WHEN SELF-HOSTING MAKES SENSE

ЕСТЬ ШЕСТЬ СИЛЬНЫХ DRIVER-ОВ

PRIVACY

Data boundary

Sensitive prompts/documents must remain inside organization-controlled infrastructure.

RESIDENCY

Location control

Inference must occur in a specific country/region/on-prem environment.

OFFLINE

No internet dependency

Air-gapped, field, industrial, secure or intermittently connected environments.

ECONOMICS

High stable utilization

Predictable sustained volume may amortize hardware better than per-token API spend.

LATENCY

Locality

Local inference can remove WAN/provider round-trip when model/hardware are sufficient.

CUSTOM MODEL

Own artifact

Fine-tuned/private weights unavailable as managed provider endpoint.

Самый слабый аргумент: «хочется не зависеть от API». Vendor independence useful, but operating models yourself creates a different dependency stack: hardware, drivers, runtime, model artifact supply chain.
02. WHEN HOSTED API IS BETTER

НЕ ПРИНОСИТЬ DATA CENTER PROBLEMS В ПРОЕКТ, КОТОРОМУ НУЖНЫ 20 REQUESTS В ДЕНЬ

LOW VOLUME

Pay per use

Idle self-hosted accelerator still costs capex/opex.

BURSTY

Elastic provider capacity

Cloud provider may absorb unpredictable peaks better than your fixed hardware.

BEST MODEL REQUIRED

Frontier capability

Some strongest models may only exist as hosted services.

SMALL TEAM

Ops capacity

No one to own driver/runtime patches, failures, monitoring, replacement hardware and upgrades.

Hybrid architecture often wins: local model handles privacy/simple/high-volume work; hosted strong model is an explicit policy-approved escalation target.
03. DECISION MATRIX

LOCAL VS HOSTED VS HYBRID

FACTOR
HOSTED API
LOCAL / SELF-HOSTED
HYBRID
RISK
MEASURE
Privacy
provider-dependent
strong control
policy-routed
data leakage
data classes eligible
Low volume
good
idle hardware
good
TCO waste
utilization
High stable volume
usage bill grows
can amortize
optimize tiers
capacity miss
cost/success
Frontier quality
often strongest
artifact-dependent
escalate
quality gap
eval pass rate
Ops burden
low
high
medium
skills/on-call
MTTR/incidents
04. DEPLOYMENT TOPOLOGIES

SELF-HOSTED — ЭТО НЕ ТОЛЬКО «GPU-СЕРВЕР»

DESKTOP / LAPTOP

Personal local AI

Single user, development, offline assistant, experimentation. Operational HA usually not required.

WORKSTATION

Team/private node

One powerful machine with one/multiple accelerators; good for small team/private workload.

PRIVATE SERVER

Central endpoint

Rack/on-prem/private cloud node behind internal gateway; easier shared access and monitoring.

CLUSTER

Production scale

Multiple serving nodes/replicas, model pools, autoscaling, orchestration, dedicated observability.

EDGE

Near device

Factory/vehicle/branch/device deployment with tight power/memory and connectivity limits.

AIR-GAPPED

Disconnected secure zone

Artifacts, patches and evaluation data enter through controlled transfer process.

PRIVATE CLOUD

Owned tenant boundary

Dedicated infrastructure under organization control; still remote, but policy/ops differ from public API.

HYBRID

Local + hosted fleet

№65 chooses among local/private/cloud targets under policy and quality constraints.

05. HARDWARE FIRST PRINCIPLES

MODEL FIT И PERFORMANCE ЗАВИСЯТ НЕ ТОЛЬКО О «КОЛИЧЕСТВЕ GPU»

VRAM

Weights + KV + runtime

Primary accelerator memory capacity for model artifact and active requests.

MEMORY BANDWIDTH

Decode critical

Autoregressive decode can be strongly memory-bandwidth-sensitive.

INTERCONNECT

Multi-device cost

Cross-GPU/node communication can dominate distributed inference.

SYSTEM RAM

Load/offload/cache

Used for model loading, CPU offload, preprocessing, artifact cache and OS/runtime.

STORAGE

Model artifact locality

Large weight files affect deployment/warm-start time and disk requirements.

POWER

Watts are capacity

Power delivery, UPS and circuit limits matter for sustained accelerator load.

THERMALS

Sustained performance

Cooling determines whether benchmark speed can be maintained over hours.

CPU

Support path

Tokenization, preprocessing, networking and some inference/offload workloads use CPU resources.

A workstation that can run a 5-minute benchmark may throttle, OOM or become noisy/unreliable under 24/7 multi-user load. Production sizing must use sustained tests.
06. VRAM / RAM MODEL

«MODEL FILE FITS» НЕ ОЗНАЧАЕТ «PRODUCTION WORKLOAD FITS»

DEVICE MEMORY BUDGET

model weights
+ runtime workspace
+ KV cache for active requests
+ temporary tensors
+ fragmentation/headroom
= required VRAM

SYSTEM MEMORY BUDGET

OS + serving runtime
+ tokenizer / preprocessing
+ model loading buffers
+ CPU-offloaded layers / KV if used
+ artifact cache
+ logs / side processes
= required RAM

IF using CPU offload:
  model may "fit"
  but token latency can increase sharply
  because data moves across CPU/GPU boundary.

FIT IS BINARY.
USABLE PERFORMANCE IS NOT.
Capacity test should include realistic context lengths and concurrency; otherwise KV cache pressure remains invisible.
07. CPU-ONLY / CPU-OFFLOAD

ВОЗМОЖНО, НО НУЖНО ЧЕСТНО ИЗМЕРИТЬ LATENCY

CPU-ONLY

Offline / small model

Useful where GPU unavailable, throughput requirement low or edge deployment values simplicity.

PARTIAL OFFLOAD

Stretch memory

Some layers/KV can live in system RAM, allowing larger models than VRAM alone.

TRADE-OFF

Transfer latency

PCIe/system-memory movement can make interactive decode much slower.

«Запускается» — недостаточный acceptance criterion. Measure TTFT/TPOT under expected context/output lengths.
08. MODEL ARTIFACT CONTRACT

WEIGHTS — ЭТО VERSIONED SOFTWARE SUPPLY-CHAIN ASSET

{
  "model_ref": "model://local/model-x",
  "publisher": "...",
  "family": "model-x",
  "revision": "commit-or-release-id",
  "weights_sha256": "...",
  "tokenizer_sha256": "...",
  "format": "...",
  "precision": "BF16",
  "license": {
    "id": "...",
    "approved": true,
    "review_ref": "legal://..."
  },
  "source_uri": "approved-registry://...",
  "acquired_at": "...",
  "runtime_compatibility": ["runtime-profile-v3"],
  "status": "APPROVED"
}
DO NOT DEPLOY BY MODEL NAME

Pin exact artifact

  • publisher/source;
  • exact revision;
  • weights checksum;
  • tokenizer checksum;
  • license/version;
  • precision/format;
  • runtime compatibility;
  • security review state;
  • evaluation record.
09. MODEL LICENSE

«OPEN WEIGHTS» НЕ ОЗНАЧАЕТ «БЕЗ ОГРАНИЧЕНИЙ»

COMMERCIAL USE

Allowed?

Check exact license terms for organization/product use.

REDISTRIBUTION

Can artifact be shipped?

Important for edge/on-prem customer deployments.

DERIVATIVES

Fine-tuned weights

License may impose conditions on modified models/adapters.

USE RESTRICTIONS

Policy clauses

Some licenses contain acceptable-use or field-of-use conditions.

License is part of deployment eligibility in model registry. A technically excellent model can be operationally ineligible.
10. SUPPLY-CHAIN SECURITY

MODEL PACKAGE МОЖЕТ БЫТЬ НЕ ТОЛЬКО DATA, НО И EXECUTABLE RISK

UNTRUSTED SOURCE

Artifact poisoning

Do not load arbitrary model repositories/files directly into production runtime.

CHECKSUM

Integrity

Verify approved artifact hash before deployment.

NO REMOTE CODE BY DEFAULT

Runtime containment

Avoid model packages requiring arbitrary remote/custom code unless reviewed and isolated.

SCAN / REVIEW

Artifact pipeline

Inspect package format, metadata, dependencies and runtime extensions before approval.

Model artifact ingestion should resemble software artifact management more than «download file and run it».
11. ARTIFACT DISTRIBUTION

НЕ СКАЧИВАТЬ 100-GB WEIGHTS ИЗ INTERNET НА КАЖДОМ RESTART

APPROVED SOURCEOne controlled acquisition.
VERIFYChecksum/license/security.
INTERNAL ARTIFACT STOREImmutable model package.
NODE CACHELocal fast disk/object cache.
LOADExact revision into runtime.
REPORTLoaded hash/revision.
№60 Artifact Store concepts apply well: stable immutable references, checksums, retention and controlled distribution.
12. LOCAL MODEL REGISTRY

LOCAL TARGET ДОЛЖЕН ВЫГЛЯДЕТЬ ДЛЯ №65 КАК НОРМАЛЬНЫЙ MODEL DEPLOYMENT

{
  "model_ref": "model://local/model-x",
  "deployment_ref": "serve://eu-private/model-x/g12",
  "capabilities": {
    "text": true,
    "vision": false,
    "tools": true,
    "context_tokens": 32768
  },
  "policy": {
    "data_classes": ["PUBLIC","INTERNAL","CONFIDENTIAL"],
    "region": "PRIVATE-EU"
  },
  "quality_tier": "STANDARD",
  "latency_tier": "LOW",
  "cost_tier": "OWNED_CAPACITY",
  "health": "HEALTHY",
  "capacity": {
    "queue_headroom": 0.72,
    "kv_headroom": 0.61
  }
}
SAME ROUTING CONTRACT

Local is just another eligible target

Application should not know:

  • IP/port;
  • GPU count;
  • runtime vendor;
  • artifact path;
  • driver stack.

№65 sees capability/policy/health/cost class and routes accordingly.

13. LOCAL-FIRST ROUTING

ДЕШЁВЫЙ/ПРИВАТНЫЙ LOCAL MODEL МОЖЕТ БЫТЬ ПЕРВЫМ TIER

LOCAL STANDARD

Use for routine classification, extraction, rewriting, simple Q&A and confidential workloads.

VERIFY / UNCERTAINTY

Task fails quality floor or exceeds capability.

STRONGER TARGET

Cloud/private bigger model only if №34 escalation + №65 policy permit it.

For confidential data, escalation path may be another stronger private model rather than public cloud. Policy filter always precedes quality ranking.
14. CLOUD FALLBACK

LOCAL OUTAGE НЕ ДАЁТ АВТОМАТИЧЕСКОЕ ПРАВО ОТПРАВИТЬ PRIVATE DATA В CLOUD

Data classLocal unavailableSafe default
PUBLICPrivate model downRoute to compatible hosted model if policy/cost allows.
INTERNALPrivate model downOnly approved enterprise/provider endpoints.
CONFIDENTIALPrivate model downFail/queue/route to another approved private deployment.
REGULATED / AIR-GAPPEDLocal model downNo network fallback; degrade or wait locally.
Availability fallback must never silently widen data-boundary policy.
15. ECONOMICS / TCO

СРАВНИВАТЬ НЕ API PRICE С ЦЕНОЙ GPU, А TOTAL COST OF OWNERSHIP

CAPEX / RENTAL

Hardware

GPU/server/network/storage purchase or reserved infrastructure cost.

ENERGY

Power + cooling

24/7 accelerators consume power even when partially utilized.

OPS

People

Deployment, patching, monitoring, incident response, capacity planning and replacement.

IDLE

Unused capacity

Self-hosted economics worsen rapidly when accelerator utilization is low.

QUALITY GAP

Hidden cost

Cheaper local model may require more retries, human review or escalation.

DOWNTIME

Business cost

Provider redundancy may be expensive, but your own outage has real cost too.

DATA VALUE

Privacy benefit

Some workloads justify higher TCO because external processing is unacceptable.

LIFECYCLE

Hardware obsolescence

Model sizes/runtimes evolve faster than typical server depreciation plans.

Useful metric: cost per successful task at required quality/SLO, not raw cost per token.
16. BREAK-EVEN MODEL

SELF-HOSTING ВЫИГРЫВАЕТ, КОГДА FIXED COST ДЕЛИТСЯ НА ДОСТАТОЧНО БОЛЬШОЙ ПОЛЕЗНЫЙ VOLUME

SELF-HOSTED MONTHLY TCO

hardware amortization / rental
+ electricity / cooling
+ storage / network
+ operations labor
+ support / replacement reserve
+ idle capacity cost
= monthly_self_hosted_cost

UNIT COST

monthly_self_hosted_cost
--------------------------------
successful production tasks

COMPARE WITH:

hosted model API cost
+ network / provider extras
+ retries / escalation
+ quality-related human review

IMPORTANT:

Do the comparison at the SAME:
  quality threshold
  context/output distribution
  latency target
  availability target
  privacy class

Otherwise the break-even math is fake.
17. UTILIZATION

ДОРОГОЙ ACCELERATOR, КОТОРЫЙ 90% ВРЕМЕНИ IDLE, МОЖЕТ БЫТЬ ХУЖЕ API ДАЖЕ ПРИ НИЗКОЙ «ЦЕНЕ TOKENS»

SHARED POOL

Increase useful load

Serve several compatible internal applications through one gateway/model pool.

BATCH JOBS

Fill valleys

Run offline indexing/evaluation/synthetic workloads when interactive demand is low.

POWER DOWN?

Conditional

Possible if startup latency and hardware/cloud economics make dynamic scale-down useful.

Do not optimize for 100% utilization at the expense of interactive SLO; №70 explains the throughput/latency trade-off.
18. SIZING BY WORKLOAD

MODEL SIZE — НЕ ПЕРВЫЙ INPUT. ПЕРВЫЙ INPUT — TASK DISTRIBUTION

TASKSWhat must local model do?
QUALITY FLOOREvals determine sufficient models.
CONTEXT / OUTPUTTypical and p95 token lengths.
CONCURRENCYInteractive + batch demand.
MODEL CANDIDATESSmallest sufficient first.
HARDWARE BENCHMARKMeasure real deployment.
TCO / SLOSelect topology.
Не начинать с «у нас есть GPU X, какую максимальную модель туда запихнуть?». Start from task quality and workload economics.
19. SMALL MODEL STRATEGY

ЛОКАЛЬНЫЙ DEPLOYMENT ЧАСТО ВЫГОДЕН ИМЕННО НА УЗКИХ, ЧАСТЫХ ЗАДАЧАХ

CLASSIFICATION

High volume

Small model may meet quality floor at much lower compute cost.

EXTRACTION

Structured tasks

Constrained schema + verifier can make smaller local model sufficient.

REWRITE

Low reasoning

Style/format transforms may not require frontier reasoning model.

ROUTER / HELPER

Support role

Local model can handle cheap helper steps while hard synthesis escalates.

Local-first tier works best when evals prove sufficiency. Avoid using a weak local model for every task just to justify hardware purchase.
20. LARGE MODEL STRATEGY

БОЛЬШАЯ MODEL УВЕЛИЧИВАЕТ НЕ ТОЛЬКО VRAM, НО И FAILURE/OPS SURFACE

QUALITY

Potential uplift

Hard reasoning/long-context tasks may benefit from stronger local model.

HARDWARE

More devices / memory

May require multi-GPU/node topology and faster interconnect.

OPERATIONS

More moving parts

Longer load time, harder rolling deploy, more expensive idle capacity and larger blast radius.

The strongest local model is not automatically the best production model. Choose the smallest model that meets measured requirements plus reasonable headroom.
21. UPDATE LIFECYCLE

MODEL UPGRADE — ЭТО SOFTWARE RELEASE

DISCOVERNew candidate revision.
LICENSE / SECURITYReview artifact eligibility.
OFFLINE EVALQuality/safety/structured output.
BENCHMARKTTFT/TPOT/memory/capacity.
CANARYSmall traffic share.
PROMOTERegister new preferred target.
ROLLBACKKeep previous artifact available.
Do not auto-pull latest model/runtime into production. Exact revision promotion must be explicit and reversible.
22. DRIVER / RUNTIME COMPATIBILITY

SELF-HOSTING ДОБАВЛЯЕТ INFRA VERSION MATRIX

DRIVER

Device compatibility

Accelerator driver version must support runtime stack.

RUNTIME

Serving framework

Kernel support, model architecture and precision features vary by version.

MODEL FORMAT

Artifact compatibility

Not every runtime supports every model architecture/quantization format.

OS / CONTAINER

Environment pinning

Reproducible images reduce «works on one node» drift.

Keep a tested deployment matrix rather than upgrading drivers/runtime/model independently in production.
23. HIGH AVAILABILITY

ONE POWERFUL WORKSTATION = ONE FAILURE DOMAIN

SINGLE NODE

SPOF

Power, GPU, driver, motherboard or OS failure stops local AI entirely.

SECOND REPLICA

Basic HA

Independent node/replica with same approved model revision.

ROUTER HEALTH

Remove failed target

№65 stops traffic to unhealthy deployment and selects compatible alternate.

DEGRADE

Explicit fallback

Queue work, use smaller local model or policy-approved hosted target.

If availability requirement is low, one node may be perfectly acceptable. HA should be driven by business SLO, not infrastructure aesthetics.
24. DISASTER RECOVERY

MODEL WEIGHTS МОЖНО СКАЧАТЬ СНОВА; ВАЖНЕЕ ВОССТАНОВИТЬ APPROVED DEPLOYMENT STATE

ARTIFACT BACKUP

Immutable source

Approved weights/tokenizer/config stored in controlled artifact repository.

CONFIG AS CODE

Rebuild node

Serving runtime, model registration, policies and network config reproducible.

BENCHMARK PROFILE

Validate rebuild

After restore, compare model checksum and performance/quality smoke tests before traffic.

Do not rely on manually configured workstation as the only copy of production deployment knowledge.
25. DATA PRIVACY: LOCAL ≠ AUTOMATICALLY PRIVATE

ДАННЫЕ МОГУТ УТЕЧЬ ЧЕРЕЗ LOGS, SWAP, BACKUPS И OBSERVABILITY

PROMPT LOGS

Hidden leak

Local serving can still dump sensitive prompts/responses to disk/log aggregator.

SWAP / CRASH DUMPS

Memory persistence

Sensitive tensors/text may end up in system artifacts depending on OS/runtime.

BACKUPS

Long retention

Logs/artifacts copied elsewhere can violate intended local-only boundary.

MINIMIZE

Metadata-first telemetry

Collect latency/tokens/errors without raw payloads unless explicitly approved.

Self-hosting narrows the trust boundary; governance still must define classification, logging, retention, deletion and access controls.
26. NETWORK ARCHITECTURE

SERVING ENDPOINT ДОЛЖЕН БЫТЬ PRIVATE BACKEND, А НЕ НОВЫЙ PUBLIC API

USER / APP
    ↓
AUTH / API LAYER
    ↓
№65 MODEL GATEWAY
  policy
  tenant
  quota
  route
    ↓
PRIVATE NETWORK
    ↓
LOCAL MODEL POOL
  serve://model-a
  serve://model-b
    ↓
NO DIRECT USER ACCESS

ADMIN PATH:
  separate identity
  separate network / VPN / bastion
  audited deployment commands

MODEL ARTIFACT PATH:
  approved registry
    ↓
  controlled artifact repository
    ↓
  serving node cache

NOT:
  serving node pulls arbitrary URL
  given by user/model at runtime
Network isolation makes local model a controlled capability behind the same permission/routing boundary as hosted providers.
27. AIR-GAPPED DEPLOYMENT

NO INTERNET МЕНЯЕТ НЕ ТОЛЬКО INFERENCE, НО И UPDATE PROCESS

TRANSFER GATE

Controlled import

Weights, runtime images and patches enter via approved media/process.

INTERNAL REGISTRY

No external pull

All runtime dependencies/artifacts available inside secure zone.

OFFLINE EVALS

Local validation

Quality and security test suites must also live in the isolated environment.

PATCH LATENCY

Plan delay

Security/runtime updates take longer due to controlled transfer/review.

Air-gap improves external network isolation but increases operational discipline requirements and patch/update latency.
28. MULTI-TENANCY

SHARED LOCAL GPU POOL НЕ ДОЛЖЕН СМЕШИВАТЬ AUTHORITY И DATA POLICY

TRUSTED TENANT CONTEXT

From gateway

Serving receives workload class/tenant metadata from host-controlled path.

SCHEDULING FAIRNESS

No monopolization

Tenant/workload quotas map to local queue/KV/concurrency budgets.

PAYLOAD ISOLATION

Runtime-dependent

Ensure one request cannot access another request's cache/state/log content.

If threat model demands strong tenant isolation, separate deployments/nodes may be safer than relying only on logical scheduler isolation.
29. OPERATIONS OWNERSHIP

КТО ОТВЕЧАЕТ ЗА SELF-HOSTED MODEL В 03:00?

MODEL OWNER

Quality / eligibility

Approves model revision, eval thresholds, license and intended task classes.

PLATFORM OWNER

Serving/runtime

Runtime, hardware, deployment, monitoring, capacity and incident response.

SECURITY / GOVERNANCE

Boundary

Artifact source, network/data policy, retention and access review.

PRODUCT OWNER

SLO / cost / fallback

Defines what degradation/outage behavior is acceptable.

If no team owns hardware/runtime lifecycle, self-hosting is an architectural orphan even if demo performance looks good.
30. OBSERVABILITY

SELF-HOSTING ДОБАВЛЯЕТ HARDWARE/DEPLOYMENT METRICS К №70 SERVING METRICS

UP

Deployment Availability

Ready time by model pool/node/revision.

GPU

Accelerator Health

Memory, temperature, power, utilization, hardware/runtime errors.

VRAM

Memory Headroom

Weights + KV + runtime occupancy and OOM protection margin.

TCO

Cost / Successful Task

Hardware + energy + operations divided by verified useful output.

UTIL

Useful Utilization

How much owned accelerator capacity produces needed production work.

MTTR

Recovery Time

Runtime/node/model failures → healthy serving again.

REV

Revision Fleet

Which exact model/runtime artifacts are loaded where.

ESC

Cloud Escalation Rate

Share of local-first tasks that require stronger external target.

31. BENCHMARKING

TEST MODEL + HARDWARE + RUNTIME КАК ОДИН DEPLOYMENT

QUALITY

Task evals

Same representative eval set used for hosted candidates.

LATENCY

TTFT / TPOT

Real prompt/output distributions and concurrency.

THROUGHPUT

Useful capacity

Tokens/tasks per second under SLO, not maximum synthetic peak.

SOAK

Sustained hours

Thermals, fragmentation, leaks, runtime stability and hardware faults.

FAILOVER

Node loss

Router/fallback behavior under local deployment outage.

POWER

Energy

Useful tasks/tokens per energy/cost when economics matter.

LONG CONTEXT

KV pressure

p95 context lengths at expected concurrency.

COLD START

Recovery

Artifact load + runtime warmup duration.

Benchmark every change to weights, quantization, runtime, driver or hardware class. Deployment performance is emergent from the whole stack.
32. FAILURE INJECTION

ПРОВЕРИТЬ НЕ ТОЛЬКО MODEL QUALITY, НО И ЖИЗНЬ БЕЗ ОДНОГО УЗЛА / DISK / NETWORK

KILL RUNTIME

Process restart

Health removes target and returns it only after model reload/readiness.

KILL NODE

Hardware loss

Traffic routes to replica/degradation policy.

FULL DISK

Artifact/log pressure

Deployment does not corrupt model cache or block all inference silently.

NETWORK PARTITION

Gateway ↔ serving

Typed health/fallback behavior; no infinite hangs.

CORRUPT ARTIFACT

Checksum test

Node refuses to load invalid weights.

THERMAL LOAD

Soak

Sustained throughput stays within expected envelope without throttling surprises.

CLOUD DENY

No fallback

Restricted data class correctly fails/queues locally.

ROLLBACK

Bad model revision

Previous approved deployment can be restored quickly.

33. QUANTIZATION BOUNDARY

QUANTIZATION МОЖЕТ СДЕЛАТЬ SELF-HOSTING ВОЗМОЖНЫМ — НО ЭТО №72

№72

Precision / compression choice

Evaluates FP16/BF16/INT8/INT4-like formats, calibration and quality/performance trade-offs.

№71

Deployment consequences

Chooses approved quantized artifact if it meets quality and hardware economics, then operates it via №70.

Do not duplicate quantization theory here. Self-hosting only needs artifact eligibility + measured real deployment behavior.
34. FINE-TUNED MODEL BOUNDARY

ADAPTED WEIGHTS НЕ ДЕЛАЮТ DEPLOYMENT PROCESS ОСОБЕННЫМ

№39 OUTPUT

Weights / adapter

Fine-tuning pipeline produces candidate artifact and eval results.

PACKAGE

Immutable revision

Merge/reference base model + adapter versions explicitly.

№71 DEPLOY

Same controls

License, checksum, security, benchmark, canary, rollback and registry entry.

Training pipeline and production serving pipeline should meet at a versioned model artifact contract.
35. EDGE DEPLOYMENT

EDGE = ЖЁСТКИЕ POWER / MEMORY / UPDATE LIMITS

SMALLER MODEL

Fit first

Choose task-sufficient artifact for constrained device.

QUANTIZED

Often necessary

Precision reduction can reduce memory/storage and enable local execution.

OFFLINE UPDATE

Version channel

Artifact rollout must survive intermittent connectivity.

THERMAL / BATTERY

Real operating envelope

Sustained inference may be power-limited rather than compute-limited.

Edge is not a smaller data center. Operational assumptions about cooling, network, maintenance and physical access differ fundamentally.
36. LOCAL DEVELOPMENT VS PRODUCTION

«РАБОТАЕТ У МЕНЯ НА НОУТБУКЕ» — ПОЛЕЗНО, НО ЭТО ДРУГОЙ SLO

AspectDeveloper localProduction self-hosted
AvailabilityBest effort.Declared SLO / monitoring / recovery.
Model revisionMay change manually.Pinned, approved, auditable.
SecuritySingle-user trust.Network/auth/tenant/data policy.
CapacityOne user.Concurrent workload + overload behavior.
UpdatesManual.Canary/rollback/versioned deployment.
ObservabilityConsole.Metrics, alerts, fleet visibility.
37. FAILURE MODES

КАК SELF-HOSTING СТАНОВИТСЯ ДОРОГОЙ И ХРУПКОЙ ИГРУШКОЙ

"API IS EXPENSIVE"
Hardware purchased without utilization/TCO model.
COST PER SUCCESS
MAX MODEL THAT FITS
Large artifact chosen without task-specific quality need.
SMALLEST SUFFICIENT
MODEL NAME ONLY
Revision/tokenizer/license/runtime drift cannot be reproduced.
PIN ARTIFACT
DIRECT USER → SERVE
Gateway policy/quotas/audit are bypassed.
PRIVATE ENDPOINT BEHIND №65
LOCAL = PRIVATE
Logs/backups/swap leak sensitive payloads anyway.
END-TO-END DATA POLICY
ONE WORKSTATION = PROD
Single hardware/OS/power failure stops service.
MATCH SLO / ADD HA IF NEEDED
AUTO-PULL LATEST
Unreviewed artifact/runtime reaches production.
APPROVE / EVAL / CANARY
NO OWNER
Drivers, security patches, failed disks and model upgrades become orphan work.
PLATFORM OWNERSHIP
CLOUD FALLBACK FOR ALL
Outage silently violates privacy/data residency.
POLICY-SAFE FALLBACK
38. METRICS

ЧТО ИЗМЕРЯТЬ, ЧТОБЫ SELF-HOSTING БЫЛ РЕШЕНИЕМ, А НЕ ИДЕОЛОГИЕЙ

$

Cost / Successful Task

Full local TCO divided by verified useful production tasks.

Q

Quality Pass Rate

Local model success by task segment vs hosted alternatives.

UTIL

Useful Accelerator Utilization

Owned capacity producing needed work under SLO.

UP

Availability

Ready endpoint uptime by model pool/revision.

MTTR

Recovery Time

Node/runtime/model incident → service restored.

ESC

Escalation Rate

Share of local-first tasks requiring stronger target.

SLO

Latency Success

TTFT/TPOT target compliance from №70.

POL

Policy-safe Route Rate

Restricted workloads never escape approved private boundary.

39. MVP IMPLEMENTATION

ONE MODEL + ONE MACHINE + ONE PRIVATE ENDPOINT — ДОСТАТОЧНО, ЧТОБЫ ПРОВЕРИТЬ REAL VALUE

self_hosted_models/
├── model_registry.yaml
├── artifacts/
│   └── approved-model-manifest.json
├── deployment/
│   ├── container-or-service-config
│   └── runtime.env.example
├── benchmarks/
│   ├── workload.json
│   └── results.json
├── policies/
│   └── data-routing.yaml
└── runbook/
    ├── deploy.md
    ├── rollback.md
    └── incident.md

MVP FLOW:

approve model artifact
  ↓
verify checksum/license
  ↓
load to one controlled node
  ↓
serve through №70 runtime
  ↓
register endpoint in №65
  ↓
allow only explicit task/data classes
  ↓
measure:
  quality
  TTFT / TPOT
  concurrency
  VRAM
  uptime
  TCO
  ↓
compare with hosted baseline
  ↓
keep / scale / abandon
80% VALUE MVP

Prove the deployment before building a fleet

  • One concrete high-value workload.
  • One approved model revision.
  • One machine/node.
  • One serving runtime from №70.
  • Private endpoint behind №65.
  • Exact checksum/tokenizer/license record.
  • Real p50/p95 prompt/output benchmark.
  • One local capacity profile.
  • Basic health/alerts.
  • Rollback to previous artifact.
  • Explicit data classes allowed locally/cloud.
  • Full monthly TCO estimate.
  • Hosted baseline comparison.

If this MVP does not produce quality/privacy/economic value, a cluster will not fix the architecture.

40. WHEN TO UPGRADE

МАСШТАБИРОВАТЬ ТОЛЬКО ПО РЕАЛЬНОМУ WORKLOAD

Observed needUpgrade
Single node meets quality but saturatesAdd horizontal serving replicas via №70.
Model does not fit one acceleratorMulti-GPU serving topology or evaluate №72 quantization / smaller sufficient model.
Multiple task classes need different modelsCreate explicit local model pools registered in №65.
Availability mattersSecond independent node, health-aware routing, artifact replication and tested failover.
Air-gapped productionInternal artifact registry, offline update/eval pipeline and transfer controls.
Costs still highIncrease utilization, route smaller models, batch offline work, evaluate quantization before buying more hardware.
Quality gap remainsUse hybrid escalation or №39 adaptation only if evals justify it.
41. PRACTICAL DECISION

СТОИТ ЛИ ДЕЛАТЬ ОТДЕЛЬНЫЙ КОМПОНЕНТ?

ВопросОтвет
Стоит ли реализовывать?Условно. Только при понятной privacy, offline, economics, latency или custom-model причине.
Separate Component?YES. Private model deployment/pool is a distinct infrastructure target behind Model Gateway.
Минимум 80% ценности?Approved artifact, one node/runtime, private endpoint, route policy, realistic benchmark, capacity/TCO profile, monitoring and rollback.
Когда overkill?GPU cluster for low-volume general chat that hosted API serves cheaply and better.
Trigger?Data cannot leave boundary, workload is large/stable, offline requirement exists, custom weights are required or measured TCO/latency clearly wins.
Как измерить uplift?Quality pass rate, cost per successful task, utilization, latency SLO, availability, privacy-policy coverage and cloud escalation rate.
Можно ли rule/tool/code вместо LLM-agent?Да. Deployment, routing eligibility, updates, checksums and capacity are deterministic infrastructure. No «self-hosting agent» is required.
42. DESIGN RULES

ПРАВИЛА ДЛЯ РЕАЛЬНОЙ СИСТЕМЫ

RULE 01

Self-host for a reason

Privacy, offline, economics, latency or custom artifacts — not fashion.

RULE 02

Smallest sufficient model

Choose by task evals, not maximum model that fits hardware.

RULE 03

Pin every artifact

Weights, tokenizer, runtime, license and checksum are deployment identity.

RULE 04

Local target stays behind Gateway

Same routing/policy/quotas/audit boundary as hosted models.

RULE 05

Measure full TCO

Hardware + energy + people + idle + quality gap + downtime.

RULE 06

Local is not automatically private

Logs, swap, backups and observability remain data-governance surfaces.

RULE 07

Treat weights as supply-chain assets

Approved source, checksum, no arbitrary remote code.

RULE 08

Canary model/runtime changes

Never auto-pull latest into production.

RULE 09

Scale after proof

One-node MVP must show value before cluster complexity.

43. FINAL MAP

SELF-HOSTING MOVES THE MODEL BOUNDARY INSIDE YOUR INFRASTRUCTURE — AND MOVES THE RESPONSIBILITY WITH IT

WHY SELF-HOST?

privacy?
data residency?
offline?
stable high volume?
latency locality?
custom model?
        ↓
IF NO STRONG DRIVER:
  HOSTED API MAY BE BETTER

IF YES:
        ↓
DEFINE TASKS
        ↓
QUALITY FLOOR / EVALS
        ↓
CHOOSE SMALLEST SUFFICIENT MODEL
        ↓
MODEL ARTIFACT REVIEW
  exact revision
  weights checksum
  tokenizer checksum
  license
  security review
        ↓
CHOOSE DEPLOYMENT TOPOLOGY
  desktop
  workstation
  private server
  cluster
  edge
  air-gap
        ↓
HARDWARE PROFILE
  VRAM
  RAM
  bandwidth
  storage
  interconnect
  power
  thermals
        ↓
№70 SERVING RUNTIME
  batching
  KV cache
  scheduler
  admission
  health
  streaming
        ↓
PRIVATE MODEL ENDPOINT
        ↓
REGISTER IN №65
  capability
  data classes
  quality tier
  latency
  cost class
  health
  capacity
        ↓
MODEL ROUTING

PUBLIC / LOW-RISK:
  local OR hosted

CONFIDENTIAL:
  approved local/private only

HARD TASK:
  №34 escalation
        ↓
  stronger eligible target
  only if policy permits

OPERATIONS:

artifact repository
  ↓
node cache
  ↓
load exact revision
  ↓
warmup
  ↓
health
  ↓
serve
  ↓
monitor
  ↓
canary update
  ↓
rollback if regression

ECONOMICS:

self-hosted cost
  =
  hardware
  + energy
  + cooling
  + storage/network
  + operations labor
  + idle capacity
  + downtime
  + quality gap

measure:
  COST PER SUCCESSFUL TASK

NOT:
  raw GPU price
  raw token throughput alone

BOUNDARIES:

№65
  routes among local/private/cloud targets

№70
  executes inference efficiently

№71
  owns deployment strategy and operations

№72
  changes precision/compression artifact

№76
  defines data/privacy/governance rules

CORE PRINCIPLE:

SELF-HOSTING DOES NOT
REMOVE A PROVIDER.

IT MAKES YOU
THE PROVIDER.

YOU NOW OWN:

THE WEIGHTS,
THE HARDWARE,
THE RUNTIME,
THE SECURITY BOUNDARY,
THE CAPACITY,
THE FAILURES,
THE PATCHES,
THE LICENSE,
THE COST
AND THE UPTIME.

THAT IS A GREAT TRADE
WHEN CONTROL MATTERS.

IT IS A BAD TRADE
WHEN THE ONLY REASON IS
"API SEEMS EXPENSIVE."

ECC RETROFIT / PRACTICAL HARNESS INTEGRATION

A. Related ECC ideas. Context-as-cache, scoped memory, lifecycle hooks, selective capabilities, feature flags, deterministic enforcement, provider-neutral adapters and eval-gated learning are applied only where relevant to №71 Local LLM / Self-Hosted Models.

B–E. Existing boundary and placement. The existing conceptual boundary, class SPECIALIZED, default CONDITIONAL and owner Model Router + Model Infrastructure remain authoritative. Runtime/control/data/offline placement is unchanged; durable state stays outside model context.

F–H. Hooks and contracts. Use bounded PRE_MODEL/POST_MODEL, PRE_TOOL/POST_TOOL, CHECKPOINT and TASK_COMPLETED events as applicable. Illustrative fields and canonical contracts are defined in NEW_CONTRACTS_SPEC.md; no universal schema is implied.

I–J. Security and evaluation. Host-side schema, permission, secret, budget, idempotency and audit checks take precedence over LLM output. Optional mechanisms require a feature flag and WITH/WITHOUT ablation; measure quality, acceptance, correction, latency, cost, escalations and severe errors.

K–L. Task profiles and cross-references. A TaskProfile selects the relevant skill, tool/context slice, memory scope and enforcement profile independently from FAST/STANDARD/DEEP. See cross-reference map, hook spec and ablation plan. Provider adapters remain outside the core.