AI Model Distillation Attacks: How to Detect Anomalous API Calls and Defend Against Model Extraction

    This article examines a security report in which a model provider accused several AI companies of running large-scale "distillation attacks" against its commercial model service. It untangles three concepts that are often conflated—knowledge distillation, model extraction, and the non-standard term "distillation attack"—and explains which behaviors are genuinely anomalous versus which are legitimate. From there it covers how providers detect and block abusive calls through identity controls, content fingerprinting, resource-consumption analysis, composite risk scoring, and forensic evidence retention, along with ways to reduce the payoff of being distilled. It closes with practical guidance for enterprises on obtaining high-quality training signals through compliant channels. The core takeaway: distillation itself is not the problem—what matters is whose data you use, how you obtain it, and what you use it for.

    1. The Incident: Starting from “Distillation Attacks”

    According to public reports, an overseas large-model provider published a security report accusing three AI model developers of using automated scripts and cloud infrastructure to carry out so-called “distillation attacks” against its commercial model service. The report claimed that the parties used large numbers of fake accounts and proxy services to bypass its authentication and anomaly-detection mechanisms, obtaining model outputs at scale to train and develop their own models.

    1.1 Call Volume and Targets

    The three named companies differed by nearly three orders of magnitude in interaction volume—roughly 90x between the smallest and largest.

    • Company A: The report claimed over 150,000 interactions, targeting “general-purpose multi-task reasoning,” including having the model score candidate answers against a standard to act as a reward model in reinforcement learning.
    • Company B: The report claimed over 3.4 million interactions, aimed at “scoring tasks based on rubrics,” again involving a reward-model scenario.
    • Company C: The report claimed over 13 million interactions. Beyond scoring tasks, this included generating compliant alternative phrasings for policy-sensitive queries that met the provider’s content-moderation requirements.

    The report also stated that all three companies targeted the provider’s most differentiated core capabilities: agentic reasoning, tool calling, and code generation.

    1.2 The Two Categories of Evidence Cited

    • Network side: Different accounts generated synchronized traffic within similar time windows and shared payment methods and operating hours.
    • Request side: The size, structure, and intent of prompts differed markedly from those of ordinary users. The report specifically noted that some requests explicitly asked the model to lay out its internal reasoning step by step.

    1.3 How to Read This Report Rationally

    • It is a one-sided accusation: The conclusions come from the provider alone. Whether accounts were fake or funding came from a common source requires the platform to present more complete forensic material; whether the accused parties respond, and how the case develops, should be followed over time.
    • Intent cannot be judged from behavior alone: Open models can also be called in bulk—for evaluation, benchmarking, or academic research. Without the terms of service and authorization context, inferring motive from behavior alone is prone to overgeneralization.
    • “Reward model” is ambiguous: In academic usage, a “reward model” usually refers to a scoring model trained on human-preference data—for example, training a Bradley-Terry preference model on comparison data, which a reinforcement-learning algorithm then uses to optimize a policy model. Reinforcement learning divides into two categories by feedback source:

      • Model-free methods based on environmental reward signals, which do not need a reward model;
      • Methods based on learned preference scores, which do require a reward model.

      In the RLHF pipeline, the scoring model is the reward model. The practice the report describes—using another party’s closed model to score candidate outputs and provide preference signals for one’s own reinforcement learning—is entirely different from “training a reward model of one’s own.” Clarifying this keeps the discussion from staying at the level of a sensational headline.

    Notably, the most contested of the three cases is Company C. Its interaction volume was roughly 90x that of Company A, and its target capabilities extended from reasoning and scoring into the safety-alignment layer. Company C is itself a model vendor that markets such alignment and safety policies as a selling point. The next section breaks these allegations down layer by layer, examining the underlying technical mechanics and how the provider detected them.

    2. Clarifying the Concepts: Knowledge Distillation, Model Extraction, and “Distillation Attacks”

    To judge whether the dispute holds up, start by separating three concepts that are often used interchangeably.

    2.1 Knowledge Distillation: A Classic and Legitimate Training Method

    Knowledge distillation was introduced by Hinton et al. in 2015. The core idea is to have a student model learn the “soft labels” produced by a teacher model—the class probability distribution. Compared with “hard labels” that give only the correct answer, soft labels also carry the teacher’s judgment about the relative merits of each candidate answer, the so-called “dark knowledge.” During training, a temperature coefficient T softens the distribution, and KL divergence measures the gap between the student’s and teacher’s outputs:

    1. import torch
    2. import torch.nn.functional as F
    3. def distillation_loss(student_logits, teacher_logits, labels, T=2.0, alpha=0.5):
    4. """Knowledge distillation loss: soft-label distillation term + hard-label cross-entropy term (illustrative implementation)"""
    5. # Temperature scaling: a larger T smooths the distribution and transfers more of the teacher's "dark knowledge"
    6. soft_student = F.log_softmax(student_logits / T, dim=-1)
    7. soft_teacher = F.softmax(teacher_logits / T, dim=-1)
    8. # KL divergence measures the gap between student and teacher distributions; multiply by T^2 to compensate for gradient scale
    9. kd_loss = F.kl_div(soft_student, soft_teacher, reduction="batchmean") * (T * T)
    10. # Cross-entropy on the true labels keeps the student from drifting away from the task
    11. ce_loss = F.cross_entropy(student_logits, labels)
    12. return alpha * kd_loss + (1 - alpha) * ce_loss

    Data distillation is its extension into natural language processing. A larger teacher model generates labels for a large set of unlabeled samples, which are then used to train a smaller model, reducing labeling cost. As long as the teacher model is your own, or its outputs are authorized, this is standard practice.

    2.2 Model Extraction: Model Theft via Queries

    Model extraction refers to attackers treating the target model as a “black-box oracle,” using carefully designed inputs to obtain outputs in bulk, and then using those input-output pairs to replicate a functionally similar stand-in model. Research on this had been systematized by around 2016:

    • For traditional models such as logistic regression, support vector machines, and decision trees, only a small number of queries are needed to replicate them with high fidelity;
    • For deep neural networks, decision boundaries can be reconstructed even with labels for just 1% of the training data;
    • For natural language models, researchers have replicated word embeddings through query access to a modified API.

    Its harm extends beyond the model itself:

    • Model theft: A replicated model can be used to circumvent licensing, or even resold for profit.
    • Transferable adversarial examples: A stand-in model trained on large-scale real queries can generate many adversarial examples that fool the original model, directly threatening its security.
    • Membership inference and training-data extraction: Related techniques have been used to determine whether a given record was in the target model’s training set, or to coax the model into reciting memorized training data verbatim.

    2.3 “Distillation Attack”: A Term That Does Not Really Exist in Academia

    “Distillation attack” is not an established academic term, but a phrase coined by a security report for communicative effect. It bundles the legitimate training method of knowledge distillation together with the offensive practice of model extraction, implying that “using a distillation method equals mounting an attack.” The two should be evaluated separately:

    Dimension Knowledge Distillation Model-Extraction Distillation
    Purpose Compress model size while retaining as much capability as possible Cheaply replicate another party’s model capability
    Teacher source Owned or authorized models Usually unauthorized
    Acquisition method Directly read the teacher model’s output distribution Large-scale, detection-evading API queries
    Assessment General-purpose ML method Must be analyzed case by case against terms of service and law

    A more accurate statement is therefore: knowledge distillation itself is beyond reproach; the real issue is how the distillation data is obtained and used. Evaluating the dispute comes down to four things—evidence, authorization, purpose, and attribution.

    3. Layer-by-Layer Breakdown: What Exactly Is “Abnormal” About the Alleged Behavior

    3.1 Large-Scale Calls: Cloud Infrastructure as an Invisibility Cloak

    Using cloud infrastructure for data collection is not unusual—crawlers, data acquisition, and offline evaluation all rely on it. What matters is whether three elements are present simultaneously:

    • Scale: Interaction volume far exceeds what legitimate business needs require;
    • Identity forgery: Batch registration, shared payment information;
    • Active evasion: Use of proxies, synchronized traffic.

    When all three stack up, the nature of the behavior shifts from “collection” to “evasion”—and that is precisely the dividing line for a compliance judgment.

    Estimating from the report’s figures, Company C’s reported 13 million interactions, averaged across early 2024, 2025, and 2026, come to roughly 180,000 per month or about 8,000 per business day. Given that cloud services scale elastically with resource usage, this volume requires only a small amount of infrastructure yet can sustain request pressure far above that of an ordinary user.

    3.2 Request-Side Profiling: Normal Traffic Does Not Mean Normal Behavior

    Traditional WAFs and rate limiters mainly target HTTP-layer attacks such as SQL injection and CC floods. They typically cannot catch requests that are “syntactically valid but semantically anomalous.” Detecting the latter requires extracting four categories of features from request content.

    Feature 1: Extremely long context, extremely high density.

    Normal conversations tend to be multi-turn short messages, whereas distillation-style calls concentrate in single-turn long prompts. A typical self-distillation prompt may contain the following parts:

    1. A system prompt describing the role and task;
    2. A batch of input samples spanning multiple domains;
    3. A format constraint requiring the model to output structured results item by item (e.g., JSON).

    A single request may contain dozens or even hundreds of samples to process. This is done for two reasons:

    • To cover more task types in a single request;
    • To amortize the fixed system-prompt tokens consumed on each call.

    Such requests show markedly higher average input length and input-to-output token ratios than normal sessions—a strong signal for identifying “batch production” behavior.

    Feature 2: Templated, systematic task organization.

    If requests from the same entity repeatedly show a fixed field structure, stable enumerated values, and a similar task distribution, it indicates execution of a predefined production pipeline rather than a human asking questions. You can compute pairwise similarity between request prompts (e.g., cosine similarity) or use clustering to observe concentration. Similarly, the “completion-type requests” from AI coding assistants exhibit comparably high templating.

    Feature 3: Severe mismatch between task type and account profile.

    A newly registered account with no history suddenly issuing a large batch of high-quality code requests, or showing broad multi-language, multi-domain coverage, does not match the distribution of a typical individual user. Rather than inspecting individual requests one by one, it is better to judge the entity profile as a whole.

    Feature 4: Targeted probing of alignment and safety policies.

    This is the category that warrants the most caution. It usually takes two forms:

    • Inductive: Systematically collecting answers to a class of questions in order to statistically map the model’s refusal boundaries;
    • Coverage-based: Constructing large numbers of question variants to find phrasings that bypass refusal policies.

    The latter specifically probes content-safety boundaries. If these results are then used to train a student model, it effectively copies over the know-how of “how to bypass safety mechanisms.” Safety alignment is meant to let a model reliably refuse harmful requests; training on this kind of data instead amplifies and hardens the evasion techniques. The “generating alternative phrasings for policy-sensitive queries” that Company C was accused of essentially falls into this direction. Its content-safety implications are more concerning than having capabilities replicated.

    3.3 Attribution: How “Synchronized Traffic + Shared Payment” Gets Reconstructed

    The report claims it can attribute behavior to specific labs with “high confidence,” based mainly on four grounds:

    1. IP address correlation;
    2. Request metadata;
    3. Infrastructure characteristics;
    4. Corroboration from industry partners.

    From an engineering standpoint, this is typically a path where weak signals stack into a strong one:

    • Network layer: The same IP range or autonomous system number (ASN), with highly synchronized request timing.
    • Account layer: Similar registration templates, the same payment channel, closely spaced token-issuance times.
    • Behavior layer: Consistent prompt fingerprints, consistent task distributions, consistent call cadence (e.g., fixed working hours, batch intervals).
    • Intelligence layer: External evidence such as security-vendor reports and peer tips.

    Any of the first three signals, appearing alone, is insufficient to make a determination. Only when they produce a “cross-hit” within the same time window does the credibility of the conclusion rise significantly.

    Take “shared payment method” as an example: there are also legitimate scenarios on cloud platforms—centralized enterprise procurement, unified settlement through resellers, and multiple departments sharing a primary account. A provider’s internal payment or funding correlation for attribution also touches on payment compliance and the protection of personal financial information. Disclosing only the fact of a “shared payment method” is itself insufficient to make a determination. External observers usually see only the conclusion; verifying it requires a more complete evidence chain.

    4. The Defense Perspective: How Model Providers Detect and Block Anomalous Calls

    For a model provider, “detect—attribute—respond” should be built as a closed loop. The platform-security practices of cloud providers such as Baidu AI Cloud follow a similar approach: rather than relying on a single line of defense, they center on continuous detection and response.

    4.1 Identity and Account Layer: Raising the Cost of Forgery

    • Real-name or enterprise verification; tiered registration;
    • Centralized screening of high-risk registration information (e.g., bulk-generated emails);
    • Merging quota accounting for accounts linked to the same payment entity;
    • Call cooldown periods and gradual quotas for new accounts.

    The identity layer is foundational. If accounts can be obtained cheaply in bulk, all subsequent detection will be bypassed.

    4.2 Content Fingerprint Layer: Identifying Prompt Reuse

    For each request, extract a prompt fingerprint along the following dimensions:

    • SimHash of character n-grams;
    • Embedding vectors;
    • Instruction-template regexes;
    • Co-occurrence of key task terms.

    Then compare the new request against historical ones. If the same template recurs, it can be judged as automated production. It bears emphasizing that templating does not equal a violation. Coding assistants’ completion requests, bulk document processing, and regression testing are all highly templated, so this signal should serve only as “scoring input” and must not directly trigger a ban.

    4.3 Resource-Consumption Layer: Identifying Abnormal Token Budgets

    Distillation-style calls show three distinct traits in token consumption:

    • Long input, stable output;
    • Strict output format (e.g., JSON);
    • Linear growth in per-account token consumption.

    By computing each account’s token usage and request frequency over a sliding window, the abnormal pattern of “stable output, sustained high yield” becomes visible.

    4.4 Composite Risk Scoring

    Any single signal, on its own, may “harm” legitimate users by mistake. The practical approach is to weight multiple signals into a single risk score, then dynamically adjust it based on historical credit:

    1. from collections import deque
    2. import time
    3. class AccountRiskScorer:
    4. """Account-level composite risk scoring (illustrative implementation; weights need to be calibrated against business data)"""
    5. def __init__(self, window_sec=3600):
    6. self.window = window_sec
    7. self.events = {} # account_id -> queue of event timestamps within the sliding window
    8. def _prune(self, account_id, now):
    9. q = self.events.setdefault(account_id, deque())
    10. while q and now - q[0] > self.window:
    11. q.popleft()
    12. return q
    13. def update(self, account_id, prompt_tokens, output_tokens, style_score):
    14. """style_score is the average similarity between the request and historical templates, in the range 0~1"""
    15. now = time.time()
    16. q = self._prune(account_id, now)
    17. q.append((now, prompt_tokens, output_tokens, style_score))
    18. n = len(q)
    19. avg_in = sum(e[1] for e in q) / n
    20. avg_style = sum(e[3] for e in q) / n
    21. # Split the window evenly by time and compute the ratio of requests in the first half to the second half
    22. mid = q[0][0] + (q[-1][0] - q[0][0]) / 2
    23. first_half = sum(1 for e in q if e[0] < mid)
    24. burst = (n - first_half) / max(first_half, 1)
    25. score = (
    26. 0.25 * min(avg_in / 2000.0, 1.0) # abnormal input length
    27. + 0.20 * avg_style # template similarity
    28. + 0.15 * min(burst / 5.0, 1.0) # burst concurrency
    29. + 0.20 * min(n / 500.0, 1.0) # high-frequency calls
    30. )
    31. return round(min(score, 1.0), 3)

    4.5 Attribution and Forensics: Retaining an “Evidence Chain”

    Once a risk score crosses the threshold, the system should fully preserve the evidence needed for forensics:

    1. Generate a globally unique request ID for each request, recording fields such as account, token, IP, ASN, TLS fingerprint, timestamp, token count, and template fingerprint.
    2. Write evidence centrally to tamper-resistant logging services. A common cloud practice is to deliver logs to object storage with versioning and compliance-retention policies enabled, for later traceability.
    3. Treat “behavior score → response action → human review → appeal result” as an event stream that is decoupled via a message queue and handed to downstream response services. Each action forms an auditable closed loop, avoiding harm to legitimate customers from misjudgment.

    4.6 Defensive Output: Reducing the Payoff of Being “Distilled”

    Detection and response are forms of passive defense; it is also worth reducing the payoff of a model being copied at the source:

    • Perturbed outputs: Apply reasonable constraints on sampling parameters such as temperature and top-p and on output length, reducing the chance that per-token probabilities can be precisely tallied.
    • Output fingerprinting: Apply a subtle watermark to generated text (e.g., a green-list/red-list word-table watermark) to enable traceability without noticeably affecting readability.
    • Capability tiering: Do not expose differentiated capabilities through low-priced bulk endpoints; instead, provide them in tiers by verification level and call quota.
    • Contract terms: Explicitly prohibit “using outputs to train a competing model” in the service agreement, and reserve audit rights.

    It should be viewed objectively that these measures can only raise the attacker’s cost; they cannot eliminate extraction behavior entirely.

    5. The Enterprise Perspective: How to Legitimately Improve Model Capability

    For an AI model developer, the truly valuable question in this dispute is not “how to evade detection” but “how to obtain high-quality training signals through compliant means.” This can be approached along two paths.

    5.1 Use an Owned or Authorized Teacher Model

    Data distillation is fully controllable technically. As long as the teacher model is your own, or its outputs are authorized, you need only address three concerns—cost, quality, and data compliance:

    1. First, evaluate the teacher model’s quality on a small human-labeled set to confirm acceptable accuracy on the target task, avoiding “distilling noise into the student”;
    2. Apply “confidence filtering”: keep only high-confidence samples from the teacher’s outputs;
    3. Cross-validate teacher outputs against human-reviewed results before deciding whether to ingest them.

    5.2 Replace a “Borrowed Reward Model” with Reinforcement Learning

    When an owned model needs further improvement, verifiable rewards can replace dependence on an external model:

    • Code tasks: run unit tests;
    • Math tasks: check the answer;
    • Tool calling: verify that execution results match expectations.

    In addition, a reward model can be trained on your own base model using human-preference data. Using open-source models as teachers for data distillation is also common industry practice, but the license terms must be observed—especially restrictions concerning “using outputs to train other models.”

    5.3 An Example: An Inference Client That Refuses “Unauthorized Channels”

    Many teams use a “model routing layer” to schedule different models uniformly. This routing layer is precisely the boundary between compliance and risk. Here is a minimal example:

    1. import hashlib
    2. import json
    3. import os
    4. import time
    5. import urllib.request
    6. class ModelRouteClient:
    7. """Only accesses authorized model services and keeps auditable call records"""
    8. ALLOWED_HOSTS = {"api.example-corp.com"} # only allow authorized service endpoints
    9. AUDIT_LOG = "model_calls_audit.jsonl" # call audit log
    10. def __init__(self, endpoints, api_keys):
    11. # Endpoints and keys are injected via environment variables or a secret manager, never hard-coded
    12. self.endpoints = {k: v for k, v in endpoints.items()
    13. if self._host(v) in self.ALLOWED_HOSTS}
    14. self.api_keys = api_keys
    15. @staticmethod
    16. def _host(url):
    17. return url.split("://", 1)[-1].split("/", 1)[0]
    18. def chat(self, model, messages, **kwargs):
    19. if model not in self.endpoints:
    20. # Reject unauthorized models outright so requests are never "routed" to an unauthorized channel
    21. raise PermissionError(f"Model {model} is not in the authorized list")
    22. url = self.endpoints[model]
    23. key = self.api_keys[model]
    24. body = json.dumps({"model": model, "messages": messages, **kwargs}).encode()
    25. req = urllib.request.Request(
    26. url, data=body,
    27. headers={"Content-Type": "application/json",
    28. "Authorization": f"Bearer {key}"})
    29. with urllib.request.urlopen(req, timeout=60) as resp:
    30. reply = json.loads(resp.read().decode())
    31. # Record the request fingerprint and a response digest for later auditing and deduplication
    32. fingerprint = hashlib.sha256(body).hexdigest()
    33. record = {"ts": time.time(), "model": model,
    34. "prompt_sha256": fingerprint,
    35. "reply_sha256": hashlib.sha256(
    36. reply["choices"][0]["message"]["content"].encode()
    37. ).hexdigest()}
    38. with open(self.AUDIT_LOG, "a", encoding="utf-8") as f:
    39. f.write(json.dumps(record, ensure_ascii=False) + "\n")
    40. return reply

    In practice, three additional constraints should be added:

    1. Global quota and rate limiting: Implement a token bucket at the routing layer, constraining the call budget per team and per task.
    2. Input filtering: Block batch prompts that involve circumventing safety policies, preventing requests that “batch-generate to bypass moderation” from flowing out internally.
    3. Data classification: Prioritize processing high-value data with privately deployed owned models or through authorized dedicated channels.

    This incident is only a microcosm of large-model competition entering deeper waters. Model capabilities can be distilled, and terms of service can be circumvented, but compliance, security, and trust cannot be “distilled.” Here are three recommendations each for three types of participants.

    For model providers

    1. Replace single-point detection with “baseline + risk scoring + human review” to reduce the false-positive rate.
    2. When publishing security reports externally, disclose the evidence chain and appeal channels at the same time so they can withstand technical scrutiny.
    3. Provide controlled channels for legitimate high-value scenarios (e.g., enterprise evaluation, academic research) to reduce the motive to “take a detour.”

    For model developers

    1. Build training-data provenance as compliance infrastructure: teacher models owned or authorized, data pipelines traceable, licenses reviewed clause by clause.
    2. Do not use “alignment” as a name for what is actually “de-alignment.” Systematically training on another party’s model responses to produce “alternative phrasings” ultimately erodes the entire industry’s security foundation.
    3. Invest resources in your own base model and original data—this is more sustainable than chasing short-term capability catch-up.

    For developers

    1. Before calling any closed-model service, first read its terms of service regarding “output usage” and “distillation prohibitions.”
    2. When distillation is needed, prefer open-source models that explicitly permit commercial use as teachers.
    3. Maintain call audit logs so that every model call is traceable.

    Returning to the opening question: distillation itself is not the problem—the problem is “whose data, obtained in what way, for what purpose.” Answer these three questions clearly, and the dispute will naturally arrive at an answer that holds up to scrutiny.