Building an On-Premises AI Coding Platform: Hardware, Scheduling, and Auditing in Practice
This article provides a practical guide to building an on-premises AI coding platform. It covers evaluating the cost and necessity of local deployment, estimating hardware requirements such as VRAM and GPU count based on model size, selecting inference engines, and implementing concurrency scheduling. Additionally, it explores routing strategies, log auditing, and compliance measures to ensure secure and efficient operations for development teams.
1. Determining the Need for On-Premises Deployment
On-preises localization is not the default choice for all teams. Teams suitable for investing in a local platform usually meet three conditions simultaneously: they have private codebases that cannot leave the intranet; their compliance departments require auditing and log retention; and their developer scale is large enough to amortize hardware costs.
Small teams or those using mostly open-source code can try a cloud API for a month or two first. Record monthly API calls and costs, then compare them with a local solution. Both sides must be calculated using the same metrics:
Monthly cloud cost ≈ Monthly average requests × Average input/output tokens per request × Unit price
Monthly local cost ≈ Hardware purchase ÷ Depreciation months + Power & datacenter costs + Ops labor cost
Below is a calculation example. All prices are hypothetical and should be replaced with contract prices and financial metrics in practice. Assume 30 developers, 40 requests per person per day, 22 workdays per month, with an average of 3,000 input tokens and 500 output tokens per request.
- Monthly requests: 30 × 40 × 22 = 26,400
- Total monthly tokens: 26,400 × 3,500 ≈ 92.4 million tokens
- Cloud cost: Assuming an average price of 20 CNY per million tokens, the monthly cost is about 1,848 CNY.
- Local cost: Hardware purchase price of 800,000 CNY, depreciated over 36 months, equals about 22,222 CNY/month; average power consumption of 2.5kW equals 1,800kWh/month, at 0.8 CNY/kWh, power cost is about 1,440 CNY; ops calculated at 0.2 FTE, 30,000 CNY per FTE per month, equals about 6,000 CNY. Total: about 29,662 CNY.
In this example, the local solution costs about 16 times the cloud solution. The two break even only when the monthly token volume reaches about 16 times the current usage. If the cloud unit price drops to 15 CNY per million tokens, the breakeven point is about 21 times the current usage. This example does not account for the value of compliance. If code is prohibited from being sent externally, the cloud solution is not viable at all, making cost comparisons meaningless.
Code and log security risks must be considered early in the solution phase, including code auditing, model output retention, least privilege, and key management. Section 4 provides a specific checklist.
2. Hardware Foundation: Sizing by Model Scale
1. How to Estimate VRAM
The VRAM usage of an inference node consists of two parts: model weights and KV Cache. The calculation formulas are as follows:
Weight VRAM = Parameter count × Bytes per parameter
FP16 takes 2 bytes per parameter, INT8 takes 1 byte, and INT4 takes about 0.5 bytes. Taking a 70B model as an example, FP16 weights are about 140GB, and after INT4 quantization, it is about 35GB to 40GB. The quantization method determines how many GPUs are needed.
The formula for KV Cache size is:
KV Cache = 2 × Number of layers × Number of KV heads × Head dimension × Context length (number of tokens) × Batch size × Bytes per element
The sources for these parameters are as follows:
- Number of layers, KV heads, head dimension: Read from the model’s
config.json. The field names are usuallynum_hidden_layers,num_key_value_heads, andhead_dim. - Number of KV heads: For models using Grouped Query Attention (GQA) or Multi-Query Attention (MQA), the number of KV heads is less than the number of query heads. For traditional Multi-Head Attention (MHA) models, the number of KV heads equals the number of query heads.
- Bytes per element: For FP16 or BF16 KV Cache, use 2. For FP8 or INT8, use 1.
- Batch size: The number of sequences generating simultaneously.
Taking a common 70B structure as an example: 80 layers, 8 KV heads, head dimension 128, KV Cache uses FP16.
- Per token usage: 2 × 80 × 8 × 128 × 2 = 327,680 bytes, about 320KB
- Single sequence, 8K context: 327,680 × 8,192 ≈ 2.5GiB
- 32 concurrent sequences, 8K context: about 80GiB
If a model of the same scale uses traditional multi-head attention with 64 KV heads, the KV Cache will magnify by 8 times at the same length. The model structure must be confirmed before sizing.
2. How Many GPUs Does a 70B Model Need?
Calculate using the following steps:
- Weights: 70B model with INT4 quantization, about 40GB.
- KV Cache: 32 concurrent, 8K context, FP16 storage, about 80GiB.
- Add a 15% margin for activations, framework overhead, and fragmentation: (40 + 80) × 1.15 ≈ 138GB.
- Calculate each 80GB GPU at 90% usable, meaning 72GB usable per GPU.
- Number of GPUs = Ceiling(138 ÷ 72) = 2 GPUs.
The theoretical usable VRAM for 2 GPUs is 144GB, leaving a margin of only 6GB, which means runtime fluctuations could cause out-of-memory errors. Additionally, tensor parallelism is usually split by 2, 4, or 8. It is recommended to use four 80GB GPUs, providing about 288GB of usable VRAM and leaving an ample margin. If concurrency or context length increases, recalculation is required.
Storing the KV Cache using INT8 can reduce the 80GiB above to about 40GiB. This approach requires inference engine support and validation to ensure generation quality does not degrade.
3. How to Estimate Concurrency for 100 Users
100 developers will not initiate requests simultaneously. You can estimate the number of in-flight requests using the following formula:
Peak concurrency = Active users × Peak requests per user per hour × Average latency per request (seconds) ÷ 3600
Calculating with 100 active users, 20 requests per user per hour during peak times, and an average latency of 15 seconds per request: 100 × 20 × 15 ÷ 3600 ≈ 8.3, rounded up to 9 concurrent in-flight requests. This number can be directly plugged into the previous KV Cache formula for a worst-case check based on the maximum context length. The KV Cache for nine 8K sequences is about 22.5GiB, which can be accommodated in the four 80GB GPU configuration.
4. Lower Bound for Single-Step Decoding Speed
Large models generate tokens step-by-step, reading weights from VRAM for each generation step. Therefore, there is a theoretical lower bound for single-step latency:
Single-step latency lower bound ≈ Weight bytes read per GPU per step ÷ VRAM bandwidth
Taking 4-GPU tensor parallelism and 40GB INT4 weights as an example, each GPU reads about 10GB per step. If VRAM bandwidth is calculated at 2TB/s, the single-step lower bound is about 5 milliseconds. This result does not account for KV Cache reads and inter-GPU communication, and can only be used as an upper limit reference. Actual performance must be measured through a POC.
5. Other Hardware Specifications
- VRAM bandwidth: Based on the nominal value in the GPU specification sheet. Bandwidth directly impacts decoding speed.
- CPU memory: Configure at 1.5 times or more of the total VRAM for model loading and buffering. A node with four 80GB GPUs is recommended to have 512GB or more. This is an empirical value; actual needs depend on testing.
- Local storage: Models are saved by version, and a 70B model’s FP16 weights are about 140GB. Multiple versions coexisting and logging require additional space. It is recommended to start with at least 2TB of NVMe.
- Network: Single-node multi-GPU communicates via PCIe or NVLink. The data volume of requests and responses is small, so 10GbE for frontend access is usually sufficient. InfiniBand or high-speed RoCE networks are only needed when doing tensor parallelism across nodes.
6. Reference Configurations
| Model Scale | Quantization | Approx Weight VRAM | Starter Configuration |
|---|---|---|---|
| 7B | FP16 | 14GB | 1x 24GB GPU, suitable for small-scale validation |
| 32B | INT4 | ~18GB | 1x 48GB GPU |
| 70B | INT4 | ~40GB | 4x 80GB GPUs; 2 GPUs only for small concurrency validation |
The above configurations are just starting points; the final setup should be based on load testing results.
3. Inference Engines and Concurrency Scheduling
1. How to Choose an Inference Engine
| Engine | Key Features | Use Cases |
|---|---|---|
| vLLM | Uses PagedAttention to manage KV Cache, supports continuous batching, provides OpenAI-compatible API, broad model support | Multi-user shared intranet services |
| TensorRT-LLM | NVIDIA-specific optimization, requires compiling engines for specific models and GPU models, tightly coupled with CUDA and TensorRT versions | Scenarios with high throughput requirements and strong ops team capabilities |
| llama.cpp | Uses GGUF quantization format, supports CPU and various GPUs, lightweight deployment | Small teams, single-node or edge devices |
In multi-user concurrency scenarios, vLLM and TensorRT-LLM are generally more suitable for shared services than llama.cpp. The final selection should be based on the throughput and Time To First Token (TTFT) measured during a POC.
2. Key Concurrency Scheduling Mechanisms
- Continuous batching: Scheduling is performed on a per-generation-step basis. When a request ends, it immediately leaves the batch, and new requests join at any time. The GPU will not idle waiting for an entire batch of requests to finish.
- PagedAttention: KV Cache is allocated in fixed-size blocks, reducing VRAM fragmentation and supporting cache sharing for sequences with the same prefix.
- Chunked prefill: Long prompts are processed in segments to prevent a single long request from occupying computing resources for too long and blocking other users’ decoding.
- Rate limiting: Sets requests per minute and token budgets per user or team, usually implemented using the token bucket algorithm. Requests exceeding limits return a 429 status code.
- Priority: Interactive code completion is set to high priority, while batch code review is set to low priority.
- Timeout and disconnection recovery: When the client disconnects, generation is canceled immediately, and the corresponding KV Cache blocks are released.
3. Request Processing Flow
- The gateway completes authentication and identifies the user and team.
- Checks rate limits and quotas; rejects directly if exceeded.
- Queues by priority and sets a maximum queueing duration.
- The scheduler forms batches within the VRAM budget.
- Inference executes, and results are returned via streaming.
- When the request times out or the client disconnects, cancels generation and reclaims resources.
- Records TTFT, output speed, and queue duration.
4. Local-First Routing and Log Auditing
1. Routing Strategy
- Local-first: All requests are sent to the intranet model service by default.
- Failover: If the local node is unhealthy, it first switches to a backup node in the same datacenter. Cloud failover is disabled by default. Cloud failback can only be enabled for approved, desensitized, non-sensitive requests.
- Sensitive file blocking: Blocks requests based on directory paths (e.g., payment modules, key configuration directories) and classification tags. Scans for keys, passwords, and certificates before sending. If a rule is hit, it is desensitized before sending or rejected directly.
2. Log Desensitization and Retention
- By default, only metadata is recorded: Request ID, user, team, timestamp, model version, input/output token count, latency, routing decision, and number of rules hit.
- Original code is not saved by default. If saving is strictly necessary, it should be encrypted, and keys and passwords should be masked.
- The retention period is determined by the compliance department and should not be permanently saved by default.
- Audit logs use append-only writes to prevent tampering.
3. Permissions and Alert Checklist
- Least privilege: Developers can only query their own call records. Administrator configuration operations and log queries use different roles, authorized separately.
- Key management: Keys for model services and gateways are stored in a key management system and are not written into code or configuration repositories.
- Alert items: Sudden spike in single-user requests; sensitive rule hits exceeding thresholds; access during non-working hours; bulk export of historical records; abnormal model node restarts.
5. POC Checklist and Code Example
1. Minimum POC Checklist
- Hardware: Based on
