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 is the output at position , the one that predicts token .
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 callkeepevery timetok_embruns, soseenholds the latest token embeddings.- Autograd fills
.gradonly on tensors you made withrequires_grad=True, like the weights.retain_grad()asks it to fill this computed one's.gradtoo. logits[0, t].sum().backward()sends a gradient back from output positiontalone. The list marks each input position whose embedding got any of it.
In a healthy model, which input positions does output 3 send gradient to?
Pick an answer above to see the rest