Module contents
Lesson 28 of 39Core 100 min

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, log⁡2K\log_2 K bits into KK classes).
  • The probabilities (or log-probabilities) of all classes: one real number per class.
  • The largest kk 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 p(x)=σ(w⊤x+b)p(\vb{x})=\sigmoid(\vb{w}\T\vb{x}+b), and the API returns pp. If 0<p<10<p<1, the logit logit⁡(p)=ln⁡p1−p=w⊤x+b\operatorname{logit}(p)=\ln\frac{p}{1-p}=\vb{w}\T\vb{x}+b is a linear function of the input. Each query gives a linear equation in the d+1d+1 unknowns (w,b)(\vb{w},b):

ln⁡p(0)1−p(0)=b,ln⁡p(ei)1−p(ei)−b=wi,i=1,…,d.\ln\frac{p(\vb{0})}{1-p(\vb{0})}=b,\qquad \ln\frac{p(\vb{e}_i)}{1-p(\vb{e}_i)}-b=w_i,\quad i=1,\dots,d.

With d+1d+1 queries, at the origin and the dd standard basis vectors, solve the linear system to recover w\vb{w} and bb exactly, up to arithmetic rounding. For KK softmax classes, ln⁡pcpK=(wc−wK)⊤x+(bc−bK)\ln\frac{p_c}{p_K}=(\vb{w}_c-\vb{w}_K)\T\vb{x}+(b_c-b_K) gives K−1K-1 equations per query. The same d+1d+1 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 d+1d+1 and the error is of the order of the machine epsilon.

[ ]Exact extraction of logistic regression with d + 1 queriesBrowser
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 w\vb{w} and bb with a maximum error of 5⋅10−165\cdot10^{-16}. No approximation: it’s linear algebra. Now degrade the output as a naive defense would: round the probability to kk decimals. The exact system stops giving the answer, but you can compensate noise with more queries, solving an overdetermined system by least squares:

[ ]Rounding of the output and least squaresBrowser
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 w\vb{w} is 1.9⋅10−21.9\cdot10^{-2} for d+1=9d+1=9 queries and falls to 1.4⋅10−31.4\cdot10^{-3} for a thousand; with four decimal places, it is already 2.7⋅10−42.7\cdot10^{-4} 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 {x:w⊤x+b=0}\{\vb{x}:\vb{w}\T\vb{x}+b=0\} can be located by bisection: given two points with different labels, each midpoint query halves the segment containing the boundary. Fit the hyperplane using m≥dm\ge d boundary points. Each point costs about b+2b+2 queries for bb bits of precision:

[ ]Only the label: bisection towards the boundaryBrowser
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 4.7⋅10−64.7\cdot10^{-6} 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 4.7⋅10−64.7\cdot10^{-6}) than probabilities rounded to 4 decimal places with 1000 queries (error 1.9⋅10−51.9\cdot10^{-5}). 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.

InteractiveTo steal a decision boundary
  • ━ victim's boundary
  • ━ substitute boundary
  • ┅ true circle
  • ● query with class 1
  • ● query with class 0
  • random, label
  • boundary only, label
  • mixed (4 + 4), label
  • random, probability

Curves: average of 6 executions (seeds 0 to 5); the band goes from the worst to the best execution of the chosen strategy, and the gray dashed line is the same strategy with the other API output. Victim: 2-16-1 network with ReLU trained on 160 points of the dotted circle with an 8% of label changes, giving accuracy of 0.937 and not 1. Substitute: 2-12-1 network with tanh trained with Adam on the queries. Test: 1600 fixed uniform points.

Queries
The API returns
128
Execution (seed)
Curve metric
Queries B128
Fidelity with the victim0.911
Accuracy (true label)0.928
Fidelity: average and worst of 6 executions0.926 / 0.911
Victim's accuracy0.937
Victim: an MLP 2-16-1 with ReLU trained on 160 points of the dotted circle, with 8% of labels flipped. You choose the query strategy, API output, budget, and execution; the substitute (2-12-1 with tanh) of that execution is trained in the browser on what you have queried. Below, the fidelity (or accuracy) versus the budget: mean of 6 executions calculated with the same code, with a band spanning the worst to the best run.

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 ∣logit∣\lvert\text{logit}\rvert 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:

