Suppose a model already predicts one measurement well, and you want it to predict a second from the same inputs. Sharing part of the network could save you from training and maintaining two separate models. But after adding the second task, the first prediction starts getting worse, even though the training loop runs normally. Multi-task learning in PyTorch trains both tasks through those shared weights.
PCGrad, introduced by Yu and colleagues in 2020, removes the component of one task's gradient that opposes the other when their inner product is negative. We implement the projection and measure gradient direction and magnitude separately, because their relative sizes determine whether the summed update harms a task.
The measurement turns out to be more useful than the fix. One task pair below disagrees on 97% of training steps, and the summed update still moves both tasks forward on 98% of them, because a disagreement only costs you something when the losing task's gradient is also the smaller one. Changing the relative size of the losses raises task A's unexplained variance from 0.026 to 0.182. Projecting the gradients brings it back to 0.082.
By the end of this post you will measure conflict in a shared-trunk model, implement PCGrad in about ten lines of PyTorch, and read the 2x2 that says whether reaching for it is worth the compute. Every experiment below runs on a laptop CPU in about three minutes.
Let's Build It
Open this in Google Colab and run it top to bottom.
Two regression tasks share one small encoder and get one linear head each. Task A reads input dimensions 0 and 1. Task B reads dimensions 2 and 3, and its target is three times larger, so its loss and its gradient are larger too. The left panel below tracks how much of each task's variance the model still fails to explain. The right panel tracks the angle between the two tasks' gradients.

The setup is deliberately small. Eight input dimensions, 512 samples, a six-unit trunk, two linear heads.
import torch
import torch.nn as nn
D_IN, N_SAMPLES, HIDDEN = 8, 512, 6
def make_tasks(pair, seed=0, amp_b=3.0):
"""Two regression targets on one input matrix."""
g = torch.Generator().manual_seed(1234 + seed)
x = torch.rand(N_SAMPLES, D_IN, generator=g) * 2 - 1
def target(i, j):
return torch.sin(2.5 * x[:, i] + 1.5 * x[:, j]) + 0.5 * x[:, i] * x[:, j]
y_a = target(0, 1)
y_b = target(2, 3) if pair == "conflict" else target(0, 1)
return x, y_a.unsqueeze(1), (amp_b * y_b).unsqueeze(1)
class SharedTrunk(nn.Module):
def __init__(self, hidden=HIDDEN):
super().__init__()
self.trunk = nn.Sequential(
nn.Linear(D_IN, hidden), nn.Tanh(),
nn.Linear(hidden, hidden), nn.Tanh(),
)
self.head_a = nn.Linear(hidden, 1)
self.head_b = nn.Linear(hidden, 1)
def forward(self, x):
h = self.trunk(x)
return self.head_a(h), self.head_b(h)
Both task pairs use the same functional form, so the only thing that changes between them is which input dimensions task B reads, and any difference in behaviour traces back to that alone.
The usual training step calls (loss_a + loss_b).backward(). This one takes the two gradients separately, because you cannot measure an angle between two vectors you have already added together.
def flat_grad(loss, params):
"""One flat vector holding the gradient of `loss` with respect to `params`."""
grads = torch.autograd.grad(loss, params, retain_graph=True)
return torch.cat([g.reshape(-1) for g in grads])
model = SharedTrunk()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
trunk_params = list(model.trunk.parameters())
x, y_a, y_b = make_tasks("conflict")
for step in range(3000):
pred_a, pred_b = model(x)
loss_a = ((pred_a - y_a) ** 2).mean()
loss_b = ((pred_b - y_b) ** 2).mean()
g_a = flat_grad(loss_a, trunk_params)
g_b = flat_grad(loss_b, trunk_params)
cos = torch.dot(g_a, g_b) / (g_a.norm() * g_b.norm())
That cos is the whole diagnostic. Run it on both task pairs and the two regimes separate immediately.

