AI Wiki中文/EN

Parameter sharing: sum the uses, update once

参数共享

Distinguish tied weights from equal copies through exact gradients, updates and a constrained-model counterexample.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two uses, one parameter

A scalar weight appears in two layers. If those layers refer to one shared parameter, every use contributes to its update. If they merely start with equal numerical values, they are still two parameters. Equality at initialization does not create a constraint that their future updates must represent the same optimization problem.

Deep Learning, Section 9.2 defines parameter sharing and explains how a convolutional kernel reuses weights at spatial positions. Bengio and colleagues’ 2003 language-model paper, Sections 1.2 and 2 provides a different setting: one word-feature table is shared across context positions. The reused object is the parameter, not necessarily its input or output.

The chain rule adds contributions from every use

Imagine temporarily assigning a separate variable uⱼ to each of K uses. Let the full objective with untied variables be L(u₁,…,uₖ). Tying them all to θ gives:

L~(θ)=L(θ,…,θ),∇θL~=∑j=1K∇ujL∣u1=⋯=uK=θ.\widetilde L(\theta)=L(\theta,\ldots,\theta),\qquad \nabla_\theta\widetilde L =\sum_{j=1}^K\left.\nabla_{u_j}L\right|_{u_1=\cdots=u_K=\theta}.

Each use has derivative one with respect to the shared scalar, or an identity Jacobian for identically shaped vectors. The multivariable chain rule therefore sums the partial gradients. A transpose or another transformation at a use site requires its corresponding Jacobian; contributions cannot simply be added with incompatible shapes.

This sum is not an instruction to average automatically. Any division by batch size or number of positions belongs to the specified loss reduction. Dividing again by the number of uses changes the effective update.

Reusing a weight in sequence

Take x=1 and target 1. Apply weight u, then weight v: prediction is vu. With u=v=w, the prediction is w² and the half squared loss satisfies:

L~(w)=12(w2−1)2,dL~dw=2w(w2−1),∂L∂u∣u=v=w=∂L∂v∣u=v=w=w(w2−1).\widetilde L(w)=\tfrac12(w^2-1)^2,\qquad \frac{d\widetilde L}{dw}=2w(w^2-1),\qquad \left.\frac{\partial L}{\partial u}\right|_{u=v=w} =\left.\frac{\partial L}{\partial v}\right|_{u=v=w}=w(w^2-1).

At w=2, each use contributes six, so the shared gradient is twelve. A step of size 1/20 gives w=7/5 and loss 288/625. Updating two independent copies with their own gradients gives u=v=17/10 and loss 35721/20000. They remain equal by symmetry in this example, yet their trajectory differs from the one-parameter update. Averaging the copies afterward does not recover w=7/5.

All partial derivatives must be evaluated at the same original forward state. Updating the shared parameter between processing its uses would mix derivatives from different models.

Sharing is a restriction, not free accuracy

Consider two uses that want opposite values:

L(u,v)=12[(u−1)2+(v+1)2],L~(w)=w2+1,min⁡wL~=1>min⁡u,vL=0.L(u,v)=\tfrac12[(u-1)^2+(v+1)^2],\qquad \widetilde L(w)=w^2+1,\qquad \min_w\widetilde L=1>\min_{u,v}L=0.

The untied optimum is (1,−1); the tied optimum is w=0. At that point, the two contributions −1 and +1 cancel. This is correct differentiation of a constrained model, not a software failure. Sharing reduces degrees of freedom and can express a useful inductive assumption, but it can also prevent the model from fitting relationships that require different parameters.

Compare shared and independent updates

The complete Python 3.12 program uses standard-library fractions. It first computes the two partial gradients of the untied chain, then sums them for one shared update. The output includes an independent-copy comparison and the conflicting-target optimum. Inputs are bounded rationals and the learning rate is restricted to [0,1] for this teaching contract.

from fractions import Fraction as F


def scalar(x):
    if type(x) not in (int,F) or abs(x)>32:raise ValueError('bounded rational required')
    return F(x)


def chain_loss(u,v,x=1,target=1):
    u,v,x,target=[scalar(a) for a in (u,v,x,target)]
    prediction=v*(u*x);error=prediction-target
    return dict(prediction=prediction,loss=error**2/2,du=error*v*x,dv=error*u*x)