[ ]Victim: an MLP trained with noisy labelsBrowser
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:

[ ]Learning-based Extraction: Random vs ActiveBrowser
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")
[ ]Learning-based Extraction: Queries Near the BoundaryBrowser
table("active", "label")
table("active", "prob")
[ ]Learning-based extraction: boundary and explorationBrowser
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 y=0y=0 with many queries to the logit. Each neuron jj from the hidden layer contributes w2,jmax⁡(0,aj(x))w_{2,j}\max(0,a_j(x)) with aj(x)=W1,j x+b1,ja_j(x)=W_{1,j}\,x+b_{1,j} on that line; upon crossing aj=0a_j=0 the slope of the logit changes suddenly, in xj=−b1,j/W1,jx_j=-b_{1,j}/W_{1,j} and with a jump of w2,j ∣W1,j∣w_{2,j}\,\lvert W_{1,j}\rvert. 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 221.52^{21.5} queries in less than an hour, coinciding with the oracle with maximum error 2−252^{-25}, and one with 4,000 parameters with 218.52^{18.5} queries and maximum error 2−40.42^{-40.4}; they report copies 2202^{20} more precise with 100 times fewer queries than the previous state of the art.

[ ]Critical points of a ReLU network along a lineBrowser
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 [−2,2][-2,2] are detected as 14 slope changes, with errors on the order of 10−1410^{-14} in position and 10−1110^{-11} 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 VV tokens. The final layer is a linear projection: if h(x)∈Rh\vb{h}(x)\in\R^{h} is the hidden state after the last normalization, the logits are ℓ(x)=Wh(x)\vb{\ell}(x)=\mat{W}\vb{h}(x) with W∈RV×h\mat{W}\in\R^{V\times h}. But hh, typically in the thousands, is much smaller than VV, in the tens or hundreds of thousands. All logit vectors lie in a subspace of RV\R^V with dimension ≤h\le h, which is visible through the rank.

Proof

Matrix multiplication does not increase the rank: rank⁡(AB)≤min⁡{rank⁡A,rank⁡B}\rank(\mat{A}\mat{B})\le\min\{\rank\mat{A},\rank\mat{B}\}, and H\mat{H} has hh columns, then rank⁡H≤h\rank\mat{H}\le h. The bias adds 1b⊤\vb{1}\vb{b}\T, that has rank ≤1\le1, and the rank of a sum is at most the sum of the ranks. The same for −c1⊤-\vb{c}\vb{1}\T. □\square

∎

This is the idea behind the attack by Carlini and colleagues: collect N>hN>h output vectors and compute their SVD. The first hh singular values are large; subsequent values fall to floating-point noise. The index of this drop is hh, the hidden dimension. The singular vectors also provide a basis for the logit subspace, the column space of W\mat{W}, recovering the final projection layer W\mat{W} up to an invertible transformation G∈Rh×h\mat{G}\in\R^{h\times h}: Wh=(WG−1)(Gh)\mat{W}\vb{h}=(\mat{W}\mat{G}^{-1})(\mat{G}\vb{h}) for any invertible G\mat{G}, while h\vb{h} 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 kk 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.

InteractiveThe hidden dimension in the singular values
  • singular values
  • threshold

N × 50304 matrix of log-probabilities differences (logits modulo a constant) from random 16-token prompts, calculated with the laboratory cell. The singular values come from the double precision Gram matrix: the floor, between 10^-7 and 10^-8, is numerical noise (the API returns single precision), not signal.

Victim model
The API returns
256
-6
Queries N256
Estimated rank at this threshold128
Values below 10^-7 (noise)128
Singular values of the matrix of N vectors of output from two open models, Pythia-14m (h = 128) and Pythia-70m (h = 512), calculated with the code from the local cell below (same random prompts, with N up to 256 and 640) and pre-recorded here. Change N, the output, and the threshold and notice the collapse.

