AI Wiki中文/EN

ControlNet: zero connections, gradient gates and spatial conditions

ControlNet

Train a small residual branch and test when zero initialization opens or blocks learning.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Add a spatial request without replacing the generator

A text prompt can describe a person raising an arm, but it does not specify every joint coordinate. A pose map, edge map or depth map provides a different kind of condition: a spatial arrangement the generator should follow while choosing remaining visual details.

ControlNet’s 2023 proposal adds trainable conditioning branches to a pretrained diffusion network. Zero-initialized output connections make the augmented block initially reproduce the base block’s output. This starting equality is useful, but it does not promise that the trained model will always preserve the original output or obey every control exactly. Read convolution, backpropagation and text-to-image generation first.

Zero projections gate gradients, while balanced batches can cancel the initial learning signal.
Zero projections gate gradients, while balanced batches can cancel the initial learning signal.

Zero output does not mean zero learning everywhere

Let F(x;θ) be a pretrained block. Keep θ fixed, create a trainable copy θc, and introduce affine zero projections Z₁ and Z₂. The abstract augmented block is:

yc=F(x;θ)+Z2(F(x+Z1(c);θc)).y_c=F(x;\theta)+Z_2\left(F(x+Z_1(c);\theta_c)\right).

This is the structure in §3.1. A 1×1 convolution mixes channels at each spatial position with shared weights. “Zero convolution” means its weights and biases start at zero; it does not mean they remain zero or that all weights in the copied block are zero.

Our two-channel row-vector version writes the trainable branch explicitly:

v=x+cA+b1,h=tanh⁡(vWc),y^=tanh⁡(xW0)+hB+b2.v=x+cA+b_1,\qquad h=\tanh(vW_c),\qquad \hat y=\tanh(xW_0)+hB+b_2.

A, Wc and B are 2×2 matrices; b₁ and b₂ each have two entries. There are 16 trainable parameters. Initialize A,b₁,B,b₂ to zero and Wc to W₀. Then:

y^∣B=0,b2=0=tanh⁡(xW0).\hat y\big|_{B=0,b_2=0}=\tanh(xW_0).

The zero outer projection is sufficient for this equality. Copying pretrained weights gives the branch a useful starting representation once that projection changes; it is not necessary merely to multiply its current output by zero.

For N rows, use half the mean squared error over both channels. If G is the derivative with respect to predictions, then G=(ŷ−y)/(2N). Differentiating the last projection gives:

∇BL=h⊤G,∇b2L=∑iGi,∇hL=GB⊤.\nabla_B L=h^\top G,\qquad \nabla_{b_2}L=\sum_i G_i,\qquad \nabla_h L=GB^\top.

At B=0, the gradient entering h is zero, but the gradient of B can be nonzero. Once B moves, gradients can reach the copied block and condition projection. Writing U=(GBᵀ)⊙(1−h²):

∇WcL=v⊤U,∇AL=c⊤UWc⊤,∇b1L=∑i(UWc⊤)i.\nabla_{W_c}L=v^\top U,\qquad \nabla_A L=c^\top UW_c^\top,\qquad \nabla_{b_1}L=\sum_i(UW_c^\top)_i.

The order of these operations explains the initial gradient gate. It does not guarantee that a whole batch’s outer gradient is nonzero. Terms can cancel even if individual examples have nonzero features and errors.

For example, let x and c be independent balanced two-dimensional sign vectors. Define the target as the base prediction plus .6c. At initialization the residual is −.6c, while h depends only on x. Therefore:

E[h⊤c]=E[h]⊤E[c]=0,E[c]=0.\mathbb E[h^\top c]=\mathbb E[h]^\top\mathbb E[c]=0,\qquad \mathbb E[c]=0.

Both outer weight and bias gradients vanish under the exact full balanced distribution; the remaining gradients are blocked by B=0. The half-MSE is still .18. This counterexample refutes a universal “nonzero input guarantees an update” claim, not the usefulness of zero connections in actual training. A minibatch or a different target can break the cancellation.

Watch the gradient enter the branch

Save as controlnet.py; use Python 3.12 and NumPy 1.26.4. The program enumerates all 16 combinations of two input signs and two condition signs. The main target adds .3x+.6c to the frozen base. The x-dependent residual makes the first outer gradient nonzero. Every parameter derivative is written explicitly and checked independently by finite differences, both at initialization and away from it.