Tasks that read different input dimensions have gradients pointing away from each other on 99% of steps, with a median cosine of -0.44. Tasks that read the same dimensions sit at +0.42 and disagree on 30% of steps. The two regimes are far enough apart that a single run tells you which one you are in, and both are measured in the same 96-dimensional space, the parameters of the shared trunk.
One detail matters for taking this measurement on your own model. Cosine similarity is only informative while the gradients still carry signal. Once both losses settle, what is left is numerical noise, and its angle means nothing. Every summary number in this post is computed over the steps before the losses flatten, marked by the dotted line in each panel above.
What Just Happened?
The shared trunk as the contested resource
The two heads never compete. head_a sees only task A's loss and head_b only task B's, so their gradients are unrelated. Every disagreement lives in model.trunk, the six-unit encoder both tasks have to share.
Six units is not enough to encode a function of dimensions 0 and 1 and a separate function of dimensions 2 and 3 at full fidelity. Something has to give, and the geometry of the two gradients decides which task does the giving.
The descent condition
Write the update the optimiser receives under loss_a + loss_b. It is . Task A's loss falls on that step when the update has a positive component along , which happens when:
Divide through by and the condition becomes a statement about the angle and the two lengths:
A negative cosine on its own breaks nothing. If both gradients are the same length, the right-hand side is -1, and no angle short of exact opposition can push task A backwards. The summed update stays a descent direction for both tasks however much they disagree.
The condition only bites when is small relative to . Then the threshold rises towards zero, an ordinary conflict clears it, and the update that helps task B increases task A's loss. Nothing in the training loop reports this, because both losses are still falling on average. Task A ends lower than it would have.
The projection
PCGrad removes the offending component. When two gradients disagree, each one gives up the part of itself that points against the other, and the survivors are summed.
def pcgrad_combine(g_a, g_b):
"""Yu et al. (2020), Algorithm 1, for two tasks."""
dot = torch.dot(g_a, g_b)
if dot >= 0:
return g_a + g_b
pc_a = g_a - dot / g_b.dot(g_b) * g_b
pc_b = g_b - dot / g_a.dot(g_a) * g_a
return pc_a + pc_b
Ten lines, no state, no hyperparameter. When the gradients agree it returns the plain sum unchanged, so in that regime its only cost is the second backward pass.

The left panel is the failure. Task B's gradient is four times longer, so the red sum lands almost on top of it and the update walks away from task A's optimum. After projection, the green arrow tilts back towards the region between the two optima.
The geometry also explains why the correction is asymmetric. The amount subtracted from is scaled by , so a short produces a large correction to the long gradient. The projection damps whichever task was shouting.
Applying it to the trunk only
The combined vector goes back onto the shared parameters. The heads keep their own gradients, since a head that only one task can see has nothing to conflict with.
def assign_flat(params, vec):
"""Write a flat vector back into .grad on each parameter."""
i = 0
for p in params:
n = p.numel()
p.grad = vec[i:i + n].view_as(p).clone()
i += n
head_params = list(model.head_a.parameters()) + list(model.head_b.parameters())
# in the training loop, in place of (loss_a + loss_b).backward()
opt.zero_grad(set_to_none=False)
assign_flat(trunk_params, pcgrad_combine(g_a, g_b))
for p, g in zip(head_params, torch.autograd.grad(loss_a + loss_b, head_params)):
p.grad = g.clone()
opt.step()
Several published implementations flatten every parameter instead, heads included. The dot product comes out the same, because each task's gradient is zero in the other head's slots. The projection then writes a nonzero correction into head slots the task cannot see, which is harmless in practice and confusing to read. Yu et al. apply the surgery to shared parameters, and so does the code above.
The result on the conflicting pair
Same seeds, same initialisation, same optimiser settings, one line different.

Task A ends at 0.182 of its variance unexplained under summation and 0.082 under PCGrad, averaged over eight seeds. Task B ends at 0.069 and 0.070, statistically indistinguishable. The projection recovered more than half of task A's shortfall and took nothing from task B to do it.
Both dotted lines are a long way below both curves. Trained on its own with the same trunk and a longer budget, task A reaches 0.0001 and task B 0.0007, so multi-task training here costs task A three orders of magnitude even at its best. Six hidden units cannot hold both functions, and gradient surgery redistributes that shortage without removing it.
Going Deeper
The 2x2
Two ingredients appeared in the algebra above: a negative cosine, and a magnitude gap. Crossing them gives four experiments. The task pair either reads the same input dimensions or different ones, and task B's target is either the same size as task A's or three times bigger.