Why does the drop occur, and why is it not always at hh? With N≤hN\le h, nothing is visible: an N×VN\times V matrix has at most NN nonzero singular values, all carrying signal. Once NN exceeds the rank, the next singular value falls sharply. At the maximum NN, Pythia-14m’s differences drop from 10−2.95≈1.1⋅10−310^{-2.95}\approx1.1\cdot10^{-3} times the largest value to 10−7.810^{-7.8}; Pythia-70m drops from 10−4.310^{-4.3} to 10−7.210^{-7.2}, the noise floor of single-precision API outputs. The rank threshold has some margin: changing it from 10−610^{-6} to 10−510^{-5} leaves the result unchanged; lowering it below 10−710^{-7} for Pythia-70m or 10−810^{-8} for Pythia-14m starts counting noise. Now enable Reveal. Pythia-14m’s log-probabilities have rank 129 =h+1=h+1, while differences from a reference column, which give logits modulo a per-prompt constant, have rank 128 =h=h, as in the theorem. For Pythia-70m, the differences have rank 511 =h−1=h-1, 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 h=γ⊙n+β\vb{h}=\boldsymbol\gamma\odot\vb{n}+\boldsymbol\beta, with zero-mean normalized n\vb{n} satisfying ∑ini=0\sum_in_i=0. Solving for ni=(hi−βi)/γin_i=(h_i-\beta_i)/\gamma_i gives ∑ihi/γi=∑iβi/γi\sum_ih_i/\gamma_i=\sum_i\beta_i/\gamma_i for every output: they lie in an affine hyperplane of dimension h−1h-1. If the right-hand side is nonzero, this hyperplane does not pass through the origin and its points span all of Rh\R^h, giving rank hh; if it is zero, they span only the hyperplane, giving rank h−1h-1. The cell below prints this sum: −5.3477-5.3477 for Pythia-14m and −0.0005-0.0005 for Pythia-70m, so close to zero that the extra direction remains in the noise. The methodological lesson is that the drop gives hh up to ±1\pm1 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 10−310^{-3} relative to the maximum logit magnitude, sufficient for the experiments below.

[ ]A forward pass of Pythia in numpyLocal GPU
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"].T
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]The API and attack toolsLocal GPU
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())
This cell needs the local lab (PyTorch with your GPU). Start it with 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 Q\mat{Q} must satisfy Q=(W−1w0⊤)G\mat{Q}=(\mat{W}-\vb{1}\vb{w}_0\T)\mat{G} for some G\mat{G}. Fit G\mat{G} using two-thirds of the vocabulary rows and measure error on the remaining third. A random matrix provides a negative control.

[ ]Recovering the projection up to GLocal GPU
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, out
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Hidden dimension of two modelsLocal GPU
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, LP
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The cell output confirms the theorem and its qualification. For Pythia-14m (h=128h=128), N=200N=200 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 W−1w0⊤\mat{W}-\vb{1}\vb{w}_0\T is 1.5⋅10−61.5\cdot10^{-6}, versus 1.0 for a random matrix. Pythia-70m (h=512h=512), with N=530N=530, gives ranks 512 and 511, a 511-column basis, and error 9.7⋅10−49.7\cdot10^{-4}: larger because the small singular values lie closer to noise, but 1000 times smaller than the control. The final LayerNorm sum ∑iβi/γi\sum_i\beta_i/\gamma_i is −5.3477-5.3477 for Pythia-14m and −0.0005-0.0005 for Pythia-70m. Also inspect the ratios σi/σ1\sigma_i/\sigma_1: Pythia-14m’s 129th log-probability singular value, the extra log-sum-exp direction, is 2.0⋅10−42.0\cdot10^{-4}; the 130th is already noise at 7.6⋅10−97.6\cdot10^{-9}. For Pythia-70m with these 530 prompts, the 512th is only 7.1⋅10−67.1\cdot10^{-6}, so a threshold of 10−510^{-5} would count 511. With 640 prompts in the figure, that value rises to 10−4.3510^{-4.35}. The threshold margin depends on NN, another reason to verify the basis rather than just count singular values.

Recovering the final layer does not copy the entire model: it reveals W\mat{W} and hh, 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.

  1. 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 kk decimal places is ≈0.25⋅10−k\approx0.25\cdot10^{-k}, averaging a uniform error between zero and half a rounding step. With k=1k=1, very different probabilities such as 0.05 and 0.14 become identical, damaging calibration and ranking across examples.
  2. Return only labels or top-kk outputs. This reduces information per query, but bisection compensates in O(d b)\bigO(d\,b) queries, as seen above. With top-kk, logit biases can expand the remaining information.
  3. Limit logit biases and controlled decoding. This closes the channel used to reconstruct full LLM output vectors, without affecting most users.
  4. 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.
  5. 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.

