Soft prompt tuning: frozen weights, live gradients
软提示调优
Train prepended vectors through frozen attention and separate input prompts from per-layer prefixes.
prompt-tuningFreeze the instrument, adjust the input
A fixed neural network can still produce different outputs when its inputs change. Soft prompt tuning learns a small set of vectors placed before the ordinary input while keeping model weights fixed. Those vectors need not correspond to actual vocabulary words.
“Frozen” therefore cannot mean “turn off every derivative.” To improve a prompt, the loss must send a gradient through the fixed model back to the prompt vectors. Cutting that path makes the trainable prompt unable to learn.
Lester, Al-Rfou and Constant study prompts at the input embedding level. Li and Liang study prefixes that can directly parameterize activations across layers. Both keep the base model fixed, but they do not expose the same trainable variables. Our experiment trains input vectors through one frozen attention layer.
Few trainable values can still require a deep backward pass
Let ordinary token embeddings be and the soft prompt be . Prepending produces:
Position conventions and attention masks must be applied consistently. Appending or prepending the same vectors is not generally equivalent. A prompt also consumes sequence positions or another explicitly managed input budget.
For a frozen model with parameters , prompt training can minimize:
Only is updated. The model remains a differentiable function of , so the chain rule is still required:
Treating the frozen model output as detached from its input destroys this derivative. Freezing its parameter updates and disabling its whole computation graph are different actions.
Our small model contains one input vector after the prompt and reads the final position. For one example, let be that position’s projected query, the keys and values of all positions, and . Attention is:
Fixed matrices project the embeddings. A fixed classifier reads the final input’s residual plus . Because this is a single layer and the final input embedding is fixed with respect to the prompt, its query has no prompt derivative. In deeper models that simplification generally fails.
Let be the loss derivative with respect to . Differentiating softmax attention gives:
A prompt vector affects both its key and its value. Under column-vector projection convention, its gradient is:
The program stores vectors as rows and uses the corresponding transposed operations. It sums each prompt position’s gradients across the batch after the loss has been averaged. A fixed positional vector contributes no trainable parameter but changes the attention computation.
Input prompt parameter count is simply:
At , this is six. Direct key/value prefixes at every layer have a different count and representation; they must not be assigned this formula automatically. Lester’s paper describes initialization choices and the importance of model scale, not a guarantee that any six-dimensional prompt can solve a new task.
Watch a prompt learn through fixed projections
The complete NumPy program fixes 33 attention and classifier weights. A declared teacher prompt produces two-class soft targets on 12 seeded input vectors. Training adjusts only a different two-by-three student prompt. This is a synthetic distribution-matching task, not text generation or pretrained semantic transfer.
"""Backpropagate into prepended soft embeddings through frozen one-layer attention."""
import json
import numpy as np
def frozen():
r=np.random.default_rng(23)
return dict(q=r.normal(0,.6,(3,3)),k=r.normal(0,.6,(3,3)),v=r.normal(0,.6,(3,3)),c=r.normal(0,.8,(3,2)))
def positions(length):return .1*np.sin(np.arange(length)[:,None]+np.arange(3)[None,:])
def forward(prompt,x,w):
p=np.asarray(prompt,float);x=np.asarray(x,float)
if p.ndim!=2 or p.shape[1]!=3 or len(p)>4 or x.ndim!=2 or x.shape[1]!=3 or not len(x) or not np.isfinite(p).all() or not np.isfinite(x).all():raise ValueError('Finite embeddings, up to4 prompt vectors, nonempty inputs required')
h=np.concatenate([np.broadcast_to(p,(len(x),*p.shape)),x[:,None,:]],axis=1)+positions(len(p)+1)
q=h[:,-1]@w['q'];k=h@w['k'];v=h@w['v'];scores=np.einsum('nd,nld->nl',q,k)/np.sqrt(3)
scores-=scores.max(axis=1,keepdims=True);a=np.exp(scores);a/=a.sum(axis=1,keepdims=True)
state=h[:,-1]+np.einsum('nl,nld->nd',a,v);logits=state@w['c'];logits-=logits.max(axis=1,keepdims=True)
logp=logits-np.log(np.exp(logits).sum(axis=1,keepdims=True))
return np.exp(logp),dict(logp=logp,q=q,v=v,a=a)
def objective(prompt,x,target,w):
p,c=forward(prompt,x,w);target=np.asarray(target,float)
if target.shape!=p.shape or not np.isfinite(target).all() or (target<0).any() or not np.allclose(target.sum(axis=1),1,rtol=0,atol=1e-12):raise ValueError('Normalized target rows required')
loss=-float(np.sum(target*c['logp'])/len(x));g=(p-target)@w['c'].T/len(x)
dv=c['a'][:,:,None]*g[:,None,:];da=np.einsum('nd,nld->nl',g,c['v']);ds=c['a']*(da-np.sum(c['a']*da,axis=1,keepdims=True))
dk=ds[:,:,None]*c['q'][:,None,:]/np.sqrt(3)
grad=(dk[:,:len(prompt)]@w['k'].T+dv[:,:len(prompt)]@w['v'].T).sum(axis=0)
return loss,grad
def train(steps=1800):
if type(steps) is not int or not 0<=steps<=10000:raise ValueError('Bounded integer steps required')
w=frozen();x=np.random.default_rng(9).normal(size=(12,3));teacher=np.array([[1.,-.5,.7],[-.7,.6,1.2]])
target,_=forward(teacher,x,w);prompt=np.random.default_rng(17).normal(0,.05,(2,3));initial=prompt.copy();history=[]
entropy=-float(np.sum(target*np.log(target))/len(x))
for i in range(steps+1):
loss,g=objective(prompt,x,target,w)
if i%300==0 or i==steps:history.append(dict(step=i,loss=loss,kl=loss-entropy))
if i<steps:prompt-=.8*g
return prompt,initial,w,x,target,history
def demo():
p,initial,w,x,target,history=train();pred,_=forward(p,x,w);base,_=forward(np.empty((0,3)),x,w)
return dict(trace=history,prompt=p.tolist(),initial_prompt=initial.tolist(),trainable=p.size,frozen_parameters=sum(a.size for a in w.values()),weights_unchanged=all(np.array_equal(a,frozen()[k]) for k,a in w.items()),first_target=target[0].tolist(),first_prediction=pred[0].tolist(),no_prompt_first=base[0].tolist(),gradient_norm=float(np.linalg.norm(objective(initial,x,target,w)[1])),scope='Teacher-generated soft labels, frozen random3D attention, positional vectors; train prompt only; not T5 or natural-language generation')
if __name__=='__main__':print(json.dumps(demo(),allow_nan=False))
The initial gradient norm is approximately 0.00417587. After 1,800 updates, mean KL divergence from the teacher targets falls from approximately 0.00246440 to 0.0000358258. The first target distribution is approximately ; the trained prompt predicts .
The code reports cross-entropy loss minus the fixed target entropy as KL. The loss itself need not approach zero because the teacher’s labels are soft. The no-prompt first-example distribution is also shown, but one example cannot rank whole-dataset performance. Removing the prompt changes the final position as well as the available keys and values in this positional model.
Tests check all six prompt gradients against central finite differences, verify that every frozen weight remains bit-for-bit unchanged, and confirm loss reduction. They check the zero-prompt case, probability normalization, positional sensitivity and the unchanged prompt when zero updates are performed. No upstream framework or model checkpoint is used.
With positions and embedding size , this specialized final-query forward pass costs for projections and attention, excluding a separate output-class dimension. It stores intermediate vectors per example. A full Transformer computes other positions, layers and activation gradients, so its training cost cannot be inferred from six trainable scalars.
A continuous vector is not a sentence with a hidden translation
A learned prompt need not sit near any vocabulary embedding. Replacing each vector by its nearest token generally changes the function and may erase the learned behavior. The prompt depends on the base checkpoint, tokenizer or embedding convention, positions and precision; transferring it to another model is not automatic.
Our teacher is deliberately generated by the same frozen architecture and prompt shape. This makes the target reachable in principle, but neither the optimizer nor arbitrary real tasks come with that guarantee. The tiny positive final KL is an actual numerical result, not proof of global convergence.
Soft prompts preserve the base weights but still add positions and computation. Per-layer prefix tuning can expose more direct control over hidden states, often with another parameterization. Discrete prompt engineering changes ordinary tokens instead of optimizing free embeddings. These methods should be compared with their input budgets and training evidence stated.
Keep the gradient path intact
- Why can a prompt learn while all model weights stay fixed? Answer: The model output is still a differentiable function of the prompt. The backward pass computes input derivatives without updating the fixed projection or classifier weights.
- How many trainable values are in two prompt vectors of dimension three? Answer: Six. The experiment separately contains 33 fixed weights, and intermediate activations consume additional storage.
- Why does the prompt gradient contain both a key and a value term? Answer: Moving a prompt vector changes how much attention it receives and the value it supplies. Omitting either path generally gives the wrong derivative.
- Does replacing learned vectors with nearest vocabulary tokens preserve the model exactly? Answer: No. The replacement changes continuous inputs unless they already equal those embeddings. There is no general meaning-preserving or output-preserving conversion.
Choose where the trainable control enters
Lester and colleagues prepend trainable input embeddings and investigate initialization and scale. Li and Liang allow prefixes to control activations across layers and discuss reparameterization. Their source experiments concern particular pretrained models and tasks; the random frozen attention layer here reproduces neither benchmark.
The example isolates a central implementation requirement: a frozen network can transmit a useful gradient to a trainable input. A real prompt-tuning experiment must then establish held-out task quality, robustness to formatting and actual training and inference costs.
Make a prediction, then check
How can a prompt learn when all model weights are frozen?
Learning objectives
- Derive prompt gradients through fixed key and value projections.
- Distinguish parameter freezing from disabling differentiation.
- State capacity, positional and deployment limits of soft prompts.
Prerequisites & connections
Explore related knowledge →References
- The Power of Scale for Parameter-Efficient Prompt Tuning
Brian Lester; Rami Al-Rfou; Noah Constant · 2021 - Prefix-Tuning: Optimizing Continuous Prompts for Generation
Xiang Lisa Li; Percy Liang · 2021
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author viewed Lester EMNLP2021 PDF2/3 sections2/2.1 and Li/Liang ACL2021 PDF4/5 sections3.3/4.1–4.3. Seven paired equations and four explained exercises. Actual prompt training through fixed attention, all six finite-difference gradients, key/value paths, frozen33 weights, positions and zero-prompt checks. Teacher soft labels on random3D model, no T5 or language-transfer claim.
- Single AI author viewed Lester EMNLP2021 PDF2/3 sections2/2.1 and Li/Liang ACL2021 PDF4/5 sections3.3/4.1–4.3. Seven paired equations and four explained exercises. Actual prompt training through fixed attention, all six finite-difference gradients, key/value paths, frozen33 weights, positions and zero-prompt checks. Teacher soft labels on random3D model, no T5 or language-transfer claim.
- Four computed SVG variants per topic;11 numeric/geometry tests and36 responsive cases passed. Twelve selected captures checked:seven final directly viewed,five byte-identical to previously viewed images. Full article acceptance recorded separately.
Source locations checked:
- The Power of Scale for Parameter-Efficient Prompt Tuning · Viewed PDF2/3: section2/2.1, frozen model, input soft embeddings, prompt parameter count, initialization and opening2.2 span-corruption qualifications. No T5 scale experiment reproduced.
- Prefix-Tuning: Optimizing Continuous Prompts for Generation · Viewed PDF4/5: section3.3 likelihood, Figure2,4.1–4.3 per-layer prefix, frozen weights, backpropagation and reparameterization. No generation benchmark reproduced.
Related topics