Read the second and third panels together. Both different-features cells conflict about equally, at a median cosine of -0.44 and -0.30. Only one of them suffers for it. With the targets the same size, the summed update pushes task A backwards on 1.8% of steps and the two methods land within a standard deviation of each other. With task B three times larger, that figure is 33.1%, and the projection is worth having.
This is the paper's own claim, reproduced at toy scale. Yu et al. are explicit about it in section 2.2:
However, conflicting gradients are not detrimental on their own. Indeed, simply averaging task gradients should provide the correct solution to descend the multi-task objective.
The fourth cell is the one to check for before adopting anything. Same features, same scale, gradients agreeing on more than three quarters of steps, and the summed update never once moving task A backwards across eight seeds and 3000 steps.

Both curves land on 0.001 for both tasks, the bands sit on top of each other for the whole run, and the second backward pass bought nothing. This is the cell most worth checking for before adopting a method, because a model in it looks exactly like a model in the first cell until you measure the angle.
The magnitude gap on its own

Tripling a target multiplies its squared error by nine, and the gradient it produces follows. That is the whole source of the imbalance here, and it is a fair model of how the problem arises in practice: a detection loss and a regression loss measured in different units, a cross-entropy term next to an L2 term, one task with far more labelled data than another.
The third cell of the 2x2 is worth a second look. Tasks reading the same features, median cosine +0.42, and still the summed update sets task A back on 9.4% of steps, with a gradient-norm ratio of 5.75. The two gradients agree on direction while task B's is nearly six times longer. Loss weighting fixes that, and GradNorm (Chen et al., 2018) automates the weighting by driving each task's gradient norm towards a common target.
Loss weighting as the competing baseline
Anyone reaching for gradient surgery should first ask what a scalar would have done. Sweeping the weight on task B over a factor of 81 traces out a curve of achievable pairs.

