Detecting and Defending Against Distillation-Style Capability Extraction from Large Language Models
This article examines distillation-style capability extraction against large language models, where an attacker uses open APIs as a black-box oracle to harvest inputs and outputs and train a competing student model. It breaks down the four-stage attack chain, presents a three-layer detection framework of behavioral, content, and relationship signals, and adds output-watermarking and canary techniques. It then lays out layered defenses spanning identity, quota, content, and legal controls, along with pseudocode for green-list watermarking and token-bucket rate limiting. Teams building AI applications on model APIs will find concrete detection metrics and a scalable detection pipeline, as well as the limits of each approach and the debate over whether API outputs can lawfully be reused to train competitors.
1. Background and Technical Characterization
A large-model provider recently disclosed that it had detected three AI labs using large numbers of accounts to carry out large-scale “distillation-style capability extraction” against its model, and it questioned whether this practice is compliant. This article focuses on detecting and defending against distillation-style capability extraction. It provides directly actionable content—attack-chain breakdown, detection metrics, watermarking schemes, and quota governance—to help teams building intelligent application services understand where the risk comes from and how to respond.
Debates about models being “distilled” have surfaced in the industry before, and the controversy usually comes down to one question: can the input and output data produced by calls to an open API be used directly to train a competing model?
To assess the impact objectively, it helps to separate two concepts:
- Knowledge distillation: A student model learns the probability distribution of the teacher model’s outputs (soft labels), approximating the teacher’s capability with fewer parameters. This is a common model-compression technique and does not, in itself, involve unauthorized access.
- Distillation-style capability extraction: The attacker treats the target model as a black-box oracle, batch-constructs inputs along the target capability dimension and collects the outputs, then trains its own student model on that data—gaining near-identical capability at a cost far below building its own model. In model-stealing research, this is typically treated as a query-based extraction attack.
The two look similar; the difference lies in authorization and boundaries. In academic research, this paradigm is widely used to compress models and cut inference costs. Once the target model is operated by someone else and the data comes from unauthorized bulk calls, the nature changes: it becomes an occupation of the service provider’s training assets and service capacity.
There is also a technical reality in the black-box setting: the attacker cannot obtain the model’s probability distribution and can only use text outputs as the supervision signal. This means that “capability” usually has to be accumulated through high-frequency, long-duration, large-scale, and distribution-concentrated sampling. A few exceptions exist: a small number of high-value outputs may be reused repeatedly, and memorization reproduction or boundary samples may also leak disproportionate information. Detection therefore cannot fixate only on “high frequency”—it must also account for low-frequency but high-value calls. The longer the attack chain, the more observable traces it generally leaves, and the wider the defender’s detection surface becomes.
2. Attack Chain: Four Stages and Their Observable Signals
Breaking distillation-style extraction into stages lets you find observable signals at each step, rather than banning accounts only after the fact.
2.1 Reconnaissance and Capability Positioning
The attacker first uses a small number of requests to confirm where the target model is strong—complex instruction following, long-context understanding, code generation, or tool calling—and picks discriminating benchmark questions as seeds.
- Defender’s view: A few probe requests are hard to characterize on their own, but seed questions often come from public benchmark sets or high-frequency knowledge Q&A. Such prompts tend to have “many restated variants and repeated original phrasings,” so features can be planted on the content side in advance.
2.2 Synthetic Corpus Batch Generation
Using the seed questions as templates, the attacker rewrites and expands them, then samples multiple responses per input across various temperature settings. Training corpora favor correct, consistently formatted outputs, so attackers tend to fix the output template and demand things like “return as JSON” or “code only.” Scaling up the corpus requires concurrency and automation—the most obvious source of traffic anomalies.
2.3 Student Model Training
The sampled results are cleaned and deduplicated for supervised fine-tuning. Some attackers also run rejection sampling: the student model first generates candidate answers, then the teacher model is called to filter or score them, keeping only the highest-quality samples. Rejection sampling makes the student issue high-frequency requests again when its performance is insufficient, forming a “performance plateau → request spike” loop. Since most base models generate text autoregressively, student models tend to reproduce the teacher’s word choices and sentence structures—which provides the basis for later output-side fingerprinting.
2.4 Iteration and Acceptance
The attacker keeps comparing gaps against benchmark sets and expanding the sampling scale. What the service provider sees is usually a simultaneous rise in the total number of accounts and request volume, with the same set of accounts using similar prompt templates over a long period.
| Stage | Core Goal | Primary Observable Signals |
|---|---|---|
| Reconnaissance | Determine target capability | Few high-precision prompts, public benchmark variants, output-structure preferences |
| Batch generation | Build training corpus | High-frequency short-interval requests, templated prompts, fixed output-format demands |
| Model training | Fit teacher behavior | Request spikes during plateaus, periodic patterns, absent day/night curve |
| Iteration | Close the gap | Account expansion, similar templates reused across accounts |
3. Detection Framework: Three Layers of Signals and Two Types of Fingerprints
3.1 Behavioral Layer: Statistical Features from Request Sequences
Human usage has clear work-rest rhythms, pauses, and randomness; automated sampling usually shows even intervals and steady concurrency. You can build rolling-window statistics per account:
# Pseudocode: account-level rolling window behavior featuresWINDOW_SECONDS = 10MAX_REQUESTS = 20 # Calibrate against business baseline to avoid false positives on legitimate bulk workloadsdef update_profile(account_id, req, now):w = windows[account_id]w.append((now, req))w.drop_older_than(now - WINDOW_SECONDS)if len(w) < MAX_REQUESTS:return LOW_RISKgaps = diff([t for t, _ in w]) # Inter-request intervalstemps = [r.temperature for _, r in w]lens = [len(r.messages[-1].content) for _, r in w]repeat = 1.0 - distinct_ngram_ratio([r.prompt for _, r in w], n=8)if (stdev(gaps) < 0.05 * mean(gaps) # Nearly evenly spaced intervalsand stdev(temps) < 0.01 # Fixed sampling parametersand stdev(lens) < 0.05 * mean(lens) # Highly consistent input lengthand repeat > 0.60): # High prompt-template repetitionreturn HIGH_RISKreturn LOW_RISK
The thresholds above are illustrative only; real values must be calibrated against the business baseline. Calibrate thresholds separately for bulk workloads, open APIs, and free tiers, and validate the false-positive rate with manually sampled cases. Human activity has clear day/night troughs, while a long-running script does not; for extremely high-frequency users on the free tier, close observation is also advisable.
| Metric | Suggested Observation | Risk Signal Example | Recommended Action |
|---|---|---|---|
| Window request volume | Requests per account within 10 s | Sustained 3× above baseline | Add verification or throttle |
| Request-interval stdev | Interval / mean | Very low coefficient of variation, near-uniform | Log and re-verify |
| Sampling-parameter stability | temperature, top_p, etc. | Fixed single configuration over time | Combine with source assessment |
| Template repetition rate | 8-gram dedup rate | Above 0.60 | Route to manual sampling queue |
| Format-constraint strength | Share of JSON / code-only | Significantly above the period average | Tag in output-side profile |
| Missing day/night curve | 24-hour request distribution | No trough, flat | Raise risk-score weight |
3.2 Content Layer: Prompt-Template Clustering and Intent Recognition
Normalize requests first: strip punctuation, lowercase, collapse whitespace, remove variable placeholders, then compute the fingerprint:
# Pseudocode: prompt normalization and template fingerprintimport rePLACEHOLDER = re.compile(r"\{\{.*?\}\}|\$\{.*?\}|<[^>]+>|\d+(?:\.\d+)?|\"[^\"]*\"|'[^']*'|`[^`]*`")def template_fingerprint(prompt: str) -> str:s = prompt.lower()s = PLACEHOLDER.sub("<X>", s) # Normalize variables, numbers, strings to placeholderss = re.sub(r"[\W_]+", " ", s) # Remove punctuation and whitespace differencesreturn " ".join(s.split()[:16]) # Use first 16 tokens as the template fingerprint
When the same template fingerprint appears frequently across many accounts, it forms strong correlation evidence. You can also measure “format-constraint strength”: an abnormal rise in the share of requests demanding strict JSON, fixed fields, or code-only usually means the output will be parsed programmatically and fed into a corpus.
Note that in Chinese, multilingual, or code scenarios, splitting only on whitespace may fail. A more robust approach is to first tokenize or normalize at the character level, then generate the template fingerprint; for code, extract the skeleton by token or syntactic structure. If you still split on whitespace, use it only for coarse filtering and back it up with manual sampling.
3.3 Relationship Layer: Account Graph and Association Propagation
A single account’s behavior is easy to disguise as a normal user. Build a graph with accounts, IPs, device fingerprints, payment identifiers, and registration email domains as nodes and edges, then use connected components or community detection to find groups of batch-registered, centrally controlled accounts:
# Pseudocode: account risk propagation based on shared features (two-hop diffusion)def propagate_risk(seeds, graph, decay=0.5, threshold=0.6, hops=2):score = {n: 1.0 for n in seeds}frontier = set(seeds)for _ in range(hops):nxt = {}for node in frontier:for nb, weight in graph.neighbors(node): # weight: number and strength of shared featuresif nb not in score:nxt[nb] = max(nxt.get(nb, 0.0), score[node] * decay * weight)for nb, s in nxt.items():if s >= threshold:score[nb] = sfrontier = set(nxt.keys())return score
Emphasize this: shared features such as IP and device are only supporting evidence and cannot be the sole basis for a penalty. Corporate egress points, campus networks, and home broadband can all cause collateral damage, so a risk score should only trigger stronger verification or manual review. Fields such as payment identifiers, email domains, and device fingerprints involve personal information; it is advisable to hash or de-identify them first, minimize retention, define clear access approvals and audit records, and set retention periods.
3.4 Output Watermarking: Statistical Detection
Embedding a statistical watermark in open-API outputs is a way to trace text provenance directly, without relying on account behavior. A typical approach:
- For each output position, use a hash of the already-generated prefix as the random source to split the vocabulary into a “green list” and a “red list.”
- During generation, modestly raise the probability of green-list tokens.
- During detection, measure the share of green-list tokens in the text. If the text truly comes from a watermarked model, that share will be significantly above the random level.
# Pseudocode: green-list watermark generation bias and significance detectionimport hashlibimport mathVOCAB_SIZE = 32000GAMMA = 0.5 # Green-list fractiondef split_key(prefix: str, pos: int) -> int:h = hashlib.sha256(f"{prefix}|{pos}".encode()).digest()return int.from_bytes(h[:4], "big") % VOCAB_SIZEdef logit_bias(prefix: str, pos: int, delta: float) -> dict:start = GAMMA * VOCAB_SIZE # Hash values in the first half are treated as green listkey = split_key(prefix, pos)# Add a bias to green-list token logits and lower red-list ones; delta controls watermark strengthreturn {tid: delta if (key + tid) % VOCAB_SIZE < start else -deltafor tid in range(VOCAB_SIZE)} # A real implementation only needs the subset of candidate tokensdef detect(text_tokens, prefixes, delta, z_threshold=4.0):# prefixes[i] must match the generation position of token iobs = 0for i, tid in enumerate(text_tokens):key = split_key(prefixes[i], i)if (key + tid) % VOCAB_SIZE < GAMMA * VOCAB_SIZE:obs += 1n = len(text_tokens)mean = GAMMA * nstd = math.sqrt(n * GAMMA * (1 - GAMMA))z = (obs - mean) / std if std > 0 else 0.0return z, z >= z_threshold
Three key constraints:
- The smaller δ is, the less impact on text quality—but the lower the detection sensitivity. You need to trade off against the quality requirements of the business.
- Because the perturbation depends on prefix-hash partitioning, paraphrase attacks such as rewriting and translation may erase it. The watermark is therefore better suited as supporting evidence than as the sole basis.
- Before detection, confirm that the text’s tokenization matches generation time, and that the
prefixeslist corresponds one-to-one with generation positions. Otherwise the green-list statistics will be distorted.
Watermark failure scenarios also include: translation or heavy rewriting, output truncation, tokenizer mismatch, insufficient sensitivity from a low δ, and abnormal green-list distribution from strict output-format constraints. Evaluate each before use.
3.5 Query Fingerprints and Canary Samples
For a very narrow set of obscure topics, a model can be steered to output a pre-planted, harmless, functionally inert marker string (a canary). If that string reappears in another model’s output, it becomes evidence of extraction. This technique applies only to a small, controlled sample set and should be treated only as supporting evidence, not extended broadly.
4. Defense Framework: Layered Governance Rather than Single-Point Blocking
Detection only surfaces the problem; governance must coordinate across four layers—identity, quota, content, and legal.
4.1 Identity and Quota: Token-Bucket Rate Limiting
# Pseudocode: token-bucket rate limitingimport timeclass TokenBucket:def __init__(self, capacity: float, rate: float):self.capacity = capacity # Bucket capacity, controls allowed burst sizeself.rate = rate # Tokens replenished per secondself.tokens = capacityself.updated = time.monotonic()def allow(self, need: float = 1.0) -> bool:now = time.monotonic()self.tokens = min(self.capacity,self.tokens + (now - self.updated) * self.rate)self.updated = nowif self.tokens >= need:self.tokens -= needreturn Truereturn False
For distributed deployment, the token-bucket state should live in a unified rate-limiting component—such as a centralized quota service, gateway-side shared state, or unified per-tenant metering—to avoid multiple instances each letting traffic through and the total spinning out of control. Quota design can be tiered: beyond a base allowance, requests are either billed at a higher cost or require manual approval, making large-scale sampling economically infeasible.
4.2 Output-Side Hardening
- Reduce sampling randomness for high-risk accounts: Output becomes more consistent, so the amount of information that can be fitted drops accordingly.
- Attach traceable identifiers to responses: Such as a request ID or a de-identified account digest. If it is later reproduced verbatim in an external model’s output, it becomes a starting point for forensics.
- Profile-annotate templated, format-restricted requests: These requests most warrant priority review.
4.3 Terms of Service and Evidence Retention
Technical measures must be paired with agreements. Terms of service should explicitly prohibit using outputs to train models that compete with the provider’s own service, and reserve the right to adjust quotas or suspend service when abuse is found. Meanwhile, account, time, request summaries, and response fingerprints need auditable logs retained to support later appeals, takedowns, and even legal proceedings. The completeness of the evidence chain often determines whether a dispute can ultimately be substantiated.
5. Engineering: A Scalable Detection Pipeline
- Collection layer: Log request metadata and response fingerprints uniformly at the API gateway; de-identify or hash-only sensitive body content per compliance requirements; define log sampling rates and access permissions.
- Feature layer: Use stream computing to complete window statistics, template clustering, and graph updates; write features to online storage for real-time decisions; design a feature-storage retention period.
- Decision layer: Run rules and models in parallel to score, output a risk level, and link to rate limiting, verification, and manual review; set a manual-review SLA.
- Response and feedback layer: Feed manual conclusions back as labeled samples, continuously calibrate thresholds, and track false-positive rates and appeal outcomes.
If the relevant service is built on Baidu AI Cloud, these layers can map to a common combination of cloud product categories:
- Log service: centrally search request metadata;
- Stream computing: complete real-time window statistics;
- Object storage: archive long-term audit logs;
- Monitoring and alerting: trigger threshold-based linkage.
The key is to build “traceability” into the design from day one, rather than backfilling data after the fact.
6. Takeaways for Model Users
For enterprises and independent developers, this has practical relevance:
- When building applications on open APIs, clarify the permitted use of API outputs to avoid being drawn into provenance disputes unintentionally;
- When choosing a provider, pay attention to its quota policy, terms of service, and data-handling disclosures;
- If you self-host open-source models, you also need output-side protection and call auditing to prevent your own fine-tuning results from being reverse-extracted.
7. Limitations and Outlook
Detection is fundamentally an attacker-defender game. Attackers can evade behavioral features by randomizing request intervals, diversifying templates, and rotating across accounts; defenders, in turn, must keep improving graph-association capability and the robustness of output fingerprints. Whether watermarks and query fingerprints hold up as valid evidence also depends on how heavily the output is rewritten and on the applicable legal environment.
The longer-term direction is “authorized capability reuse”: replacing uncontrollable black-box sampling with controlled model-output interfaces and auditable data-authorization mechanisms. Once the technical boundaries are clear, distillation is not necessarily a bad thing; the controversy stems more from “unauthorized mass replication.” For service providers, combining behavioral detection, content fingerprints, output watermarking, and contractual constraints is the pragmatic path to balancing an open ecosystem with intellectual-property protection.