InteractiveThe cost of each defense
  • exact probability
  • rounded to 3 decimals
  • label only (20 boundary points, b bits)

Victim: logistic regression with d = 10 variables and ‖w‖ = 3. The attacker queries x ~ N(0, 0.25 I), calculates the log-odds of the returned probability and fits by least squares; with the label it searches for 20 points of the boundary and fits the hyperplane. Below 10^-12 the error depends on the rounding of each machine and is shown as floor; the queries with saturated probability after rounding are discarded.

API output
100
3
16
Attacker queries100
Directional error of w9.3e-4
Correct digits3.0
Legitimate user cost (mean error of p)2.6e-4
Directional error of w (vertical axis, log scale) against the number of attacker queries. Choose the API output: exact probability, rounded to k decimals, or just the label. The vertical marker follows the fit that you have set; readings include what the legitimate user loses.

Two readings. First: with exact probability, 11 queries (d+1d+1) already give an error below 10−1210^{-12}, the floor of the figure; with rounding to 3 decimals, 11 queries leave the error in 2.6⋅10−22.6\cdot10^{-2}, and there are about 100 needed to drop below 10−310^{-3} and about 400 to get to 5.0⋅10−45.0\cdot10^{-4}. The rounding curve drops slowly, approximately as 1/n1/\sqrt n, because the attacker only averages noise. Second: the label-only curve drops as 2−b2^{-b} with the bisection steps: with 20 boundary points and 20 steps, 490 queries leave the error in 6.7⋅10−76.7\cdot10^{-7}, 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 2.5⋅10−32.5\cdot10^{-3} with 2 decimals and 2.6⋅10−42.6\cdot10^{-4} 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 mm triggers and cc classes, an unmarked model matches each label with probability 1/c1/c if labels were chosen randomly and independently of the data. The match count therefore follows Bin(m,1/c)\mathrm{Bin}(m,1/c). For c=10c=10, 12 matches out of 20 have tail probability 5.8⋅10−85.8\cdot10^{-8} 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 ti−1t_{i-1}, partition the vocabulary into a green set of fraction γ\gamma and a red set. Add δ>0\delta>0 to green-token logits, then sample using the usual decoding procedure. Given T+1T+1 tokens, the detector reconstructs the list at each position from the preceding token and counts how many of the final TT tokens are green: ∣s∣G|s|_G.

The z-test

For unmarked text and a pseudorandom partition independent of its content, each token is green with probability γ\gamma, and ∣s∣G∼Bin(T,γ)|s|_G\sim\mathrm{Bin}(T,\gamma) if the TT 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

z=∣s∣G−γTT γ (1−γ)z=\frac{|s|_G-\gamma T}{\sqrt{T\,\gamma\,(1-\gamma)}}

is approximately N(0,1)\Normal(0,1) under the null hypothesis, which is rejected when zz exceeds a threshold. This is a one-sample proportion test. At threshold z=4z=4, the one-sided normal p-value is 3.2⋅10−53.2\cdot10^{-5}. This is per text: over nn texts, the expected number of false positives is n⋅3.2⋅10−5n\cdot3.2\cdot10^{-5}. For very large zz, the normal approximation is inaccurate in the tail: with γ<1/2\gamma<1/2, the binomial is right-skewed and the normal underestimates its upper tail. You will check this in the exercise with T=200T=200.

How much can the signal rise

Let qq be the probability mass assigned to green tokens at one step. After adding δ\delta to their logits, the green mass becomes

q′(q)=q eδ1−q+q eδ,q'(q)=\frac{q\,e^{\delta}}{1-q+q\,e^{\delta}},

because green tokens’ unnormalized weights are multiplied by eδe^\delta. The function q′q' is concave, and a pseudorandom list gives expected green mass E[q]=γ\E[q]=\gamma; Jensen’s inequality gives

