Generative memorization: ranks, repeats and what an audit can show
生成模型中的记忆与复现
Audit an artificial canary and separate exposure from sampling probability and privacy guarantees.
generative-memorizationA likely answer and a remembered record are different claims
A generator producing a familiar phrase has not automatically revealed a training record. A generator assigning unusually high likelihood to a deliberately inserted random string gives more specific evidence. The question needs a reference: which candidate space, which training intervention and which output similarity count?
The Secret Sharer studies artificial canaries and defines exposure through candidate rank. Diffusion extraction research uses a separate approximate definition for images, based on a distance threshold and training near-duplicates. These operational definitions support particular investigations; neither is a universal definition of privacy or a legal test. Read entropy and generative models first.
Rank depends on the comparison set
Consider M artificial equal-length candidate labels. A categorical model fitted to counts cᵢ assigns probabilities proportional to counts. Insert k extra copies of one chosen candidate r:
This is a transparent count model, not a neural language model. We choose r explicitly so that the calculation is repeatable. A randomized canary experiment and a real model require additional experimental controls.
For equal-length candidates, ordering by lower log-perplexity is equivalent to ordering by higher probability. Following the inclusive rank convention in the paper’s definition:
A tie includes every tied candidate. A completely uniform model therefore gives every candidate rank M, not rank one. Exposure relative to this declared candidate space is:
The score compares a model-induced ordering with uniform enumeration of this space. It is not a direct measure of mutual information or a prior-independent privacy certificate. Changing the space can change exposure even when the candidate probability is fixed. A natural population’s frequencies need not equal the uniform enumeration baseline.
Rank also does not determine random sampling success. For K independent samples from the same model, the chance of drawing candidate r at least once is:
This differs from ordered guessing, and it does not describe adaptive prompts or dependent samples. The code uses log1p and expm1 to retain numerical accuracy at small probabilities.
A separate quantity is performance on an unchanged target population P:
Improving an inserted canary’s rank can worsen this loss. A small change in average loss can coexist with a large change for a rare candidate; an aggregate is not a substitute for a targeted audit.
For generated points z and training points xⱼ, a near-match diagnostic can be defined explicitly as:
This RMS metric is our toy choice, not a reproduction of the image paper’s exact implementation. Its result depends on units, representation, threshold and the reference collection. A close match by itself does not prove a causal dependence on one particular training inclusion.
Insert an artificial symbol and enumerate its rank
Save as generative_memorization.py; use Python 3.12 and NumPy 1.26.4. The 64 candidates are artificial symbols with baseline counts 64 down to 1. The chosen canary is symbol-63, initially the least frequent. No personal information, external model or real secret is involved.
"""Original finite canary audit; every label and observation is artificial."""
import json
import numpy as np
def prob(p):
p = np.asarray(p, dtype=float)
if p.ndim != 1 or not 2 <= len(p) <= 4096 or not np.isfinite(p).all() or np.any(p < 0) or not np.isclose(p.sum(), 1, atol=1e-12, rtol=0):
raise ValueError('Expected a normalized finite candidate distribution')
return p
def exposure(p, index):
p = prob(p)
if type(index) is not int or not 0 <= index < len(p): raise ValueError('Invalid candidate index')
# Equal length candidates: lower log-perplexity means higher probability.
rank = int(np.count_nonzero(p >= p[index]))
return rank, float(np.log2(len(p))-np.log2(rank))
def fit_counts(counts, additional=0, index=63):
counts = np.asarray(counts)
if counts.ndim != 1 or not 2 <= len(counts) <= 4096 or counts.dtype.kind not in 'iu' or np.any(counts < 0) or counts.sum() <= 0:
raise ValueError('Expected nonnegative integer counts')
if type(additional) is not int or not 0 <= additional <= 100000 or type(index) is not int or not 0 <= index < len(counts):
raise ValueError('Invalid insertion')
updated = counts.astype(float); updated[index] += additional
return updated/updated.sum()
def hit_probability(p, budget):
if isinstance(p, (bool, np.bool_)) or not np.isfinite(p) or not 0 <= p <= 1 or type(budget) is not int or not 0 <= budget <= 100000:
raise ValueError('Probability and nonnegative integer budget required')
if budget == 0 or p == 0: return 0.
if p == 1: return 1.
return float(-np.expm1(budget*np.log1p(-p)))
def greedy_bits(p):
p = prob(p); n = int(np.log2(len(p)))
if 2**n != len(p): raise ValueError('Binary candidate space required')
left, right = 0, len(p)
while right-left > 1:
middle = (left+right)//2
if p[left:middle].sum() >= p[middle:right].sum(): right = middle
else: left = middle
return left
def nearest_rates(training, samples, thresholds):
training, samples = np.asarray(training, dtype=float), np.asarray(samples, dtype=float)
thresholds = np.asarray(thresholds, dtype=float)
if training.ndim != 2 or samples.ndim != 2 or min(len(training), len(samples)) < 1 or training.shape[1] != samples.shape[1] or training.shape[1] < 1 or not np.isfinite(training).all() or not np.isfinite(samples).all() or thresholds.ndim != 1 or not np.isfinite(thresholds).all() or np.any(thresholds < 0):
raise ValueError('Finite point matrices and nonnegative thresholds required')
rms = np.sqrt(np.mean((samples[:, None]-training[None])**2, axis=-1)).min(axis=1)
return [float(np.mean(rms <= t)) for t in thresholds]
def demo():
counts = np.arange(64, 0, -1); true = fit_counts(counts); rows = []
for copies in [0, 16, 63, 64, 256]:
q = fit_counts(counts, copies); rank, bits = exposure(q, 63)
rows.append(dict(extra_copies=copies, rank=rank, exposure_bits=bits, canary_probability=float(q[63]),
hit_in_100=hit_probability(q[63], 100), population_nll=float(-true @ np.log(q))))
p = np.array([.30, .29, .01, .40])
return dict(candidate_count=64, artificial_canary='symbol-63', experiments=rows,
uniform_exposure=exposure(np.ones(64)/64, 63)[1],
greedy_counterexample=dict(probabilities=p.tolist(), greedy_index=greedy_bits(p), global_mode=int(p.argmax())),
nearest_example=dict(thresholds=[0, .49, .5, 1], rates=nearest_rates([[-1], [1]], [[-1], [0], [.5]], [0, .49, .5, 1])),
scope='Artificial categorical counts and points; exposure is a specified-space audit, not a neural-model extraction result or privacy guarantee.')
if __name__ == '__main__': print(json.dumps(demo(), indent=2))
Without extra copies the canary has rank 64 and exposure zero. Adding 63 copies ties it with the most frequent symbol: inclusive rank two, exposure five bits. Adding 64 makes it uniquely first: exposure six bits but probability only 65/2144, about .0303. One hundred independent samples hit it with probability about .954. Adding 256 copies keeps the same maximum exposure while raising its probability to about .110. Rank has saturated; probability has not.
The baseline population NLL rises from about 3.97326 to 4.00156 after 64 extra copies. The toy sequence distribution [.30,.29,.01,.40] supplies a different warning: greedy prefix sampling chooses binary sequence 00, while the most probable complete sequence is 11. High full-sequence rank is not equivalent to discovery by a particular decoder.
Ranking one candidate costs O(M); sorting all candidates would cost O(M log M). Exact enumeration becomes impractical for large sequence spaces. The toy nearest-point routine costs O(nmd) and forms the corresponding intermediate; it is intentionally for small point sets, not a scalable image-search system.
A negative audit is not a universal guarantee
The image extraction definition distinguishes near-copies of particular training examples from other recognizable generated images. A distance threshold can miss transformations or flag common structures. The paper also separates extractability from the number of near-duplicates in training. We do not run its extraction procedure or infer a modern model’s behaviour from this categorical example.
Record the candidate construction, insertion count, model access, sampling or search budget, similarity rule and comparison population. Report ties explicitly. An audit might miss another prompt, a different data subgroup or a different adversary. Conversely, on a tiny support containing only training-observed states, exact matches can be inevitable without sample-specific memorization, as in the synthetic-table example.
Separate the three probabilities
- Calculate. Why do 63 extra copies give five exposure bits rather than six? Answer: The count becomes 64, tying another candidate. Inclusive rank is two, so log₂64−log₂2=5.
- Interpret. Does six-bit exposure imply a one-shot hit probability near one? Answer: No. With 64 added copies it is only 65/2144. Exposure uses rank; random sampling uses probability mass.
- Diagnose. Why does greedy decoding miss the .40 sequence in the four-sequence example? Answer: The first-bit-zero branch has total mass .59, exceeding .41 for first-bit one. Greedy commits to that branch and returns its .30 sequence.
- Transfer. What happens when a near-match threshold is increased? Answer: The reported rate cannot decrease under the same metric and reference set. That change reflects the audit definition, not a change in the generator’s memory.
Use narrow definitions to make claims testable
Canary exposure and approximate image extraction make different questions measurable. Their value comes from explicit assumptions and evidence. Our finite experiments clarify rank, mass and thresholds; they do not establish a privacy guarantee or reproduce a neural-model attack.
Make a prediction, then check
Does maximum exposure imply near-certain one-shot sampling?
Learning objectives
- Calculate exposure with an explicit tie rule.
- Separate rank from sampling success.
- State the limits of near-match audits.
Prerequisites & connections
Explore related knowledge →References
- The Secret Sharer: Evaluating and Testing Unintended Memorization in Neural Networks (USENIX2019)
Nicholas Carlini; Chang Liu; Úlfar Erlingsson; Jernej Kos; Dawn Song · 2019 - Extracting Training Data from Diffusion Models (v1)
Nicholas Carlini; Jamie Hayes; Milad Nasr; Matthew Jagielski; Vikash Sehwag; Florian Tramèr; Borja Balle; Daphne Ippolito; Eric Wallace · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked Secret Sharer artificial-canary setup/section4.2/opening4.3 and Diffusion Extraction v1 section4.1/opening4.2. Six paired equations and four explained exercises; original64-symbol count intervention, inclusive tie rank, exposure, hit probability, greedy counterexample and declared toy RMS near-match rates. No real secrets, neural-model attack or general privacy claim.
- Single AI author checked Secret Sharer artificial-canary setup/section4.2/opening4.3 and Diffusion Extraction v1 section4.1/opening4.2. Six paired equations and four explained exercises; original64-symbol count intervention, inclusive tie rank, exposure, hit probability, greedy counterexample and declared toy RMS near-match rates. No real secrets, neural-model attack or general privacy claim.
- Four computed SVG variants per topic. Fifteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Initial label polish and English mobile-title clipping correction preserved. Full article acceptance recorded separately.
Source locations checked:
- The Secret Sharer: Evaluating and Testing Unintended Memorization in Neural Networks (USENIX2019) · Read artificial-canary setup, section4.2 and opening4.3; PDF6 viewed. Rank includes ties under the stated inequality. No neural training or real-secret extraction.
- Extracting Training Data from Diffusion Models (v1) · Read section4.1 and opening4.2; PDF4 viewed. Approximate extraction and near-duplicate definitions only; no attack pipeline or benchmark replication.
Related topics