AI Wiki中文/EN

GRU: two gates, two reset conventions

门控循环单元

Compare reset-before and reset-after GRUs with identical parameters, exact preactivations and complete state-Jacobian checks.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two gates, but the formula still matters

A GRU uses one hidden-state vector and two sigmoid gates. The update gate mixes an old state with a candidate; the reset gate changes how old information enters that candidate. There is no separate LSTM-style cell-state vector, but this smaller state interface does not make every GRU implementation identical.

Cho and colleagues’ 2014 paper, Section 2.3, equations 5–8 defines the reset operation before a recurrent matrix multiplication. The fixed PyTorch 2.8 GRU documentation explicitly uses a different candidate calculation and explains the difference. We implement both conventions so that a checkpoint reproduction can be checked against equations, not just the name GRU.

The update gate here means the retained fraction

For each gate q in reset r and update z, compute an affine function of current input xₜ and previous hidden state hₜ₋₁:

qt=σ(Wiqxt+biq+Whqht−1+bhq),q∈{r,z}.q_t=\sigma(W_{iq}x_t+b_{iq}+W_{hq}h_{t-1}+b_{hq}),\qquad q\in\{r,z\}.

All operations are coordinate-wise where a vector gate multiplies another vector. In this convention, z close to one keeps more old state. Some descriptions use a complementary gate for writing new state; the name alone does not tell you which coefficient multiplies which term.

Write aₜ for the input-side candidate affine term, U for its recurrent matrix and bₕ for its recurrent bias. The two candidate formulas are:

ntbefore=tanh⁡ ⁣(at+U(rt⊙ht−1)+bh),ntafter=tanh⁡ ⁣(at+rt⊙(Uht−1+bh)).n_t^{\mathrm{before}}=\tanh\!\left(a_t+U(r_t\odot h_{t-1})+b_h\right),\qquad n_t^{\mathrm{after}}=\tanh\!\left(a_t+r_t\odot(Uh_{t-1}+b_h)\right).

The original paper’s displayed candidate is the reset-before form without explicit bias terms. The extended bias notation above follows the comparison in the fixed API documentation. PyTorch uses reset-after. A diagonal reset multiplication generally does not commute with a dense recurrent matrix; the bias placement also differs. Even a scalar example can differ when a recurrent bias is present.

A two-coordinate example makes the difference large enough to see

Let h=(1,2), r=(1/4,3/4), z=(1/2,1/2), input candidate term zero and recurrent bias zero. Let U swap the two coordinates. Reset-before first forms (1/4,3/2), then swaps it to (3/2,1/4). Reset-after first swaps h to (2,1), then gates it to (1/2,3/4). Tanh therefore receives different inputs before the state mixture is even applied.

The resulting states are approximately (0.952574127,1.122459331) and (0.731058579,1.317574476). The same numerical weights and gates have not reproduced the same cell. The example’s initial second coordinate is two; there is no claim that an arbitrary initial state must already lie inside the tanh range.

A direct carry term is not the full Jacobian

Using either candidate n, the update and full hidden-state Jacobian are:

ht=zt⊙ht−1+(1−zt)⊙nt,Jt=diag⁡(zt)+diag⁡(ht−1−nt)Dz+diag⁡(1−zt)Dn.h_t=z_t\odot h_{t-1}+(1-z_t)\odot n_t,\qquad J_t=\operatorname{diag}(z_t) +\operatorname{diag}(h_{t-1}-n_t)D_z +\operatorname{diag}(1-z_t)D_n.

Here Dz and Dn are derivatives of z and n with respect to the previous hidden state. The first term is the direct carry route; the other terms follow from the product rule. Dn must differentiate the chosen reset placement, including the reset gate’s dependence on h. Treating the gates as constants in a general cell omits those terms.

For fixed gate values in [0,1], each output coordinate is between its old-state and candidate values. If the initial state lies in [−1,1] coordinate-wise, tanh candidates and the mixture preserve that interval in real arithmetic. This bounded-state statement does not bound all derivatives with respect to parameters or previous states.

Return the candidate and the complete derivative

The complete Python 3.12 / NumPy 1.26.4 program uses parameter blocks in r,z,n order, separate input/recurrent biases and column vectors. It returns both the candidate preactivation and the full state Jacobian. Inputs and parameter shapes are checked; the reset-placement mode must be explicit or use the declared reset-after default.

The example sets gate weights to zero and chooses biases so sigmoid produces r=(1/4,3/4) and z=(1/2,1/2). It still evaluates the gates normally. The final recurrent block is the coordinate-swap matrix.

import numpy as np


def bounded(value):
    a=np.array(value,dtype=np.float64,copy=True)
    if not np.isfinite(a).all() or np.any(np.abs(a)>8):raise ValueError('finite entries with magnitude at most 8 required')
    return a


def sigmoid(a):
    a=np.asarray(a,dtype=float);out=np.empty_like(a);positive=a>=0
    out[positive]=1/(1+np.exp(-a[positive]));e=np.exp(a[~positive]);out[~positive]=e/(1+e)
    return out