For N rows and channel width d, each dense pointwise block costs O(Nd²), and its activations cost O(Nd); this example uses d=2. An image ControlNet additionally runs a condition encoder and copied multiscale diffusion blocks. The small operation count is not a full U-Net memory or latency estimate.

"""Original two-channel residual control block with two zero projections."""
import itertools,json
import numpy as np
BASE=np.array([[.7,.2],[-.1,.9]])

def dataset():
    values=np.array(list(itertools.product([-1.,1.],repeat=4)))
    return values[:,:2],values[:,2:]

def initial():return np.r_[np.zeros(6),BASE.ravel(),np.zeros(6)]

def objective(theta,x,c,target):
    theta=np.asarray(theta,float);x=np.asarray(x,float);c=np.asarray(c,float);target=np.asarray(target,float)
    if theta.shape!=(16,) or x.ndim!=2 or x.shape[1]!=2 or c.shape!=x.shape or target.shape!=x.shape or not len(x) or not all(np.isfinite(a).all() for a in [theta,x,c,target]):raise ValueError('Invalid parameters or matched two-channel arrays')
    a=theta[:4].reshape(2,2);b1=theta[4:6];w=theta[6:10].reshape(2,2);b=theta[10:14].reshape(2,2);b2=theta[14:]
    v=x+c@a+b1;h=np.tanh(v@w);prediction=np.tanh(x@BASE)+h@b+b2;error=prediction-target;g=error/error.size
    gb=h.T@g;gb2=g.sum(axis=0);gz=(g@b.T)*(1-h*h);gw=v.T@gz;gv=gz@w.T;ga=c.T@gv;gb1=gv.sum(axis=0)
    return float(np.mean(error**2)/2),np.r_[ga.ravel(),gb1,gw.ravel(),gb.ravel(),gb2],prediction

def train(updates=3000):
    if not isinstance(updates,int) or isinstance(updates,bool) or not 0<=updates<=6000:raise ValueError('Invalid updates')
    x,c=dataset();target=np.tanh(x@BASE)+.3*x+.6*c;theta=initial();history=[];gradients=[]
    for step in range(updates+1):
        loss,g,_=objective(theta,x,c,target)
        if step%500==0 or step==updates:history.append(loss)
        if step<3:gradients.append(dict(condition=float(np.linalg.norm(g[:6])),copy=float(np.linalg.norm(g[6:10])),output=float(np.linalg.norm(g[10:]))))
        if step<updates:theta-=.1*g
    return theta,history,gradients

def output(theta,x,c,strength=1.):
    if not np.isfinite(strength) or not 0<=strength<=2:raise ValueError('Strength must be in[0,2]')
    prediction=objective(theta,x,c,np.zeros_like(x))[2];base=np.tanh(np.asarray(x)@BASE)
    return base+strength*(prediction-base)

def demo():
    x,c=dataset();theta,history,gradients=train();base=np.tanh(x@BASE);zero=initial();dead_target=base+.6*c;dead_loss,dead_grad,_=objective(zero,x,c,dead_target)
    return dict(training_half_mse=history,first_gradients=gradients,initial_base_error=float(np.max(abs(output(zero,x,c)-base))),disabled_branch_error=float(np.max(abs(output(theta,x,c,0)-base))),zero_condition_branch_change=float(np.max(abs(output(theta,x,np.zeros_like(c))-base))),balanced_control_only_loss=dead_loss,balanced_control_only_gradient=float(np.linalg.norm(dead_grad)),parameters=theta.tolist(),scope='Two-channel tanh block with16 trained parameters on a balanced synthetic grid; no U-Net, diffusion training or spatial-image benchmark.')
if __name__=='__main__':print(json.dumps(demo(),indent=2))

The initial output exactly matches the base. On the first update, condition and copied-block gradient norms are zero while the output-projection norm is about .139727. On the next evaluation they become approximately .001907, .001116 and .136616. Training with rate .1 for 3,000 steps lowers half-MSE from .225 to about 4.38×10⁻¹³ on this fully enumerated task.

The separate pure-condition target retains loss .18 and an initial gradient norm about 1.76×10⁻¹⁷, floating-point residue around the exact cancellation. A single example has a nonzero outer gradient. Do not remove the counterexample or change its seed to make every training setup appear successful.

The frozen base matrix remains byte-for-byte unchanged. Yet setting the condition input to zero after training changes the output by as much as .67766 relative to the base: the branch also processes x and can have biases. To disable the residual branch explicitly, use a strength a:

y(a)=ybase+a(ycontrolled−ybase).y(a)=y_{\mathrm{base}}+a\left(y_{\mathrm{controlled}}-y_{\mathrm{base}}\right).

At a=0 the base is restored. This is different from supplying an all-zero hint. Interpolating or amplifying the residual need not yield calibrated semantic control.

Frozen weights still transmit derivatives

The paper’s Stable Diffusion integration copies encoder and middle blocks, encodes the spatial hint and adds control outputs to the corresponding decoder connections. The fixed implementation produces multiple residual outputs and scales them before injection. Our two-channel block captures the zero-connection mechanism, not the full spatial network or its training objective.

Freezing parameters is not the same as stopping all activation gradients. A frozen downstream decoder must still transmit derivatives back to injected control features if the control branch is to learn. The inspected implementation uses no_grad for the original encoder/middle path, then processes controlled features through the output path. Its optimizer also has an sd_locked option that can include decoder parameters; identify the configuration before saying the whole backbone is frozen.

An inaccurate pose, edge or depth condition can produce an inaccurate constraint. Competing text and spatial conditions need explicit tests; an edge match does not establish correct object identity or physical geometry. Exact initial equality, preservation of frozen parameter values, final sample quality and control adherence are four different claims. The synthetic training loss proves only the stated block’s fit.

For retaining particular pixels or following an edit instruction rather than an external spatial map, compare generative image editing. Real workflows should evaluate both requested control and unintended changes, with their sampling budget and preprocessing fixed.

Follow a zero through the chain rule

  1. Calculation. At B=0, can the copied block receive a first-step gradient? Can B itself receive one? Answer: The copied block receives GBᵀ=0. B receives hᵀG, which may be nonzero. “May” matters because a batch can cancel it.
  2. Prediction. Set the trained condition input c to zero. Must the output equal the base? Answer: No. The branch still receives x and its learned biases. Setting its final residual strength to zero, rather than zeroing the hint, restores the base in this construction.
  3. Boundary. Why does the independent balanced target base+.6c have a zero full-batch initial gradient despite positive loss? Answer: h depends only on x, while the condition has zero mean and is independent of x. Thus the cross-moment hᵀc and the mean residual vanish; upstream branch gradients are blocked by the zero outer weight.
  4. Transfer. May a frozen downstream decoder be wrapped entirely in no_grad during control-branch training? Answer: Not if that discards the derivative from loss to control features. Its weights can stay fixed while its activation Jacobian remains in the computation graph.

Inspect the abstract block and its actual placement

Read ControlNet v1 §3.1–3.2, Figure 2 and the zero-connection equations, then the fixed forward, injection and optimizer methods. PDF pages 2,4,5 were inspected. The early paper’s channel-index notation is replaced here by an explicit row-matrix derivation and all-parameter gradient checks; no universal nonzero-gradient claim is inherited. The code version, scope and Apache license heading are recorded, but no upstream code, weights or image benchmarks are reproduced.

Make a prediction, then check

Does a zero condition input disable a trained control branch?

Choose one answer

Learning objectives

  • Derive zero-connection gradients.
  • Identify exact initial equality and later residual effects.
  • Verify a batch-cancellation counterexample.
  • Distinguish frozen weights from stopped activation gradients.

Prerequisites & connections

Explore related knowledge →

References

  1. Adding Conditional Control to Text-to-Image Diffusion Models (v1)
    Lvmin Zhang; Maneesh Agrawala · 2023
  2. controlnet-model reference at ed85cd1
    lllyasviel/ControlNet contributors · 2023

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked ControlNet v1 selected section3.1-3.2/equations1-8 and fixed cldm.py freeze/residual code. Seven paired equations and four explained exercises; original sixteen-parameter two-channel block, all gradients, identity initialization, gate sequence, frozen base, balanced-batch cancellation and zero-hint versus disabled branch. No U-Net reproduction or universal nonzero-first-gradient claim.

  • Single AI author checked ControlNet v1 selected section3.1-3.2/equations1-8 and fixed cldm.py freeze/residual code. Seven paired equations and four explained exercises; original sixteen-parameter two-channel block, all gradients, identity initialization, gate sequence, frozen base, balanced-batch cancellation and zero-hint versus disabled branch. No U-Net reproduction or universal nonzero-first-gradient claim.
  • Four computed SVG variants per topic. Thirteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. English spacing correction and initial test-mixin discovery error preserved. Full article acceptance recorded separately.

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.