E[q′]≤q′(γ)=γ eδ1+γ(eδ−1).\E[q']\le q'(\gamma)=\frac{\gamma\,e^{\delta}}{1+\gamma(e^{\delta}-1)}.

For γ=0.25\gamma=0.25, this is 0.4750.475 with δ=1\delta=1, 0.7110.711 with δ=2\delta=2, and 0.9480.948 with δ=4\delta=4. The maximum is attained only when the green mass at every step is already γ\gamma, corresponding to high-entropy distributions. In a low-entropy step with one token’s probability near 1, the green mass qq is 00 or 11 and q′(q)=qq'(q)=q: the watermark cannot shift it, and the token is green only with probability γ\gamma. Text with little freedom, such as code or very-low-temperature responses (see temperature sampling), is therefore harder to watermark. Applying top-kk or nucleus filtering after the bias further restricts its effect by discarding low-probability green tokens. The expected signal is E[z]≲T (q′(γ)−γ)/γ(1−γ)\E[z]\lesssim\sqrt T\,(q'(\gamma)-\gamma)/\sqrt{\gamma(1-\gamma)}: it grows as T\sqrt T, and a green fraction ρ\rho requires approximately T≈16γ(1−γ)/(ρ−γ)2T\approx16\gamma(1-\gamma)/(\rho-\gamma)^2 tokens to reach z=4z=4.

InteractiveWatermarked text
Stealing a model is cheaper than training one, because

green red according to the detector. The first token only provides context. Dashed underline: rewritten position. Tokens that have truly changed: 0 (sometimes the rewriter chooses the same token).

  • δ = 1
  • δ = 2
  • δ = 4
  • threshold z = 4

With δ = 2 and γ = 0.25, mean z falls below 4 after rewriting about 40 % of positions (T = 100). The rewrites are the tokens that Pythia-14m, without a watermark, would have chosen in each position given the preceding watermarked text.

γ (green fraction)
δ (logit bias)
100
0 %
Green tokens / evaluated63 / 100
Green fraction (expected γ)0.63 (0.25)
z8.78
One-sided p-value8.6e-19
Verdict with z > 4watermarked
Text generated by Pythia-70m with the green-list watermark for several values of γ and δ (same key, same starting text, and same random numbers in all cases). Click tokens to rewrite them with the token that Pythia-14m would have sampled without the watermark, or increase the rewritten fraction, and see how long it takes for the signal to disappear. Below, the mean z-score of eight random rewrites for three values of δ.

With δ=0\delta=0, no watermark, z fluctuates around zero: for T=100T=100, between −0.6-0.6 and 2.02.0 depending on γ\gamma. In the initial state, δ=2\delta=2, T=100T=100, and γ=0.25\gamma=0.25, z is 8.78, below the formula’s bound of 10.6510.65 for that TT (63 green tokens out of 100). Now try γ=0.75\gamma=0.75: the same δ\delta gives z of 5.31, because a large γ\gamma leaves little room between the baseline green fraction and 100%100\%. With δ=1\delta=1 and γ=0.1\gamma=0.1, 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 γ=0.25\gamma=0.25 and T=100T=100, mean z drops below 4 after rewriting 20% of positions for δ=1\delta=1 (3.72), 40% for δ=2\delta=2 (3.87), and 60% for δ=4\delta=4 (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.

[ ]Green list, generation with mark and detectorLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Detection: z versus deltaLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In our run, with γ=0.25\gamma=0.25, T=100T=100, and four prompts, mean z was −0.64-0.64 without a watermark (minimum −1.80-1.80, maximum 0.290.29, green fraction 0.222), 9.409.40 for δ=2\delta=2 (minimum 7.49, green fraction 0.659), and 15.1415.14 for δ=4\delta=4 (minimum 14.91, green fraction 0.909). At z>4z>4, 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 3.2⋅10−53.2\cdot10^{-5}. Green fractions of 0.659 for δ=2\delta=2 and 0.909 for δ=4\delta=4 are below the respective Jensen bounds of 0.7110.711 and 0.9480.948. Quality has a cost, although the measurement is noisy: mean NLL under the unmarked model is 4.175 without watermarking, 4.120 for δ=2\delta=2, and 4.868 for δ=4\delta=4. With four texts, δ=2\delta=2 is indistinguishable from no watermarking, whereas δ=4\delta=4 has a visible cost.

[ ]Attack of rewriting with another modelLocal GPU
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})")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The table shows gradual degradation as the randomly selected fraction ε\varepsilon increases; the next section gives the numbers. The second column highlights a measurement detail: the rewriter sometimes selects the original token, so ε=0.6\varepsilon=0.6 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 zz 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 10−510^{-5}. 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 δ=4\delta=4 and T=100T=100 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, δ=4\delta=4 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 u1,…,uVu_1,\dots,u_V, uniform on (0,1)(0,1) and derived from a key, choose the token tt minimizing −ln⁡ut/pt-\ln u_t/p_t.

