12/30
Part 3 of 6 · CausalityLearn and do

A gradient chart shows the shape of a leak

The causal test says that a leak exists. A chart shows where it is.

def dependency_chart(model: nn.Module, V: int, T: int = 6) -> None:
    """Prints which inputs each output t sends gradient to."""
    seen = {}

    def keep(module: nn.Module, inputs: tuple, out: torch.Tensor) -> None:
        out.retain_grad()
        seen["emb"] = out
    hook = model.tok_emb.register_forward_hook(keep)
    try:
        for t in range(T):
            logits, _ = model(torch.randint(0, V, (1, T)))
            logits[0, t].sum().backward()
            print(t, [int(g.abs().sum() > 0) for g in seen["emb"].grad[0]])
    finally:
        hook.remove()

When the causality test fails, get a picture of the leak. Send a gradient back from one output, and see which inputs receive any of it. Row tt is the output at position tt, the one that predicts token t+1t + 1.

The idea is all that matters here, not the API names. Keep the token embeddings from the latest forward pass, and ask autograd for their gradient. In this code:

  • register_forward_hook(keep) makes PyTorch call keep every time tok_emb runs, so seen holds the latest token embeddings.
  • Autograd fills .grad only on tensors you made with requires_grad=True, like the weights. retain_grad() asks it to fill this computed one's .grad too.
  • logits[0, t].sum().backward() sends a gradient back from output position t alone. The list marks each input position whose embedding got any of it.
Predict

In a healthy model, which input positions does output 3 send gradient to?

Pick an answer above to see the rest