Compressing Large Language Models for Security Analysis: Quantization and Expert Pruning in Practice
As large language models (LLMs) become increasingly common in vulnerability discovery and code audit, the cost of inference becomes a major deployment bottleneck for security teams. This paper describes practical approaches to model compression for security use cases, with a focus on two proven techniques: quantization and expert pruning. It explains the structure of model memory consumption, walks through group-wise quantization and its error checks, and explores how to reduce redundancy in Mixture-of-Experts (MoE) architectures without sacrificing accuracy on critical security tasks. It also describes an evaluation design that measures capability retention after compression and outlines a repeatable engineering process for applying these methods in production.
Background: Why Security Analysis Needs Large Models
The number of vulnerabilities in software grows with codebase size. Traditional static analysis tools rely on manually written rules that often fail to cover novel defect patterns and produce high false-positive rates, requiring security teams to spend significant time triaging results. Large language models can understand code semantics, track data flow, and explain call relationships, making them increasingly useful for vulnerability discovery, patch review, and code audit.
However, model scale introduces new deployment challenges. Larger parameter counts generally improve reasoning capability, but they also produce larger weight files and raise the barrier to deployment. An uncompressed large model may require multiple high-memory accelerators and significant storage and network bandwidth. For security teams operating in restricted networks or edge environments, these costs directly determine whether a solution can be deployed at all.
Balancing model capability against deployment cost is therefore a central issue in LLM engineering for security. Model compression techniques offer a practical path forward.
Understanding the Components of Model Size
Model size is primarily determined by two factors: the number of parameters and the number of bits used per parameter. For example, in a common half-precision floating-point format, each parameter occupies 2 bytes. A 100-billion parameter model would require about 200 GB of storage for weights alone.
Inference introduces additional memory overhead, including activation caches, key-value caches, and runtime temporary buffers. These overheads grow with context length and the number of concurrent requests. Therefore, compression efforts should focus not only on file size, but also on GPU memory consumption and inference latency.
A rough estimate can be made using the following formula:
Weight storage ≈ number of parameters × bytes per parameterGPU memory requirement ≈ weight storage + activation and cache overhead + runtime headroom
The estimation result determines the compression target. If a team has only one inference server, the weights must be compressed to fit within its memory, while leaving room for caches and concurrent requests.
Quantization: Storing Weights with Lower Numerical Precision
Quantization maps high-precision floating-point numbers to low-bit integers. The common approach is to compute a scaling factor and a zero point for a group of weights, then round each weight into the integer range of the target bit width. During inference, the scaling factor is used to approximate the original value.
Quantization falls into two main categories:
- Post-training quantization: applies directly to existing weights without retraining. It has low implementation cost but is sensitive to outliers.
- Quantization-aware training: simulates quantization error during the training process. It typically yields better accuracy but requires additional training resources and data.
In practice, group-wise quantization is often more stable than whole-tensor quantization. Weights are divided into fixed-length groups, and each group uses its own scaling factor, which reduces the impact of outliers on the overall precision. Smaller groups generally produce better accuracy but also require more scaling factors to store, creating a trade-off.
The following pseudocode illustrates the idea:
def quantize_group(weights, bits=4, group_size=128):qmax = 2 ** (bits - 1) - 1result = []for group in split_into_groups(weights, group_size):scale = max(abs(w) for w in group) / qmaxif scale == 0:scale = 1.0q_values = [clamp(round(w / scale), -qmax - 1, qmax) for w in group]result.append((q_values, scale))return result
Error checking after quantization is mandatory. A common practice is to compare the output distributions of the compressed model and the original model on the same inputs, with special attention to tail samples.
Expert Pruning: Removing Redundancy in Sparse Structures
Mixture-of-Experts (MoE) architectures split feed-forward layers into multiple expert sub-networks, with a router selecting only a few experts per input. This structure contains a large total parameter count, but only a subset is activated for each inference, making it suitable for structured slimming.
Expert pruning aims to identify and remove experts that contribute little to the target task. Common criteria include:
- Activation frequency: counting how often each expert is selected by the router on representative data.
- Contribution: measuring how much a metric on the validation set drops when a specific expert is removed.
- Redundancy: merging or removing experts whose outputs are highly similar.
The risks are clear. Infrequently activated experts may handle rare but important patterns, such as specific types of memory management defects or vulnerabilities in uncommon protocol implementations. Therefore, the pruning decision should be made after analyzing statistics by task category, rather than relying on overall activation frequency alone.
The following flow illustrates the approach:
1. Count each expert's activation frequency and loss contribution on a representative dataset2. Mark high-value experts by task category3. Remove or merge low-contribution experts4. Re-evaluate on the held-out set and compare with the baseline5. Roll back the step if a key category's metric drops below the threshold
Evaluation: Measuring Capability Retention Beyond Model Size
Evaluating a compressed model must cover capability, not just size. A complete evaluation plan should include at least the following:
- Task coverage: vulnerability identification, data flow analysis, patch diff review, code audit Q&A, etc.
- Metrics: precision, recall, false-negative rate, as well as results broken down by vulnerability type.
- Baseline comparison: using the uncompressed model’s performance on the same evaluation set as a reference.
- Data isolation: evaluation samples must be separate from training and calibration data to avoid inflated results.
The retention rate should be computed on the same evaluation set, for example, “the ratio of the compressed model’s key metrics to the baseline’s.” This number is only valid for that specific evaluation set and cannot be generalized to other scenarios. Teams should repeat the test on their own codebase, recording the test version, data scope, and random seed to ensure reproducibility.
Engineering Implementation Process
To put a compression solution into production, the following steps are recommended:
- Define goals: determine hardware limits, latency requirements, and acceptable capability degradation.
- Prepare calibration data: select code samples close to actual business scenarios, covering the main languages and vulnerability types.
- Compress incrementally: apply quantization first, then pruning, and save intermediate versions at each step.
- Run regression testing: validate on security benchmark sets and historical real-world cases.
- Stage the rollout: start in a low-risk environment and compare with manual review results.
- Monitor continuously: record false positives and false negatives, and periodically re-evaluate.
Every version should have traceable records so that rollback is straightforward when problems occur.
For security, analysis services should follow the principle of least privilege. The model reads only the code repositories it is authorized to access, analysis results are written to controlled storage, and logs do not contain keys or sensitive credentials. If the code under analysis contains text intended to alter model behavior, the system should treat it accordingly.