def tied_step(w,rate):
    w,rate=scalar(w),scalar(rate)
    if not 0<=rate<=1:raise ValueError('rate must be in [0,1]')
    before=chain_loss(w,w);gradient=before['du']+before['dv']
    updated=w-rate*gradient
    return updated,gradient,before


def conflict_loss(u,v):
    u,v=scalar(u),scalar(v)
    return ((u-1)**2+(v+1)**2)/2


if __name__=='__main__':
    w,gradient,before=tied_step(2,F(1,20))
    print('initial prediction/loss:',before['prediction'],before['loss'])
    print('use gradients:',before['du'],before['dv'],'shared gradient:',gradient)
    print('tied parameter:',w,'new loss:',chain_loss(w,w)['loss'])
    u=F(2)-F(1,20)*before['du'];v=F(2)-F(1,20)*before['dv']
    print('independent equal copies:',u,v,'new loss:',chain_loss(u,v)['loss'])
    print('conflicting targets: tied optimum loss:',conflict_loss(0,0),'untied optimum loss:',conflict_loss(1,-1))

Actual output:

initial prediction/loss: 4 9/2
use gradients: 6 6 shared gradient: 12
tied parameter: 7/5 new loss: 288/625
independent equal copies: 17/10 17/10 new loss: 35721/20000
conflicting targets: tied optimum loss: 1 untied optimum loss: 0

Tests check the literal updates, the derivative of the tied loss by finite differences, and the sum of untied partial derivatives. They also verify the constrained optimum and reject invalid rates or nonfinite inputs. Reusing a d-parameter block K times retains d distinct parameters rather than Kd, but it still performs K uses of the block; parameter savings are not automatically proportional savings in computation or saved activations.

Check identity, reduction and optimizer state

In an automatic-differentiation implementation, make sure the uses refer to the intended shared parameter object. Copies or detached values can break the relationship. Conversely, including the same parameter twice in an update list can apply the optimizer twice even when its gradient was already accumulated correctly.

A shared parameter should have the optimizer state appropriate to that parameter. Several independent momentum states followed by averaging weights generally define a different algorithm. The present example uses plain gradient descent and does not implement a framework’s parameter registration or optimizer machinery.

Regularization also needs counting. Adding the same L 2 penalty once per use can multiply its strength compared with penalizing the distinct shared parameter once. Loss averaging, gradient clipping and accumulation order can further change numerical comparisons, so state those rules before comparing implementations.

Sharing alone does not guarantee invariance. A convolutional model’s translation behavior also depends on stride, padding and the rest of the network. A shared lookup table similarly returns different rows for different token identities, even though all positions use the same table.

How many gradients reach the parameter?

  1. At w=2 in the tied chain, what is the shared gradient?

Answer 1: Twelve, the sum of six from each use.

  1. What is w after a learning-rate 1/20 update?

Answer 2: Seven fifths.

  1. Do equal independent copies necessarily follow the same update as one shared parameter?

Answer 3: No. Here each copy becomes 17/10 while the shared value becomes 7/5.

  1. Why can the two gradients cancel at the tied optimum in the conflicting-target example?

Answer 4: The two uses prefer opposite changes, and the shared model cannot choose separate values.

Sharing connects examples, positions and time steps

The textbook supplies the convolutional definition; the language-model paper supplies shared feature-table use across context positions and acknowledges earlier distributed-representation work. Our scalar chain, exact update comparison and constrained-loss counterexample are original, not reproduced training experiments.

Continue with embedding layers for repeated indices and row-gradient accumulation, or backpropagation for the general chain rule behind shared computation.

Make a prediction, then check

At w2 in the tied two-use example, what gradient updates the shared parameter?

Choose one answer

Learning objectives

  • Accumulate all use-site gradients before updating a shared parameter.
  • Recognize the modeling restrictions imposed by sharing.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Learning — Chapter 9: Convolutional Networks
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
  2. A Neural Probabilistic Language Model
    Yoshua Bengio; Réjean Ducharme; Pascal Vincent; Christian Jauvin · 2003

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed per chapter. Shared gradients, embedding scatter-add, receptive-field geometry and pooling routes are checked against literal references, analytic identities and finite differences. All four examples use exact fractions from the standard library.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
  • Shortened only the Chinese title after visual inspection to avoid splitting a word across lines. Prose, equations, program and exercises unchanged; Chinese SHA rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.