Proof

Et=−ln⁡utE_t=-\ln u_t is exponential with rate 1, so Et/ptE_t/p_t is exponential with rate ptp_t. The minimum of independent exponentials with rates ptp_t occurs at tt with probability pt/∑sps=ptp_t/\sum_s p_s=p_t. □\square

∎

For an observer without the key, the output is an exact sample of the model, without distortion. Someone with the key observes that the utu_t of the chosen tokens are abnormally large and can test ∑i−ln⁡(1−uti)\sum_i-\ln(1-u_{t_i}) 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 p≤0.01p\le0.01 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 p≤0.01p\le0.01, and it is less robust to certain automatic paraphrases. It is the same law as the green list: the signal comes from entropy.

Exercises

Proof
Prove: Prove that the logits matrix of N prompts from an LLM with a final linear layer has a rank at most h, and h + 1 if the projection carries bias.
0
The final layer is ℓ(x)=Wh(x)+b\vb{\ell}(x)=\mat{W}\vb{h}(x)+\vb{b}, with W∈RV×h\mat{W}\in\R^{V\times h} and h(x)∈Rh\vb{h}(x)\in\R^h. Apply the rank bounds for products and sums.

Step 1 of 3. How is matrix L∈RN×V\mat{L}\in\R^{N\times V} written whose row ii is ℓ(xi)⊤\vb{\ell}(x_i)\T?

Numeric
A green list detector evaluates T = 200 tokens with γ = 0.25 and finds 90 greens. Calculate the z-score.
Numeric
A weak watermark uses γ = 0.5 and δ = 1. In its best case (at each step the green mass of the model is exactly γ), how many tokens T are needed for the expected z to reach 4? Give T without rounding to an integer.
Numeric
You verify the property of a model with 20 triggers whose labels were randomly chosen among 10 classes. The suspect model gets 12 correct. If not marked, each correct has probability 1/10 and is independent. What is the p-value P(X ≥ 12) in units of 10⁻⁸?
CodeExtract logistic regression exactly
Implement extract_logistic(query_fn, d): query_fn(x) returns the log-odds w⊤x+b\vb{w}\T\vb{x}+b 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
Shift+Enter to run
Quiz
What statement about the cost of stealing the hyperplane is correct for a d-variable logistic regression API that only returns the label (0 or 1)?
Quiz
An API rounds the probability to 2 decimals. In the cell with d = 8, the angular error was 1.9e-2 with d + 1 queries and 1.4e-3 with 1000. How do you assess the defense?
Quiz
An LLM API only returns the 5 largest log-probabilities for each query, but allows adding an arbitrary bias to any token. Why does this fail to prevent final-layer extraction?
Quiz
A PRADA type query detector marks customers whose sequence of queries deviates from the benign distribution. What limit should you expect?
Quiz
The victim in the figure has task accuracy of 0.937. You have two stolen substitutes: A, with accuracy 0.955 and fidelity 0.952; B, with accuracy 0.936 and fidelity 0.983. You want to locally fabricate adversarial examples that deceive the victim. Which one do you use?
Quiz
A text generated with a green-list watermark gives z = 15.1. After changing 55% of the tokens with another model, the average z is 3.3 (values from the rewriting cell). What is the correct conclusion?
Quiz
A model generates code with temperature almost 0 and very few plausible alternatives per token. What do you expect from the green-list watermark?

Summary

Key idea
Each API response gives an equation involving the weights. With probabilities or logits, d + 1 queries suffice for a linear model, and the output rank reveals an LLM’s final-layer dimension; with labels alone, bisection adds a logarithmic precision factor. API defenses increase extraction cost and must be evaluated by both query cost and lost utility for legitimate users. Model watermarks, fingerprints, and dataset inference provide evidence of copying. For text, green-list watermarking uses a z-test whose signal depends on entropy and degrades gradually with editing.