Distillation Attacks: How Large-Model Knowledge Is Extracted and How to Defend Against It

    Knowledge distillation is widely used to transfer capabilities from large teacher models to smaller, more efficient student models. The same mechanism can be abused through large-scale, automated API queries that collect model outputs and use them to train a competitive substitute model. This article explains the technical principles, attack workflow, common variants, legal and commercial risks, and a six-layer defense strategy covering contracts, access control, output protection, reasoning isolation, auditing, and model governance.

    1. From Knowledge Distillation to Distillation Attacks

    As large language models evolve rapidly, training costs, dataset sizes, and compute requirements continue to rise. Knowledge distillation is a model compression and capability-transfer technique that moves knowledge from a large teacher model to a smaller student model. It is commonly used to reduce inference costs and support private or resource-efficient deployment.

    In commercial competition, however, this technique can be repurposed as a systematic method for extracting a target model’s capabilities. This misuse is commonly referred to as a distillation attack.

    A distillation attack can be defined as follows: an attacker submits large numbers of high-frequency, templated prompts to a target model, collects the resulting high-quality responses, and uses the input-output pairs as training data for a substitute model. The substitute model is designed to approximate the target model’s functionality and behavior while requiring far less investment than building a comparable model from scratch.

    In commercial settings, this activity is often treated as a breach of the target service’s terms. Model service agreements commonly prohibit automated scraping, bulk extraction, reverse engineering, and the use of outputs to train competing models.

    The concept of knowledge distillation was systematized in academic research around 2015. Its central idea is to use the soft labels produced by a teacher model to transfer dark knowledge to a student model. A teacher does not only assign a probability to the correct class. It also assigns nonzero probabilities to incorrect classes. These probability distributions contain structural information about class similarity and contextual decision boundaries that cannot be conveyed by hard labels alone.

    Distillation attacks exploit the same mechanism. The target model acts as the teacher, the attacker’s substitute model acts as the student, and the attacker attempts to obtain the teacher’s dark knowledge indirectly by collecting its outputs.

    2. How Knowledge Distillation Works

    2.1 The Teacher-Student Paradigm

    A conventional distillation system contains two models:

    • Teacher model: Usually larger, more capable, and more expensive to run.
    • Student model: Usually smaller, faster, and easier to deploy in resource-constrained environments.

    The student is not trained only against manually labeled data. It also learns to approximate the teacher’s output distribution. These outputs are called soft targets and generally contain more information than hard labels.

    For example, in a classification task, a teacher might assign the following probabilities to an image:

    1. cat: 0.80, dog: 0.15, tiger: 0.05

    This distribution provides more transferable information than a single cat label because it reveals semantic relationships among the classes.

    2.2 Temperature and the Loss Function

    Distillation usually introduces a temperature parameter, (T), to control how smooth the soft labels are. A larger (T) produces a smoother probability distribution, while a value approaching 1 produces a distribution closer to the original model output.

    The training objective generally contains two components:

    • Soft loss: The divergence between the student’s output distribution and the teacher’s soft targets, such as KL divergence.
    • Hard loss: The cross-entropy loss between the student’s output and the ground-truth label.

    A typical objective is:

    1. total_loss = alpha * soft_loss + (1 - alpha) * hard_loss

    Here, alpha controls the weight of the soft targets, while T is used to scale the teacher and student logits. In practice, the soft loss is often multiplied by (T^2) to compensate for changes in gradient scale caused by temperature scaling.

    The following conceptual pseudocode is independent of any specific training framework:

    1. teacher = load_pretrained_teacher()
    2. student = init_small_student()
    3. for batch in training_data:
    4. x, hard_label = batch
    5. with no_grad():
    6. teacher_logits = teacher(x)
    7. student_logits = student(x)
    8. soft_loss = kl_divergence(
    9. softmax(teacher_logits / T),
    10. softmax(student_logits / T)
    11. ) * T * T
    12. hard_loss = cross_entropy(student_logits, hard_label)
    13. total_loss = alpha * soft_loss + (1 - alpha) * hard_loss
    14. update_student(student, total_loss)

    Classic distillation assumes that the teacher’s logits are available. When a generative model is exposed through an API, external callers typically receive only the final text rather than the internal logits. As a result, real-world distillation attacks usually rely on output-level distillation or imitation learning.

    In this approach, the attacker treats the target model’s text responses as teacher signals and uses them for supervised fine-tuning. With enough samples, the attacker may also attempt to estimate aspects of the target model’s output distribution.

    2.3 Characteristics of Output-Level Distillation

    Output-level distillation for generative models differs significantly from traditional classification distillation:

    • Traditional distillation can obtain a complete probability vector with high information density.
    • Output-level distillation usually obtains sampled text, which is discrete and lossy.
    • Attackers therefore need more data and more diverse prompts to cover the teacher’s capability boundaries.
    • Attackers may attempt to induce the model to reveal reasoning chains or intermediate thought processes, seeking richer signals than the final answer alone.

    A distillation attack is therefore not simply a matter of “asking the model many questions.” It is a complete workflow involving prompt engineering, data collection, data cleaning, model fine-tuning, and performance evaluation.

    3. The Distillation Attack Workflow

    A typical distillation attack can be divided into five stages.

    3.1 Target Reconnaissance

    The attacker first identifies the target model’s capability boundaries, input and output formats, interface restrictions, and pricing rules. Reconnaissance may examine:

    • Which task types the model supports, such as code generation, summarization, vulnerability analysis, and mathematical reasoning.
    • The maximum context length and whether multi-turn conversations are supported.
    • Whether the service returns reasoning traces or intermediate states.
    • Whether it uses rate limits, content safety filters, or anomaly detection.
    • How different input styles affect the output distribution.

    This phase is often performed through a small number of distributed requests, making it less likely to trigger bulk-abuse protections.

    3.2 Data Collection

    Data collection is the core of the attack. The attacker creates a large prompt set covering different domains, difficulty levels, languages, and output formats. The prompts may come from public datasets, synthetic templates, or manually designed examples.

    Automated scripts may then issue large numbers of requests using multiple accounts, proxy IP pools, and dynamically adjusted request intervals.

    In publicly discussed incidents, a single campaign may involve more than one hundred thousand prompt requests. These requests are usually not random. They tend to be highly concentrated, templated, and persistent.

    Attackers may also submit multiple rewrites of the same task to obtain different versions of a response and increase the diversity of the eventual training set.

    3.3 Data Cleaning and Augmentation

    Raw collected data is not always suitable for training. Attackers may process it by:

    • Filtering refusals, safety blocks, malformed responses, and empty outputs.
    • Removing duplicates while retaining responses with higher information value.
    • Reorganizing multi-turn conversations so the substitute model can learn the same dialogue format.
    • Extracting reasoning chains or internal system prompts as additional training targets.
    • Splitting the data by task type, training multiple specialized models, and combining them into a larger system.

    3.4 Substitute-Model Training

    Once enough input-output pairs have been collected, the attacker can train a substitute model. This is an imitation-learning process: given the same input as the target model, the substitute is trained to produce a similar response.

    The training objective may use sequence-likelihood maximization or a reinforcement-learning reward designed around generation quality.

    The following pseudocode illustrates the process from the attacker’s perspective:

    1. dataset = []
    2. for prompt in massive_prompt_set:
    3. response = target_model_api(prompt)
    4. if is_usable(response):
    5. dataset.append({
    6. "prompt": prompt,
    7. "response": response
    8. })
    9. student = init_student_model()
    10. for batch in dataset:
    11. loss = imitation_loss(student, batch)
    12. update_student(student, loss)

    If the target service exposes separable reasoning blocks, an attacker may store those blocks together with the final answers and use them to train the substitute model to reproduce similar reasoning paths. This can make the substitute resemble the target not only in its answers but also in its problem-solving behavior.

    3.5 Evaluation and Iteration

    Attackers typically create an evaluation set to compare the substitute model with the target. If the substitute performs poorly on a particular task, the attacker may:

    • Collect additional prompts for that task.
    • Adjust the sampling temperature or prompt style.
    • Increase the model size or the number of training epochs.
    • Use multiple teacher models for ensemble distillation.

    This process can be repeated until the substitute reaches an acceptable level in the target business scenario.

    4. Common Variants of Distillation Attacks

    Distillation attacks can take several forms.

    4.1 Chain-of-Thought Distillation

    In chain-of-thought distillation, the attacker attempts to induce the target model to produce step-by-step reasoning and then includes that reasoning in the training data.

    Compared with learning only final answers, the substitute model may learn deeper problem-solving strategies. This is one reason some model providers bind reasoning blocks to the conversation context that produced them. If reasoning blocks cannot be exported independently, it becomes more difficult to collect high-value reasoning data at scale.

    4.2 Inducing Internal Mechanisms

    Attackers may construct carefully designed prompts intended to reveal system prompts, safety policies, internal tool descriptions, or model identity information.

    Once collected, this information can be used not only to train a substitute model but also to bypass safety controls and extract additional capabilities.

    4.3 Segmented Multi-Task Extraction

    A single substitute model may have difficulty covering all of the target model’s capabilities. Attackers may therefore divide the extraction process into task-specific segments.

    For example, one prompt set may focus on code generation, another on text rewriting, and another on security analysis. The resulting specialized models can then be combined through a routing layer to form a broader system.

    4.4 Industrial-Scale Distillation

    When a commercial organization uses distributed infrastructure, large-scale data pipelines, and continuous training systems to conduct the activity, the behavior may be described as industrial-scale distillation.

    The goal is often to reproduce an entire commercial model service, significantly shortening development cycles and reducing research costs. At this scale, the activity goes beyond ordinary research and may become a dispute involving breach of contract or unfair competition.

    5. Risks and Compliance Concerns

    5.1 Commercial Risks for Model Providers

    The direct consequence of a distillation attack is the indirect replication of the provider’s research and development investment. The cost of a large model includes much more than compute. It also includes data collection, data cleaning, alignment, safety evaluation, and continuous engineering work.

    Through distillation attacks, competitors may bypass much of this investment and obtain a functionally similar substitute at a substantially lower cost. This can put pressure on the original provider’s margins and competitive position.

    From a contractual perspective, most model service terms prohibit automated scraping, bulk generation, and the use of outputs to train competing models.

    Violations may result in account suspension, service termination, or claims for damages. From an intellectual-property perspective, whether model outputs are protected by copyright or qualify as trade secrets remains a matter of ongoing legal debate. Under unfair-competition principles, systematic extraction and imitation may be characterized as free-riding.

    5.3 Disputes Over the Technical Boundary

    Knowledge distillation itself is technically neutral. Legitimate distillation can be used for model compression, cross-architecture transfer, private deployment, research, and education.

    The key questions are scale and intent. A person using a small number of model outputs for individual study is fundamentally different from a commercial organization conducting millions of automated requests to train a competing model.

    Distillation attacks should therefore not be understood as a reason to reject distillation technology in general. The analysis should focus on the scale, purpose, methods, and contractual terms surrounding the activity.

    6. A Six-Layer Defense Strategy

    Model providers should not rely solely on service terms. Effective protection requires defense in depth across six layers: contracts, access, outputs, reasoning, auditing, and model strategy.

    6.1 Contract Layer: Clear Prohibitions

    Terms of service establish the first legal boundary. They should clearly prohibit:

    • Automated or programmatic access to the model service.
    • Bulk extraction, mirroring, copying, or caching of model outputs.
    • Using outputs to train a competing model.
    • Reverse engineering, bypassing restrictions, or probing internal mechanisms.
    • Violations of specified remedies and evidence-preservation requirements.

    Terms alone cannot stop an attack, but they provide a foundation for technical enforcement and later dispute resolution.

    6.2 Access Layer: Rate Limits, Quotas, and Risk Detection

    The access layer is the first technical gate. Common controls include:

    • Request-rate limits based on accounts, IP addresses, and device fingerprints.
    • Dynamic quotas based on user level.
    • Automatic blocking of unusually high-concurrency traffic.
    • Detection of proxy IP pools and account-rotation patterns.
    • Risk controls during registration, authentication, and API key issuance.

    The central challenge is distinguishing legitimate high-volume usage from malicious bulk collection. Normal business traffic generally has more variation in user behavior, task types, and timing. Distillation attacks tend to be highly templated, repetitive, stable in concurrency, and persistent over long periods.

    6.3 Output Layer: Perturbation, Watermarking, and Truncation

    Output-layer controls directly affect the quality of data available to an attacker. Possible measures include:

    • Embedding imperceptible watermarks so collected data contains traceable markers.
    • Applying randomized perturbations or rounding to reduce the direct reuse value of individual outputs.
    • Limiting maximum output length to avoid exposing excessive reasoning content in a single response.
    • Blocking or degrading responses for sensitive capabilities.
    • Producing varied outputs for identical or similar inputs to make automated data cleaning more difficult.

    The goal is not to make the service unusable for normal users. It is to make automatedly collected data less reliable, less complete, or more difficult to attribute.

    6.4 Reasoning Layer: Context Binding and State Isolation

    Reasoning-layer defenses have become increasingly important. The central idea is to bind intermediate states, reasoning blocks, or chains of thought to the conversation context in which they were generated.

    Possible designs include:

    • Preventing reasoning blocks from being exported independently of the original session.
    • Preventing later requests from referencing intermediate states from other requests.
    • Making reasoning blocks non-reproducible when a context is copied into a new session.
    • Detecting suspicious cross-session concatenation or state migration.

    These measures increase the difficulty of collecting reasoning traces at scale and reduce the consistency of datasets assembled from many independent requests.

    6.5 Audit Layer: Logging, Monitoring, and Traceability

    The audit layer is essential for detection and evidence collection. A model provider should maintain comprehensive logs covering:

    • Input and output summaries, model versions, and inference latency for each request.
    • User identifiers, IP addresses, device fingerprints, and session relationships.
    • Request patterns, timestamps, and token consumption.
    • Whether security policies or rate-limit rules were triggered.

    Logs, monitoring alerts, and anomaly-detection algorithms can help identify signals such as:

    • An account’s QPS is far above the normal business baseline.
    • Prompt distributions are strongly templated.
    • Large numbers of requests originate from the same proxy IP range.
    • Outputs are downloaded systematically, continuously, and in bulk.
    • Request sequences contain many synonymous rewrites or minor variations.
    • Different sessions show frequent cloning-like behavior.

    These signals support both operational response and later legal or contractual enforcement.

    6.6 Model Strategy Layer: Capability Segmentation and Release Governance

    Model-level defense follows the principle that all capabilities should not be exposed at once. Strategies may include:

    • Placing high-risk capabilities behind separate interfaces with higher permission requirements.
    • Using phased model releases so that compromise of one version does not affect the entire service.
    • Injecting model watermarks during training so distilled substitutes contain detectable characteristics.
    • Providing different inference precision or context lengths to different user groups.
    • Updating model behavior periodically to increase the cost of keeping distilled data current.

    This layer must be coordinated closely with business operations to balance security and user experience.

    7. Implementation and Operational Guidance

    For model providers, distillation defense should not be a one-time configuration task. It should become a continuous operational loop:

    1. Establish a security baseline and define normal user behavior.
    2. Integrate access control, rate limiting, logging, and alerting into the API gateway layer.
    3. Update detection rules when new large-scale anomalous patterns emerge.
    4. Review incidents regularly and improve output perturbation and model-release strategies.
    5. Keep contractual terms, privacy policies, and service documentation aligned with current controls.

    For model users, the boundaries should be understood clearly. Not every use of model outputs for learning constitutes a distillation attack. Limited sampling for personal research will generally have a different character from bypassing normal interfaces, using automation to generate massive volumes of requests, and training a commercial model with similar capabilities.

    Users should obtain data through official bulk-access mechanisms or seek appropriate research authorization where available. This can reduce the risk of violating service terms.

    In cloud deployments, model providers can store tamper-resistant audit logs in object storage, use logging services for full-text or structured search, and apply monitoring alerts to respond to abnormal QPS, error rates, and request patterns in real time.

    Baidu AI Cloud similarly emphasizes coordinated governance across contracts, access, outputs, reasoning, and auditing rather than relying on a single defensive control.

    8. Conclusion

    A distillation attack is an abusive application of knowledge distillation. Its defining feature is not distillation itself, but the large-scale, automated, and commercial transfer of a target model’s capabilities into a substitute model.

    Understanding these attacks requires both a clear grasp of distillation principles and a systematic approach to API access control, output protection, and auditability.

    For developers, the key lesson is not to treat a model service as merely a black-box endpoint. Every request, output, and reasoning segment should be included in the security governance scope.

    Only by combining contractual restrictions, technical controls, and continuous operational monitoring can providers effectively reduce the commercial and legal risks associated with distillation attacks.