def gru(x,h,wi,wh,bi,bh,mode='after'):
    x,h,wi,wh,bi,bh=[bounded(v) for v in (x,h,wi,wh,bi,bh)]
    if x.ndim!=1 or h.ndim!=1 or not 1<=len(x)<=4 or not 1<=len(h)<=4:raise ValueError('bounded feature/state vectors required')
    size=len(h)
    if wi.shape!=(3*size,len(x)) or wh.shape!=(3*size,size) or bi.shape!=(3*size,) or bh.shape!=(3*size,):raise ValueError('r,z,n parameter shapes required')
    if mode not in ('before','after'):raise ValueError('reset mode must be before or after')
    affine=wi@x+bi+wh@h+bh;r=sigmoid(affine[:size]);z=sigmoid(affine[size:2*size])
    dr=np.diag(r*(1-r))@wh[:size];dz=np.diag(z*(1-z))@wh[size:2*size]
    un=wh[2*size:];recurrent_bias=bh[2*size:];incoming=wi[2*size:]@x+bi[2*size:]
    if mode=='before':
        pre=incoming+un@(r*h)+recurrent_bias
        dpre=un@(np.diag(r)+np.diag(h)@dr)
    else:
        rec=un@h+recurrent_bias;pre=incoming+r*rec
        dpre=np.diag(r)@un+np.diag(rec)@dr
    candidate=np.tanh(pre);dn=np.diag(1-candidate*candidate)@dpre
    new_h=z*h+(1-z)*candidate
    jac=np.diag(z)+np.diag(h-candidate)@dz+np.diag(1-z)@dn
    return dict(h=new_h,r=r,z=z,candidate=candidate,pre=pre,jacobian=jac)


if __name__=='__main__':
    wi=np.zeros((6,1));wh=np.zeros((6,2));wh[4:]=[[0,1],[1,0]]
    bi=np.array([-np.log(3),np.log(3),0,0,0,0]);bh=np.zeros(6)
    for mode in ('before','after'):
        result=gru([0],[1,2],wi,wh,bi,bh,mode)
        print(mode,'reset:',np.round(result['r'],6).tolist(),'update:',result['z'].tolist())
        print('candidate preactivation:',result['pre'].tolist(),'new state:',np.round(result['h'],9).tolist())
        print('state Jacobian:',np.round(result['jacobian'],9).tolist())

Actual output:

before reset: [0.25, 0.75] update: [0.5, 0.5]
candidate preactivation: [1.5, 0.25] new state: [0.952574127, 1.122459331]
state Jacobian: [[0.5, 0.06776499], [0.117501856, 0.5]]
after reset: [0.25, 0.75] update: [0.5, 0.5]
candidate preactivation: [0.5, 0.75] new state: [0.731058579, 1.317574476]
state Jacobian: [[0.5, 0.098305967], [0.223719678, 0.5]]

Tests check these literal preactivations and resulting states, a scalar recurrent-bias counterexample, and both full-state Jacobians against finite differences with nonzero gate recurrent weights. They also check the bounded-state interval for valid initial states and reject shape/mode/nonfinite-input errors.

An ordinary vector GRU forward step costs O(H(D+H)); this implementation additionally constructs dense state Jacobians, which can add O(H³) work and O(H²) storage. Hidden width is limited to four for this audit. The code stores separate biases, so its parameter count is 3HD+3H²+6H. It does not implement batching, stacked layers, sequence packing or a training optimizer.

Resetting a candidate does not erase every route

Even when a reset gate makes the candidate ignore recurrent content, the update equation can still retain old h through z. If the candidate is zero and z is one half, the new state is half the old state. “Reset” describes an operation inside the candidate computation, not an unconditional full-state reset.

Changing gate conventions without converting the complete equations can reverse the meaning of a parameter or silently change a model. A reset-before checkpoint cannot generally be loaded unchanged into a reset-after cell and expected to match. Differences in biases, gate order and matrix orientation also need checking.

Sigmoid and tanh can saturate numerically. A gate near one may create a useful carry path, but hidden-dependent gate derivatives and recurrent candidate derivatives still affect the total gradient. Long-sequence training requires its own loss, BPTT policy, initialization and validation.

The cited paper studied a particular encoder-decoder and translation setup; the documentation defines a software operation. Our two-coordinate comparison is not a performance comparison between GRUs and LSTMs, or between frameworks.

Before or after what?

  1. In this update convention, does z near one favor the old state or the candidate?

Answer 1: The old state.

  1. What candidate preactivations arise from reset-before in the swap example?

Answer 2: (3/2,1/4).

  1. What preactivations does reset-after produce from the same values?

Answer 3: (1/2,3/4).

  1. Is diag(z) alone the full state Jacobian of a general GRU?

Answer 4: No. The gate and candidate depend on the previous state, adding the Dz and Dn terms.

Reproducibility starts at the candidate equation

We inspected the fixed September 3,2014 v 3 paper and the fixed PyTorch 2.8 equations, including its reset-order note. The two-mode implementation, swap and bias counterexamples, product-rule Jacobian and tests are original. We did not reproduce the translation experiments or copy a framework kernel.

Continue with LSTM to compare state interfaces and BPTT to train through repeated cells. Similar gate names are not sufficient evidence that two recurrent models compute the same function.

Make a prediction, then check

What candidate preactivation does reset-after produce in the swap example?

Choose one answer

Learning objectives

  • Reproduce a GRU only after specifying reset and bias placement.
  • Differentiate the full hidden-state update including gate dependence.

Prerequisites & connections

Explore related knowledge →

References

  1. Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation — arXiv1406.1078v3
    Kyunghyun Cho; Bart van Merriënboer; Caglar Gulcehre; Dzmitry Bahdanau; Fethi Bougares; Holger Schwenk; Yoshua Bengio · 2014
  2. GRU — PyTorch 2.8
    PyTorch contributors

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. Recurrent state carry, full/cut BPTT and LSTM/GRU state Jacobians are checked against literal references, independent forward sensitivities, frozen-boundary surrogates and finite differences. RNN/GRU use NumPy1.26.4; BPTT/LSTM use 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.

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.