PCGrad lands at (0.082, 0.070), close to the curve the weight sweep traces and roughly where a weight of about 1/3 would put you. A weight of 1/9 reaches a mean normalised MSE of 0.065 against PCGrad's 0.076, so the tuned scalar wins on this problem.
PCGrad reaches a good point on that curve without the sweep, choosing per step from the geometry instead of committing to one number in advance. On four tasks the sweep becomes a four-dimensional search and the argument shifts. On two tasks with a compute budget for tuning, weight the losses.
The cost
Every step needs one backward pass per task rather than one for the sum. On this toy that is 2x; on a real encoder where the backbone dominates, expect something between 1.5x and 2x wall-clock, plus memory for holding the per-task gradients. torch.autograd.grad with retain_graph=True keeps the graph alive across those calls, which is where the memory goes.
Against that, the measurement itself is nearly free. Two gradients you were going to compute anyway, one dot product, two norms. Log the cosine and the norm ratio for a few hundred steps of an existing multi-task model before deciding anything.
The decision rule
The 2x2 gives a decision procedure. Log cos and ‖g_B‖/‖g_A‖ during a normal run. If the median cosine sits near zero or positive, the tasks are not fighting and no projection method will help. If it is firmly negative but the norms are comparable, the sum is still a descent direction for both tasks and you have no problem to solve. Both conditions together, a firmly negative cosine and a norm ratio far from one, is the regime where the projection earns its compute.
Two caveats on the toy. Its conflict is constructed, with tasks reading disjoint input dimensions, which is stronger than most real task pairs. And it is small enough that a six-unit trunk is a hard capacity ceiling, so the trade-off between tasks is sharper than you would see with a backbone that has room to spare.
Where This Comes From
PCGrad was introduced by Tianhe Yu, Saurabh Kumar, Abhishek Gupta, Sergey Levine, Karol Hausman and Chelsea Finn in "Gradient Surgery for Multi-Task Learning" (NeurIPS 2020, arXiv:2001.06782). They were working on multi-task reinforcement learning, where a single policy trained on several robotic manipulation tasks was performing worse than policies trained on each task alone.
Their diagnosis names three conditions together, which they call the tragic triad: conflicting gradients, a large difference in gradient magnitudes so that one task dominates, and high curvature along the direction of the multi-task gradient. Definition 1 states the first:
We define as the angle between two task gradients and . We define the gradients as conflicting when .
Definition 2 states the second as a gradient magnitude similarity, which is 1 when the two gradients are the same length and falls towards 0 as they diverge:
The full update rule, their Algorithm 1, generalises the two-task version above to any number of tasks. Each task's gradient is projected in turn against the others, sampled in random order:
Require: model parameters θ, task minibatch B = {T_k}
1: g_k <- ∇_θ L_k(θ) for all k
2: g_k^PC <- g_k for all k
3: for T_i in B do
4: for T_j sampled uniformly from B \ T_i, in random order do
5: if g_i^PC · g_j < 0 then
6: g_i^PC <- g_i^PC - (g_i^PC · g_j) / ‖g_j‖^2 · g_j
7: return update Δθ = Σ_i g_i^PC
Their Theorem 2 gives the condition under which one PCGrad step lowers the multi-task loss more than the summed gradient does. The first of its three conditions is:
Read that against the algebra earlier in this post. When the two gradients are the same length, and the condition demands a cosine of -1, which is exact opposition and does not occur. As the magnitudes diverge, falls towards 0 and an ordinary conflict satisfies it. The guarantee describes a conflict large enough to outrun the magnitude gap. The other two conditions require the curvature along the multi-task gradient to be large enough, and the step size to be big enough that the resulting misestimation matters.
Condition (a) is worth logging alongside the raw cosine, and it is a stricter test than the one derived earlier. On the conflicting, imbalanced pair, the summed update moved task A backwards on 33.1% of steps while condition (a) held on 3.7% of them, with a median of 0.86. So the single-step guarantee fired rarely, and PCGrad still halved task A's error over 3000 steps. A sufficient condition for one step to improve says little about where a trajectory ends up, which is the usual gap between an optimisation guarantee and an experiment.
Further reading
- The original paper: Yu et al. (2020), "Gradient Surgery for Multi-Task Learning" (free PDF). Sections 2.2 to 2.4 carry the definitions, the algorithm and the two theorems.
- The magnitude problem: Chen et al. (2018), "GradNorm: Gradient Normalization for Adaptive Loss Balancing in Deep Multitask Networks" (arXiv:1711.02257). Learns the loss weights instead of projecting the gradients.
- The multi-objective framing: Sener and Koltun (2018), "Multi-Task Learning as Multi-Objective Optimization" (arXiv:1810.04650). Treats the problem as finding a Pareto-stationary point and applies the multiple-gradient descent algorithm.
- The general version: Quinton and Rey (2024), "Jacobian Descent for Multi-Objective Optimization" (arXiv:2406.16232), released as TorchJD. Stacks the per-task gradients into a Jacobian and picks an update from it with an aggregator, of which PCGrad is one choice among many.
- Next algorithm to learn: GradNorm, if the diagnostic on your own model shows a norm ratio far from 1 and a cosine near zero.
Interactive Tools
- Regression Playground: Fit and compare regression models on your own points, the single-task version of what the two heads here are doing.
- Overfitting Explorer: Capacity against error, which is the constraint that makes the six-unit trunk in this post a contested resource.
Related Posts
- Optimisers from Scratch: SGD, Momentum and Adam: The Adam settings used here come from this post, and it covers what the optimiser does with the vector once you have combined it.
- Backprop, Jacobians and Hessians: The Jacobian framing that Jacobian descent generalises, and why first-order methods dominate in practice.
- Transfer Learning for NLP: The sequential version of sharing a trunk between tasks, where the conflict shows up as forgetting instead.
- Continual Learning and Catastrophic Forgetting: What happens when the two tasks arrive one after the other rather than together.
- The Universal Approximation Theorem in NumPy: Why width is the resource the two tasks are competing over.





