Model extraction and intellectual property protection: watermarking
Study the confidentiality of the model itself. Move from solving linear-model equations to recovering production LLMs' final layers from log-probabilities, via learning-based extraction and ReLU-network cryptanalysis. Analyze extraction defenses and their costs, then study evidence of copying: model watermarks, fingerprints, dataset inference, and statistical watermarks in generated text.
After this lesson you can
- Extract a logistic model exactly with d+1 queries and extract an MLP through learning with active queries.
- Distinguish accuracy-based extraction from fidelity-based extraction and measure both.
- Recover an LLM's hidden dimension from the rank of its logit vectors.
- Evaluate API defenses and their cost for legitimate users.
- Implement a green list watermark in the generation and its detection with a z-test, and measure its robustness to paraphrasing.
Before you start
Training costs, querying is cheap
A model deployed behind an API has two uncomfortable owners: the party that trained it and paid for data, computation, and time, and anyone able to query it. Every response reveals information about its weights. Model extraction reconstructs a substitute from queries, copying the model’s function or, in the best case, its parameters. This attacks the confidentiality of the model itself, unlike the attacks on prediction integrity or training-data privacy covered in the module’s threat model.
There are two reasons to take this seriously. The first is economic: if copying costs less than training, the owner’s advantage disappears. Orekondy and colleagues build a reasonable copy of an image-analysis service for about 30 dollars, according to their abstract, and Carlini and colleagues recover the final projection matrices of OpenAI’s Ada and Babbage models for less than 20 dollars. The second is technical: a substitute with accessible weights enables white-box attacks. The transfer attacks in the adversarial-examples lesson need exactly this: a local model that behaves like the victim.
This lesson is defensive: you are interested in the attacker to measure how much it costs, what API outputs facilitate it, what defenses truly make it more expensive, and how to demonstrate later that a model is yours. All attacks target your own, small, and local models; none touch a third-party service.
Threat model: budget and outputs
An extraction threat model specifies three things: what the attacker knows, such as architecture, data type, and input distribution; their query budget, which translates into money and time; and, above all, what the API returns, because the information per query varies greatly across outputs:
- The label (one bit in binary, bits into classes).
- The probabilities (or log-probabilities) of all classes: one real number per class.
- The largest log-probabilities, as offered by many LLM APIs.
- The complete logits, or probabilities with user-controlled decoding, such as token biases and temperature.
The attacker also has two distinct objectives, clearly separated by Jagielski and colleagues. Accuracy seeks good performance on the underlying task; fidelity seeks agreement with the victim on every input, including its errors. Accuracy suffices for someone copying a production model to use it; fidelity matters when crafting transferable adversarial examples or avoiding payment while preserving behavior. The same extraction can succeed by one metric and fail by the other, so this lesson always measures both.
Solving equations: the linear case
Start with the case where the attacker need not learn anything. Logistic regression computes , and the API returns . If , the logit is a linear function of the input. Each query gives a linear equation in the unknowns :
With queries, at the origin and the standard basis vectors, solve the linear system to recover and exactly, up to arithmetic rounding. For softmax classes, gives equations per query. The same queries recover all parameter differences, which are all softmax can distinguish. Tramèr and colleagues applied this reasoning to logistic regression, networks, and decision trees on BigML and Amazon Machine Learning services, obtaining nearly perfect-fidelity copies. Their abstract adds a key API-design result: omitting confidence values, the seemingly natural countermeasure, does not prevent harmful extraction.
Run the base case and check the two properties: the number of queries is and the error is of the order of the machine epsilon.
import numpy as np
rs = np.random.RandomState(3)
d = 8
w_true, b_true = rs.randn(d), 0.7
class PredictionAPI:
"""Víctima: una regresión logística. Cuenta las consultas y puede degradar la salida."""
def __init__(self, w, b, decimals=None):
self.w, self.b, self.decimals, self.queries = w, b, decimals, 0
def prob(self, x):
self.queries += 1
p = 1 / (1 + np.exp(-(x @ self.w + self.b)))
return p if self.decimals is None else np.round(p, self.decimals)
def label(self, x):
self.queries += 1
return int(x @ self.w + self.b > 0)
def log_odds(api):
def f(x):
p = api.prob(x)
return np.log(p / (1 - p)) # log-odds = w.x + b
return f
def extract_logistic(query_fn, d):
"""d + 1 consultas: b = f(0) y w_i = f(e_i) - b."""
b = query_fn(np.zeros(d))
w = np.array([query_fn(e) - b for e in np.eye(d)])
return w, b
api = PredictionAPI(w_true, b_true)
w_hat, b_hat = extract_logistic(log_odds(api), d)
print("consultas:", api.queries, "| error máximo en w:", np.abs(w_hat - w_true).max(), "| error en b:", abs(b_hat - b_true))The 9 queries recover and with a maximum error of . No approximation: it’s linear algebra. Now degrade the output as a naive defense would: round the probability to decimals. The exact system stops giving the answer, but you can compensate noise with more queries, solving an overdetermined system by least squares:
def lstsq_extract(api, n, scale=0.5, seed=0):
"""Con n > d + 1 consultas aleatorias, mínimos cuadrados sobre el log-odds (promedia el ruido de redondeo)."""
r = np.random.RandomState(seed)
X = scale * r.randn(n, d)
y, keep = [], []
for i, x in enumerate(X):
p = api.prob(x)
if 0 < p < 1: # una probabilidad saturada no informa
y.append(np.log(p / (1 - p)))
keep.append(i)
A = np.hstack([X[keep], np.ones((len(keep), 1))])
c = np.linalg.lstsq(A, np.array(y), rcond=None)[0]
return c[:-1], c[-1]
def angle_error(w_hat):
u, v = w_hat / np.linalg.norm(w_hat), w_true / np.linalg.norm(w_true)
return np.linalg.norm(u - v)
print("decimales | d+1 consultas (e_i) | 100 consultas | 1000 consultas")
for k in [2, 3, 4, 6]:
a1 = PredictionAPI(w_true, b_true, k)
w1, _ = extract_logistic(log_odds(a1), d)
w2, _ = lstsq_extract(PredictionAPI(w_true, b_true, k), 100)
w3, _ = lstsq_extract(PredictionAPI(w_true, b_true, k), 1000)
print(f"{k:9d} | {angle_error(w1):19.1e} | {angle_error(w2):13.1e} | {angle_error(w3):.1e}")Read the table by rows. With two decimal places, the directional error of is for queries and falls to for a thousand; with four decimal places, it is already for 9 queries. Rounding increases the error, but the attacker can reduce it by paying for more queries. This is the general pattern of almost all the API defenses below: they increase the attack’s cost by a factor, rather than ruling it out.
Returning only the label is also insufficient. The hyperplane can be located by bisection: given two points with different labels, each midpoint query halves the segment containing the boundary. Fit the hyperplane using boundary points. Each point costs about queries for bits of precision:
def boundary_point(api, a, c, label_a, bits):
"""Bisección sobre el segmento a-c, cuyos extremos tienen etiquetas distintas: una consulta por paso."""
lo, hi = a, c
for _ in range(bits):
mid = (lo + hi) / 2
if api.label(mid) == label_a:
lo = mid
else:
hi = mid
return (lo + hi) / 2
def steal_with_labels(api, m, bits, seed=0):
"""Busca m puntos de la frontera w.x + b = 0 y ajusta w/b por mínimos cuadrados sobre w'.p = -1 (supone b = 1 conocido)."""
r = np.random.RandomState(seed)
pts = []
while len(pts) < m:
a, c = 2 * r.randn(d), 2 * r.randn(d)
la, lc = api.label(a), api.label(c)
if la != lc: # solo sirven pares con etiquetas distintas; los demás se descartan, pero cuentan como consultas
pts.append(boundary_point(api, a, c, la, bits))
return np.linalg.lstsq(np.array(pts), -np.ones(m), rcond=None)[0]
for bits in [8, 16, 30]:
api = PredictionAPI(w_true, 1.0) # sesgo 1: la frontera no pasa por el origen
w_hat = steal_with_labels(api, 20, bits)
print(f"bits = {bits:2d} | consultas = {api.queries:4d} | error de dirección de w = {angle_error(w_hat):.1e}")With 20 boundary points and 16 bisection steps, the angular error is after 428 queries, including rejected queries that do not cross the boundary. Compare this with the rounding table: label-only output gives greater precision with 428 queries (error ) than probabilities rounded to 4 decimal places with 1000 queries (error ). The intuition that withholding information necessarily protects more fails here because bisection is adaptive: each response determines the next query.
Extraction by learning: when there are no equations
An MLP is nonlinear in its input, so there is no linear system to solve. But the victim remains an oracle, and a substitute can train on (input, API output) pairs. This is the same operation as knowledge distillation, with different permissions: the distiller has neither the teacher’s data nor its weights, only permission or a means to query it. Probabilities provide soft distillation targets; labels provide hard targets.
The attacker makes two choices. First, where to query: random domain points or points near the boundary of the current substitute, using uncertainty sampling where a new response most changes the fit. Second, what to request: labels or probabilities. The figure shows both on a fully visible 2D victim, with a third strategy combining exploration and boundary queries: each round of 8 queries includes 4 closest to the substitute’s boundary and 4 random points.
What to observe, with the means of the 6 executions from the figure. First, the output. With probabilities, each query contributes a real number, not a bit: with random queries, 64 probabilities give a fidelity of 0.952 and 256 labels are needed to achieve the same (0.955). Four times fewer queries for the same copy.
Second, the strategy. Boundary-only queries with probabilities perform best from 128 queries onward (0.981 versus 0.956 for random queries, whose curve plateaus because they rarely fall near the boundary). With labels, however, the mean hides a failure: select run 3. All 8 initial queries fall outside the circle, the substitute predicts class 0 throughout the plane, and the points with the smallest from this boundaryless substitute continue to fall outside. Fidelity remains at 0.794, the class-0 fraction, from 8 to 256 queries. This is active learning’s sampling bias: an incorrect model chooses the queries, with nothing forcing it to discover its error. The mixed strategy adds exploration: with labels at 128 queries, its worst run gives 0.935 and its mean is 0.959, exceeding random sampling at 256 queries (0.955).
Third, the metric. Switch the curve to accuracy. Random sampling with 64 probability queries achieves task accuracy of 0.955, higher than the victim’s 0.937, but fidelity of only 0.952: a smooth substitute does not reproduce the islands created by label noise and is correct where the victim errs. At the other extreme, mixed sampling with 256 labels gives fidelity of 0.983 and accuracy of 0.936, matching the victim’s accuracy while also copying its errors. The metrics measure different properties. An attacker seeking fidelity is more dangerous because the copy behaves like the victim even where it fails.
This is what the laboratory reproduces, with a victim and a substitute in pure numpy:
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def truth(X):
"""La tarea: la clase 1 es el interior de un círculo."""
return (((X[:, 0] - 0.2) ** 2 + X[:, 1] ** 2) < 1.0).astype(float)
class Net:
"""MLP 2-H-1 con ReLU o tanh y Adam sobre la entropía cruzada con objetivos en [0, 1]."""
def __init__(self, H, act, rs, s1, s2):
self.act = act
self.p = [rs.randn(2, H) * s1, np.zeros(H), rs.randn(H) * s2, np.zeros(())]
def forward(self, X):
W1, b1, w2, b2 = self.p
z = X @ W1 + b1
a = np.maximum(z, 0) if self.act == "relu" else np.tanh(z)
return a @ w2 + b2, z, a
def logit(self, X):
return self.forward(X)[0]
def fit(self, X, y, steps, lr):
m = [np.zeros_like(q) for q in self.p]
v = [np.zeros_like(q) for q in self.p]
for t in range(1, steps + 1):
out, z, a = self.forward(X)
dz = (sigmoid(out) - y) / len(X)
da = np.outer(dz, self.p[2]) * ((z > 0) if self.act == "relu" else (1 - a * a))
for i, g in enumerate([X.T @ da, da.sum(0), a.T @ dz, dz.sum()]):
m[i] = 0.9 * m[i] + 0.1 * g
v[i] = 0.999 * v[i] + 0.001 * g * g
self.p[i] -= lr * (m[i] / (1 - 0.9**t)) / (np.sqrt(v[i] / (1 - 0.999**t)) + 1e-8)
return self
# La víctima: 160 puntos del círculo con un 8 % de etiquetas cambiadas
rs = np.random.RandomState(0)
Xtr = rs.uniform(-2, 2, (160, 2))
ytr = np.where(rs.rand(160) < 0.08, 1 - truth(Xtr), truth(Xtr))
victim = Net(16, "relu", rs, 0.7, 0.3).fit(Xtr, ytr, 1500, 0.01)
Xtest = np.random.RandomState(1).uniform(-2, 2, (5000, 2))
v_label = victim.logit(Xtest) > 0
print("exactitud de la víctima frente a la tarea:", round(float((v_label == truth(Xtest)).mean()), 3))
print("primeros pesos de la capa 1:", np.round(victim.p[0][0, :4], 4), "| b2 =", round(float(victim.p[3]), 4))The victim succeeds 93.7% on the task. Now run the six combinations (strategy by output), with two seeds and budgets of 32 and 128:
def extract(strategy, output, budget, seed):
"""Extrae la víctima con `budget` consultas, en rondas de 8. strategy: random (al azar), active (los 8 candidatos
más cercanos a la frontera del sustituto) o mixed (los 4 más cercanos y 4 al azar)."""
r = np.random.RandomState(100 + seed)
def api(X):
p = sigmoid(victim.logit(X))
return (p > 0.5).astype(float) if output == "label" else p
X = r.uniform(-2, 2, (8, 2))
y = api(X)
S = Net(12, "tanh", np.random.RandomState(seed), 0.8, 0.3).fit(X, y, 300, 0.03)
while len(X) < budget:
if strategy == "random":
Xn = r.uniform(-2, 2, (8, 2))
else:
pool = r.uniform(-2, 2, (320, 2))
near = pool[np.argsort(np.abs(S.logit(pool)))[: 8 if strategy == "active" else 4]]
Xn = near if strategy == "active" else np.vstack([near, pool[-4:]])
X, y = np.vstack([X, Xn]), np.concatenate([y, api(Xn)])
S.fit(X, y, 120, 0.03)
S.fit(X, y, 200, 0.03)
s_label = S.logit(Xtest) > 0
return (s_label == v_label).mean(), (s_label == truth(Xtest)).mean()
def table(strategy, output, budgets=(32, 128), seeds=(0, 1)):
res = {b: np.mean([extract(strategy, output, b, s) for s in seeds], axis=0) for b in budgets}
cols = " ".join(f"B={b}: fidelidad {res[b][0]:.3f}, exactitud {res[b][1]:.3f}" for b in budgets)
print(f"{strategy:8s} {output:5s} {cols}")
table("random", "label")
table("random", "prob")table("active", "label")
table("active", "prob")table("mixed", "label")
table("mixed", "prob")Read the three tables carefully: they use only two seeds. The probability advantage persists in every row: for every strategy and budget, probability-based fidelity exceeds label-based fidelity (0.905 versus 0.852 with 32 random queries; 0.978 versus 0.956 with 128 boundary-only queries). The strategy ranking changes, however: with labels and 128 queries, boundary-only gives 0.956, mixed sampling 0.933, and random sampling 0.921; with 32 labels, random sampling is best (0.852 versus 0.800 and 0.789). Two seeds leave substantial variability. The figure’s six runs and range band help separate that variability from the pattern described above: boundary queries yield more information, while exploration protects against a substitute missing a class. With probabilities and 128 queries, accuracies of 0.933, 0.948, and 0.949 remain near the victim’s 0.937.
Jagielski and collaborators formalize what you see: they argue analytically and empirically that strategies based on learning cannot produce a high-fidelity copy because training only adjusts the function near the queried points. To go further, one has to read the parameters.
Cryptanalytic extraction of ReLU networks
A ReLU network is piecewise linear, and the pieces betray the weights. Consider the victim above and follow the line with many queries to the logit. Each neuron from the hidden layer contributes with on that line; upon crossing the slope of the logit changes suddenly, in and with a jump of . Detecting those critical points reveals, neuron by neuron, where its hyperplane is and how much it weighs; repeating for another line gives the other component. That is the principle of the cryptanalytic extraction of Carlini, Jagielski and Mironov: a differential attack that recovers the parameters of a ReLU network to floating-point precision. According to its summary, a network with 100,000 parameters trained on MNIST was extracted with queries in less than an hour, coinciding with the oracle with maximum error , and one with 4,000 parameters with queries and maximum error ; they report copies more precise with 100 times fewer queries than the previous state of the art.
def kinks_along_x(f, y0, lo=-2.0, hi=2.0, n=40001, tol=1e-6):
"""Recorre la recta y = y0 con n consultas al logit y devuelve las abscisas donde cambia la pendiente y el salto."""
t = np.linspace(lo, hi, n)
slope = np.diff(f(np.stack([t, np.full(n, y0)], 1))) / np.diff(t)
jump = np.diff(slope)
idx = np.where(np.abs(jump) > tol)[0]
groups = np.split(idx, np.where(np.diff(idx) > 1)[0] + 1) # un cambio de pendiente puede repartirse entre dos celdas vecinas
xs = [np.average(t[1:-1][g], weights=np.abs(jump[g])) for g in groups]
return np.array(xs), np.array([jump[g].sum() for g in groups])
W1, b1, w2, b2 = victim.p
found_x, found_jump = kinks_along_x(victim.logit, y0=0.0)
# teoría: la neurona j cruza cero en x_j = -b1_j / W1[0, j] y el salto de pendiente es w2_j * |W1[0, j]|
x_th = -b1 / W1[0]
inside = (x_th > -2) & (x_th < 2)
order = np.argsort(x_th[inside])
th_x, th_jump = x_th[inside][order], (w2 * np.abs(W1[0]))[inside][order]
print("neuronas cuyo cruce cae en [-2, 2]:", int(inside.sum()), "| cambios de pendiente hallados:", len(found_x))
print("error máximo en la abscisa: %.1e | error máximo en el salto: %.1e" % (np.abs(found_x - th_x).max(), np.abs(found_jump - th_jump).max()))The 14 crossings within are detected as 14 slope changes, with errors on the order of in position and in jump size: essentially exact recovery. A full attack must handle depth, signs, and neurons whose hyperplanes do not cross the explored region; here, 2 of the 16 do not appear along this line. The key idea is that full-precision logit access turns piecewise linearity into a channel for reading weights.
Stealing part of an LLM: the hidden dimension in the rank
For a prompt, an LLM API returns next-token log-probabilities over a vocabulary of tokens. The final layer is a linear projection: if is the hidden state after the last normalization, the logits are with . But , typically in the thousands, is much smaller than , in the tens or hundreds of thousands. All logit vectors lie in a subspace of with dimension , which is visible through the rank.
Proof
Matrix multiplication does not increase the rank: , and has columns, then . The bias adds , that has rank , and the rank of a sum is at most the sum of the ranks. The same for .
∎This is the idea behind the attack by Carlini and colleagues: collect output vectors and compute their SVD. The first singular values are large; subsequent values fall to floating-point noise. The index of this drop is , the hidden dimension. The singular vectors also provide a basis for the logit subspace, the column space of , recovering the final projection layer up to an invertible transformation : for any invertible , while is hidden. According to the abstract, the attack extracts Ada’s and Babbage’s full projection matrices for less than 20 dollars, confirms hidden dimensions of 1024 and 2048 respectively, recovers gpt-3.5-turbo’s hidden dimension, and estimates the query cost of recovering its entire matrix at less than 2,000 dollars.
A practical detail is hidden by the theorem: production APIs do not simply return logits, but the largest log-probabilities, sometimes with user-controlled token biases. The paper’s attack exploits this combination to reconstruct the full output vector using more queries per vector. A simple defense discussed below is to avoid offering logit biases together with log-probabilities.
Why does the drop occur, and why is it not always at ? With , nothing is visible: an matrix has at most nonzero singular values, all carrying signal. Once exceeds the rank, the next singular value falls sharply. At the maximum , Pythia-14m’s differences drop from times the largest value to ; Pythia-70m drops from to , the noise floor of single-precision API outputs. The rank threshold has some margin: changing it from to leaves the result unchanged; lowering it below for Pythia-70m or for Pythia-14m starts counting noise. Now enable Reveal. Pythia-14m’s log-probabilities have rank 129 , while differences from a reference column, which give logits modulo a per-prompt constant, have rank 128 , as in the theorem. For Pythia-70m, the differences have rank 511 , and log-probabilities have rank 512.
This does not contradict the theorem, which gives a bound. The cause lies in the final LayerNorm: its output is , with zero-mean normalized satisfying . Solving for gives for every output: they lie in an affine hyperplane of dimension . If the right-hand side is nonzero, this hyperplane does not pass through the origin and its points span all of , giving rank ; if it is zero, they span only the hyperplane, giving rank . The cell below prints this sum: for Pythia-14m and for Pythia-70m, so close to zero that the extra direction remains in the noise. The methodological lesson is that the drop gives up to from architectural details. Reconstruct and check the basis rather than treating the index as a magic number.
The local lab implements a Pythia (GPT-NeoX) forward pass in about forty lines of pure NumPy, an API returning single-precision log-probabilities, and the attack. It requires neither a GPU nor PyTorch; weights are loaded with safetensors and the tokenizer with tokenizers. The forward pass agrees with the transformers implementation to a relative error on the order of relative to the maximum logit magnitude, sufficient for the experiments below.
import json
import numpy as np
from scipy.special import erf
from safetensors.numpy import load_file
from huggingface_hub import snapshot_download
from tokenizers import Tokenizer
class Pythia:
"""Pythia (GPT-NeoX) en numpy puro: solo inferencia, con caché de claves y valores."""
def __init__(self, name):
d = snapshot_download(name, allow_patterns=["config.json", "model.safetensors", "tokenizer.json"])
cfg = json.load(open(d + "/config.json", encoding="utf-8"))
self.h, self.nh, self.L = cfg["hidden_size"], cfg["num_attention_heads"], cfg["num_hidden_layers"]
self.hd = self.h // self.nh
self.rd = int(self.hd * cfg["rotary_pct"]) # solo se rota una parte de cada cabeza
self.eps = cfg["layer_norm_eps"]
self.w = {k.replace("gpt_neox.", ""): v.astype(np.float32) for k, v in load_file(d + "/model.safetensors").items()}
self.tok = Tokenizer.from_file(d + "/tokenizer.json")
self.V = self.w["embed_out.weight"].shape[0]
def ln(self, x, name):
mu = x.mean(-1, keepdims=True)
var = ((x - mu) ** 2).mean(-1, keepdims=True)
return (x - mu) / np.sqrt(var + self.eps) * self.w[name + ".weight"] + self.w[name + ".bias"]
def rope(self, x, pos):
f = pos[:, None] / 10000 ** (np.arange(0, self.rd, 2) / self.rd)[None]
e = np.concatenate([f, f], -1)
c, s = np.cos(e).astype(x.dtype), np.sin(e).astype(x.dtype)
xr, xp = x[..., : self.rd], x[..., self.rd :]
rot = np.concatenate([-xr[..., self.rd // 2 :], xr[..., : self.rd // 2]], -1)
return np.concatenate([xr * c + rot * s, xp], -1)
def hidden(self, ids, cache=None):
"""Estado tras la LayerNorm final de cada posición: forma (B, T, h)."""
ids = np.asarray(ids)
B, T = ids.shape
t0 = cache[0][0].shape[2] if cache else 0
pos = np.arange(t0, t0 + T)
x = self.w["embed_in.weight"][ids]
for l in range(self.L):
p = f"layers.{l}."
a = self.ln(x, p + "input_layernorm")
qkv = a @ self.w[p + "attention.query_key_value.weight"].T + self.w[p + "attention.query_key_value.bias"]
qkv = qkv.reshape(B, T, self.nh, 3 * self.hd).transpose(0, 2, 1, 3)
q, k, v = qkv[..., : self.hd], qkv[..., self.hd : 2 * self.hd], qkv[..., 2 * self.hd :]
q, k = self.rope(q, pos), self.rope(k, pos)
if cache is not None:
if len(cache) > l:
k, v = np.concatenate([cache[l][0], k], 2), np.concatenate([cache[l][1], v], 2)
cache[l] = (k, v)
else:
cache.append((k, v))
s = q @ k.transpose(0, 1, 3, 2) / self.hd ** 0.5
s = np.where(np.arange(k.shape[2])[None] <= (t0 + np.arange(T))[:, None], s, -1e30)
s = np.exp(s - s.max(-1, keepdims=True))
att = ((s / s.sum(-1, keepdims=True)) @ v).transpose(0, 2, 1, 3).reshape(B, T, self.h)
att = att @ self.w[p + "attention.dense.weight"].T + self.w[p + "attention.dense.bias"]
m = self.ln(x, p + "post_attention_layernorm") @ self.w[p + "mlp.dense_h_to_4h.weight"].T + self.w[p + "mlp.dense_h_to_4h.bias"]
m = 0.5 * m * (1 + erf(m / 2 ** 0.5)) # GELU exacta
m = m @ self.w[p + "mlp.dense_4h_to_h.weight"].T + self.w[p + "mlp.dense_4h_to_h.bias"]
x = x + att + m # bloques en paralelo: atención y MLP leen el mismo x
return self.ln(x, "final_layer_norm")
def logits(self, ids, cache=None):
"""Logits de la última posición: forma (B, V). Es la salida de la capa de proyección final."""
return self.hidden(ids, cache)[:, -1] @ self.w["embed_out.weight"].Tnpm run lab and open the connection link.class LogprobAPI:
"""La víctima vista desde fuera: recibe prompts y devuelve el vector completo de log-probabilidades del siguiente token."""
def __init__(self, model):
self.m, self.queries = model, 0
def __call__(self, prompts):
out = []
for i in range(0, len(prompts), 16):
lg = self.m.logits(prompts[i : i + 16])
lg -= lg.max(1, keepdims=True)
out.append((lg - np.log(np.exp(lg).sum(1, keepdims=True))).astype(np.float32)) # las APIs devuelven float32
self.queries += len(lg)
return np.concatenate(out)
def sing_vals(M, ref=None, chunk=6288):
"""Valores singulares de M (o de M menos la columna ref) vía la matriz de Gram en doble precisión.
Devuelve también los autovectores izquierdos. Se recorre M por trozos de columnas para no copiarla entera."""
G = np.zeros((len(M), len(M)))
for j in range(0, M.shape[1], chunk):
c = M[:, j : j + chunk].astype(np.float64)
if ref is not None:
c -= ref[:, None]
G += c @ c.T
ev, U = np.linalg.eigh(G)
return np.sqrt(np.abs(ev[::-1])), U[:, ::-1]
def rank_estimate(s, tau=1e-6):
"""Cuántos valores singulares superan tau veces el mayor."""
return int((s / s[0] > tau).sum())npm run lab and open the connection link.The practical addition to the theory is checking the recovered basis. The API returns only log-probabilities, so subtract each row’s token-0 value to obtain logits modulo a per-prompt constant. The recovered basis must satisfy for some . Fit using two-thirds of the vocabulary rows and measure error on the remaining third. A random matrix provides a negative control.
def recover_projection(model, LP, tau=1e-6, rows=12000, seed=1):
"""Recupera, en `rows` filas del vocabulario, una base Q de la capa de proyección: Q = (W - 1 w0^T) G con G desconocida.
Se comprueba ajustando G con 2/3 de las filas y midiendo el error relativo en el 1/3 restante."""
ref = LP[:, 0]
s, U = sing_vals(LP, ref)
r = rank_estimate(s, tau)
R = np.random.RandomState(seed).choice(model.V, rows, replace=False)
Q = (LP[:, R] - ref[:, None]).T @ U[:, :r] / s[:r] # filas de la base recuperada en los tokens R
Wf = model.w["embed_out.weight"]
W = Wf[R] - Wf[0] # la proyección verdadera menos la fila del token 0 (la API solo da diferencias), solo para comprobar
k = 2 * rows // 3
out = {}
for tag, Wm in [("W verdadera", W), ("matriz al azar", np.random.RandomState(2).randn(*W.shape).astype(np.float32))]:
G = np.linalg.lstsq(Wm[:k], Q[:k], rcond=None)[0]
out[tag] = np.linalg.norm(Q[k:] - Wm[k:] @ G) / np.linalg.norm(Q[k:])
return r, outnpm run lab and open the connection link.import time
for name, N in [("EleutherAI/pythia-14m", 200), ("EleutherAI/pythia-70m", 530)]:
t0 = time.time()
model = Pythia(name)
api = LogprobAPI(model)
prompts = np.random.RandomState(0).randint(0, 50000, (N, 16)) # prompts de tokens al azar
LP = api(prompts) # (N, V) log-probabilidades
s_lp, _ = sing_vals(LP)
s_d, _ = sing_vals(LP, ref=LP[:, 0]) # log p(t) - log p(0) = logit(t) - logit(0)
print(f"{name}: h = {model.h}, V = {model.V}, N = {N}, consultas = {api.queries}")
print(" rango de las log-probabilidades:", rank_estimate(s_lp), "| de las diferencias con la columna 0:", rank_estimate(s_d))
print(" sigma_i/sigma_1 de las log-probabilidades en i = h, h+1, h+2:", ["%.1e" % (s_lp[i] / s_lp[0]) for i in (model.h - 1, model.h, model.h + 1)])
b, g = model.w["final_layer_norm.bias"].astype(np.float64), model.w["final_layer_norm.weight"].astype(np.float64)
print(" suma de beta_i/gamma_i de la LayerNorm final:", round(float((b / g).sum()), 4))
r, err = recover_projection(model, LP)
print(" base recuperada con r =", r, "columnas; error relativo fuera de la muestra:", {k: "%.1e" % v for k, v in err.items()})
print(" tiempo %.0f s" % (time.time() - t0))
del model, api, LPnpm run lab and open the connection link.The cell output confirms the theorem and its qualification. For Pythia-14m (), queries give log-probability rank 129 and reference-column difference rank 128. The recovered basis has 128 columns; relative reconstruction error on unseen rows of is , versus 1.0 for a random matrix. Pythia-70m (), with , gives ranks 512 and 511, a 511-column basis, and error : larger because the small singular values lie closer to noise, but 1000 times smaller than the control. The final LayerNorm sum is for Pythia-14m and for Pythia-70m. Also inspect the ratios : Pythia-14m’s 129th log-probability singular value, the extra log-sum-exp direction, is ; the 130th is already noise at . For Pythia-70m with these 530 prompts, the 512th is only , so a threshold of would count 511. With 640 prompts in the figure, that value rises to . The threshold margin depends on , another reason to verify the basis rather than just count singular values.
Recovering the final layer does not copy the entire model: it reveals and , giving a strong clue about the model’s size and the capacity of its remaining layers, but the lower layers stay hidden. Copying the complete function follows the earlier route: distill the model using (prompt, output distribution) pairs from the API. This is the same operation as distillation, except that the teacher is a third-party service. Full log-probabilities provide much more signal per query than sampled text, so offering them has security implications.
Defenses: increasing the cost of extraction
With the mechanism clear, extraction defenses can be understood as changes to output or access that increase the attacker’s cost. Evaluate them together with what legitimate users lose.
- Round or truncate probabilities. This adds noise to each query’s equations, at the cost of less precise confidence values for legitimate users. The mean error from rounding a probability to decimal places is , averaging a uniform error between zero and half a rounding step. With , very different probabilities such as 0.05 and 0.14 become identical, damaging calibration and ranking across examples.
- Return only labels or top- outputs. This reduces information per query, but bisection compensates in queries, as seen above. With top-, logit biases can expand the remaining information.
- Limit logit biases and controlled decoding. This closes the channel used to reconstruct full LLM output vectors, without affecting most users.
- Monitor queries. PRADA analyzes the distribution of a client’s consecutive queries and raises an alert when it departs from benign usage. Its abstract reports detecting all extraction attacks predating that work without false positives. Such a defense has two weaknesses: an informed attacker can imitate benign traffic or distribute queries across accounts, while even a small false-positive rate flags legitimate users at production scale.
- Pricing and rate limits. These change how many queries can be made, rather than what each query reveals.
The figure measures the first two defenses on a 10-variable logistic regression model, using an attacker based on least squares or bisection.
Two readings. First: with exact probability, 11 queries () already give an error below , the floor of the figure; with rounding to 3 decimals, 11 queries leave the error in , and there are about 100 needed to drop below and about 400 to get to . The rounding curve drops slowly, approximately as , because the attacker only averages noise. Second: the label-only curve drops as with the bisection steps: with 20 boundary points and 20 steps, 490 queries leave the error in , about 750 times below the rounding to 3 decimals with 400. Move the controls to check these figures and look at the reading of the cost to the legitimate user: the mean error of each probability is with 2 decimals and with 3, while with just the label that user loses the probabilities completely.
None of these defenses guarantees protection. The design question is which copying precision becomes uneconomical for an attacker with the specified threat-model budget, and how much service quality must be sacrificed to reach that point.
Demonstrating theft: watermarks and model fingerprints
If copying cannot be prevented, you want to be able to demonstrate it. Three families of methods provide different guarantees.
A model watermark modifies training so that the model responds in a prearranged way to secret inputs. Adi and colleagues use a backdoor, as their title states: triggers with chosen labels kept secret by the owner. For black-box verification, the owner queries the suspect with these triggers and counts matches. This repurposes the backdoor mechanism from the previous lesson. The test is binomial: with triggers and classes, an unmarked model matches each label with probability if labels were chosen randomly and independently of the data. The match count therefore follows . For , 12 matches out of 20 have tail probability under the unmarked-model hypothesis. This is strong statistical evidence, but requires the watermark to survive copying: a substitute trained on the original’s outputs need not inherit behavior on triggers that are rarely queried.
Fingerprints do not modify the model. They use an existing property, such as behavior on adversarial examples or boundary inputs, and test whether a suspect shares it. Dataset inference, from Maini, Yaghini and Papernot, starts from another observation: copies inherit knowledge of the training set, which the owner possesses. It combines statistical testing with estimates of several points’ distances to the boundary. According to the abstract, it establishes model theft with over 99% confidence using only 50 original training examples, with experiments on CIFAR10, SVHN, CIFAR100, and ImageNet. Its argument against backdoor watermarks is that triggers are outside the training distribution and may therefore not survive in a copy.
None of the three prevents the theft, and all produce evidence that later a court or arbitrator must evaluate. Think of them as a log, not as a lock.
Watermarks in text: green list
An LLM can also watermark individual outputs. This addresses a different question: whether a specific text was generated by your model, rather than whether the model belongs to you. Before generating each token, the scheme of Kirchenbauer and colleagues selects a pseudorandom list of green tokens using a secret and the preceding token, then biases generation toward that list. A detector knowing the key can count green tokens without accessing the model.
A green-list watermark performs three operations per step. Using a key and the previous token , partition the vocabulary into a green set of fraction and a red set. Add to green-token logits, then sample using the usual decoding procedure. Given tokens, the detector reconstructs the list at each position from the preceding token and counts how many of the final tokens are green: .
The z-test
For unmarked text and a pseudorandom partition independent of its content, each token is green with probability , and if the matches are independent. Repeated pairs violate this independence; a common practice is to count each distinct pair only once. By the central limit theorem, the statistic
is approximately under the null hypothesis, which is rejected when exceeds a threshold. This is a one-sample proportion test. At threshold , the one-sided normal p-value is . This is per text: over texts, the expected number of false positives is . For very large , the normal approximation is inaccurate in the tail: with , the binomial is right-skewed and the normal underestimates its upper tail. You will check this in the exercise with .
How much can the signal rise
Let be the probability mass assigned to green tokens at one step. After adding to their logits, the green mass becomes
because green tokens’ unnormalized weights are multiplied by . The function is concave, and a pseudorandom list gives expected green mass ; Jensen’s inequality gives
For , this is with , with , and with . The maximum is attained only when the green mass at every step is already , corresponding to high-entropy distributions. In a low-entropy step with one token’s probability near 1, the green mass is or and : the watermark cannot shift it, and the token is green only with probability . Text with little freedom, such as code or very-low-temperature responses (see temperature sampling), is therefore harder to watermark. Applying top- or nucleus filtering after the bias further restricts its effect by discarding low-probability green tokens. The expected signal is : it grows as , and a green fraction requires approximately tokens to reach .
With , no watermark, z fluctuates around zero: for , between and depending on . In the initial state, , , and , z is 8.78, below the formula’s bound of for that (63 green tokens out of 100). Now try : the same gives z of 5.31, because a large leaves little room between the baseline green fraction and . With and , 100 tokens give z of 3.67, below the detection threshold: a weak watermark needs more text. Click one token: the next token’s color may also change because each position’s list depends on the preceding token. Rewriting one token destroys at most two signals. The lower curve therefore declines gradually: with and , mean z drops below 4 after rewriting 20% of positions for (3.72), 40% for (3.87), and 60% for (3.67).
The laboratory implements everything from scratch on the previous model: the green list with a 32-bit hash (the same one used in the figure), the generation loop with the bias, the detector, and a rewriting attack with another model. The texts are sampled with temperature 1 without filters, so the entropy is high; with a better model and more conservative decoding, the results would be more modest.
KEY = 15485863
def fmix32(x):
"""Mezcla de bits de 32 bits (finalizador de MurmurHash3); la aritmética uint32 de numpy es módulo 2^32."""
x = x ^ (x >> np.uint32(16))
x = x * np.uint32(0x85EBCA6B)
x = x ^ (x >> np.uint32(13))
x = x * np.uint32(0xC2B2AE35)
return x ^ (x >> np.uint32(16))
def green_mask(prev, V, gamma):
"""Lista verde del siguiente token: t es verde si hash(clave, prev, t) cae en el primer gamma del rango de 32 bits."""
base = np.uint32((KEY + prev * 0x9E3779B1) & 0xFFFFFFFF)
h = fmix32(base + np.arange(V, dtype=np.uint32) * np.uint32(0x85EBCA77))
return h < np.uint32(int(gamma * 2**32))
def generate(model, prompt_ids, T, gamma, delta, rs):
"""Muestrea T tokens sumando delta al logit de los tokens verdes. Devuelve los tokens y el NLL medio bajo el modelo sin marca."""
cache, ids, nll = [], list(prompt_ids), 0.0
lg = model.logits(np.array([ids]), cache)[0].astype(np.float64)
for _ in range(T):
lp = lg - lg.max()
lp -= np.log(np.exp(lp).sum()) # log-probabilidades del modelo sin marca
z = lg + (delta * green_mask(ids[-1], model.V, gamma) if delta else 0.0)
p = np.exp(z - z.max())
t = min(int(np.searchsorted(np.cumsum(p / p.sum()), rs.uniform())), model.V - 1)
nll -= lp[t]
ids.append(t)
lg = model.logits(np.array([[t]]), cache)[0].astype(np.float64)
return ids[len(prompt_ids) :], nll / T
def detect(tokens, V, gamma):
"""Test z: cuenta los verdes entre los tokens 1..T (el primero solo aporta contexto)."""
G = sum(bool(green_mask(tokens[i - 1], V, gamma)[tokens[i]]) for i in range(1, len(tokens)))
T = len(tokens) - 1
return T, G, (G - gamma * T) / np.sqrt(T * gamma * (1 - gamma))npm run lab and open the connection link.import time
big = Pythia("EleutherAI/pythia-70m")
prompts = [
"Stealing a model is cheaper than training one, because",
"The security team reviewed the access logs and found that",
"In this tutorial we explain how neural networks",
"The river crossed the old town and",
]
gamma, T, t0 = 0.25, 100, time.time()
texts = {}
print(" delta z medio z mín z máx verdes/T NLL medio detectados (z>4)")
for delta in [0, 2, 4]:
rows = []
for j, pr in enumerate(prompts):
toks, nll = generate(big, big.tok.encode(pr).ids, T, gamma, delta, np.random.RandomState(10 + j))
texts[(delta, j)] = toks
Tn, G, z = detect(toks, big.V, gamma)
rows.append((z, G / Tn, nll))
zs = np.array([r[0] for r in rows])
print(f"{delta:6d} {zs.mean():9.2f} {zs.min():7.2f} {zs.max():7.2f} {np.mean([r[1] for r in rows]):9.3f} {np.mean([r[2] for r in rows]):10.3f} {int((zs > 4).sum())}/{len(zs)}")
print("tiempo %.0f s" % (time.time() - t0))npm run lab and open the connection link.In our run, with , , and four prompts, mean z was without a watermark (minimum , maximum , green fraction 0.222), for (minimum 7.49, green fraction 0.659), and for (minimum 14.91, green fraction 0.909). At , detection counts were 0 of 4, 4 of 4, and 4 of 4 texts. Exact text depends on machine arithmetic because rounding can change one token and all subsequent tokens; the figures’ orders of magnitude do not. Unmarked texts stay below the threshold, but four texts cannot estimate the false-positive rate; the theoretical normal p-value is . Green fractions of 0.659 for and 0.909 for are below the respective Jensen bounds of and . Quality has a cost, although the measurement is noisy: mean NLL under the unmarked model is 4.175 without watermarking, 4.120 for , and 4.868 for . With four texts, is indistinguishable from no watermarking, whereas has a visible cost.
small = Pythia("EleutherAI/pythia-14m") # el reescritor: otro modelo, sin marca, con el mismo tokenizador
def rewrite_candidates(prompt_ids, toks):
"""En cada posición, el token que el reescritor habría muestreado dado el texto marcado anterior."""
rs, cache, alts = np.random.RandomState(99), [], []
lg = small.logits(np.array([prompt_ids]), cache)[0].astype(np.float64)
for t in toks:
p = np.exp(lg - lg.max())
alts.append(min(int(np.searchsorted(np.cumsum(p / p.sum()), rs.uniform())), small.V - 1))
lg = small.logits(np.array([[t]]), cache)[0].astype(np.float64)
return alts
alts = {(4, j): rewrite_candidates(big.tok.encode(pr).ids, texts[(4, j)]) for j, pr in enumerate(prompts)}
print("fracción sorteada | tokens cambiados de verdad | z medio con delta = 4 (4 textos x 5 sorteos)")
for eps in [0, 0.1, 0.2, 0.3, 0.4, 0.6]:
zs, changed = [], []
for j in range(len(prompts)):
for rep in range(5):
u = np.random.RandomState(1000 * rep + j).uniform(size=T)
new = [alts[(4, j)][i] if u[i] < eps else texts[(4, j)][i] for i in range(T)]
changed.append(np.mean([a != b for a, b in zip(new, texts[(4, j)])])) # a veces el reescritor elige el mismo token
zs.append(detect(new, big.V, gamma)[2])
print(f"{eps:16.1f} | {np.mean(changed):25.2f} | {np.mean(zs):6.2f} (mín {np.min(zs):5.2f})")npm run lab and open the connection link.The table shows gradual degradation as the randomly selected fraction increases; the next section gives the numbers. The second column highlights a measurement detail: the rewriter sometimes selects the original token, so actually changes 55% of tokens. Pythia-14m is much weaker than an instruction-following LLM paraphraser: it substitutes individual tokens with its own choices, without coherently rewriting the meaning. This is an editing attack rather than a full paraphrase, so it provides only a weak indication of a real adversary’s capabilities. As an exercise, replace rewrite_candidates with a local instruction-tuned model that rewrites the entire text: decode with big.tok.decode, paraphrase, and tokenize again with big.tok.encode before calling detect. Measure again; this requires transformers and a few gigabytes of memory.
Robustness, paraphrasing and distortion-free schemes
The green-list detector measures a local text property: how many (previous token, token) pairs are green. Substituting a token affects its own pair and the next pair, giving a double effect. Experiments show gradual degradation with the rewritten fraction, rather than an abrupt collapse. A sufficiently strong paraphrase can remove the watermark, however, and the literature provides evidence on both sides.
Kirchenbauer and colleagues study the reliability of the marks against human and LLM paraphrases and mixtures of generated and human text. According to their summary, the mark remains detectable in all three cases, because paraphrases tend to preserve n-grams from the original, and after a strong human paraphrase it takes on average 800 tokens to detect it with a false positive rate of . On the other side, Krishna and colleagues build DIPPER, an 11 billion parameter paraphrasing model, and show that paraphrasing without significantly changing the meaning evades several detectors, including watermarks; the only before-and-after figure given in their summary is that of DetectGPT, from 70.3% to 4.6% detection with 1% false positives. Their defense proposes something else: that the provider keeps the generations and searches for approximate matches; with a database of 15 million generations, it detects between 80% and 97% of paraphrases with 1% of human texts classified as generated.
There is no contradiction: outcomes depend on how much text is available, such as 800 tokens versus a typical response of a few hundred; how much is rewritten; and whether rewriting preserves n-grams. In the lab above, with individual-token substitutions, mean z for and falls from 15.14 to 6.24 when 37% of tokens change. The worst of 20 cases remains at 4.24, barely above threshold. With 55% changed, mean z falls to 3.34, below threshold. A strong watermark can withstand moderate edits in long texts; this does not establish protection against an adversary rewriting most of the text.
Distortion-free schemes address another problem: green-list bias changes the distribution and can reduce quality. In the lab, raises mean NLL under the unmarked model from 4.175 to 4.868. Kuditipudi and colleagues construct watermarks whose marginal output distribution is exactly the model’s. The basic idea is an exponential race: given independent , uniform on and derived from a key, choose the token minimizing .
Proof
is exponential with rate 1, so is exponential with rate . The minimum of independent exponentials with rates occurs at with probability .
∎For an observer without the key, the output is an exact sample of the model, without distortion. Someone with the key observes that the of the chosen tokens are abnormally large and can test against a Gamma distribution. Its robust scheme aligns the text with the key sequence via edit distance. According to their abstract, with OPT-1.3B and LLaMA-7B they detect marked text with from 35 tokens even with 40% to 50% of the tokens corrupted by substitutions, insertions or deletions; with Alpaca-7B, where the entropy is lower, only around 25% of the responses (of median about 100 tokens) are detectable with , and it is less robust to certain automatic paraphrases. It is the same law as the green list: the signal comes from entropy.
Exercises
Step 1 of 3. How is matrix written whose row is ?
extract_logistic(query_fn, d): query_fn(x) returns the log-odds of a vector of length d. Recover (w, b) with exactly d + 1 queries.import numpy as np
def extract_logistic(query_fn, d):
pass