Multi-Task Learning in PyTorch: When Gradients Conflict

Multi-task learning in PyTorch: measure gradient conflict between two tasks, implement PCGrad in ten lines, and find out when projecting gradients pays.

Cover Image for Multi-Task Learning in PyTorch: When Gradients Conflict

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.

Open In Colab

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.

Animation of a multi-task training run over 3000 steps, drawn 200 steps at a time. The left panel plots normalised MSE on a log scale for both tasks, under naive summation in red and PCGrad in green, with task A solid and task B dashed. The two task A curves separate from around step 300 onwards, the red one settling near 0.18 and the green one near 0.08. The two task B curves stay together throughout and end near 0.07. The right panel plots the cosine between the two task gradients, which drops below zero within the first hundred steps and stays there, drifting from about minus 0.35 down to minus 0.8, with a shaded band for the spread across eight seeds. Its title counts the percentage of steps on which the gradients disagree, ending at 99%.

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.

Two panels plotting the cosine between task gradients over 3000 training steps, mean of eight seeds with a shaded 10th to 90th percentile band. In the left panel, tasks reading different features, the curve drops below zero within the first hundred steps and never returns, with a median of minus 0.44 and a title reading negative on 99% of learning steps. In the right panel, tasks reading the same features, the curve climbs to about plus 0.7 by step 500 before falling, with a median of plus 0.42 and a title reading negative on 30% of learning steps. Each panel has a grey dotted vertical line where the losses settle, with the region to its right shaded grey and a note explaining that the gradients there are numerical noise and are not counted.

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 gA+gBg_A + g_B. Task A's loss falls on that step when the update has a positive component along −gA-g_A, which happens when:

gA⋅(gA+gB)>0⟺∥gA∥2+gA⋅gB>0g_A \cdot (g_A + g_B) > 0 \quad \Longleftrightarrow \quad \|g_A\|^2 + g_A \cdot g_B > 0

Divide through by ∥gA∥∥gB∥\|g_A\| \|g_B\| and the condition becomes a statement about the angle and the two lengths:

cos⁡(gA,gB)>−∥gA∥∥gB∥\cos(g_A, g_B) > - \frac{\|g_A\|}{\|g_B\|}

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 ∥gA∥\|g_A\| is small relative to ∥gB∥\|g_B\|. 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.

Two panels showing the same two-dimensional loss surfaces. Blue elliptical contours belong to task A with its optimum at the lower left, amber contours to task B with its optimum at the upper right. A black dot marks the current parameters between them. In the left panel three arrows leave the dot: a short blue arrow for the negative task A gradient pointing down and left, a long amber arrow for the negative task B gradient pointing up, and a red arrow for their sum which points up, almost on top of the amber one, away from task A's optimum. The title records a cosine of minus 0.56 and notes that task B's gradient is 4.0 times longer. In the right panel the original arrows are faded and replaced by their projections, and the green summed arrow now points up and to the left, towards the region between the two optima.

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 gBg_B is scaled by 1/∥gA∥21/\|g_A\|^2, so a short gAg_A 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.

Two panels of loss curves on a log scale, mean of eight seeds with a shaded 10th to 90th percentile band. The left panel is task A, the smaller loss, where the red naive-summation curve settles at 0.182 and the green PCGrad curve settles at 0.082, with a grey dotted line far below at 0.0001 marking what task A reaches trained on its own. The right panel is task B, the larger loss, where the red and green curves lie almost on top of each other and end at 0.069 and 0.070 respectively, above a grey dotted line at 0.0007 for task B trained on its own.

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.

Three panels across the four experimental cells, labelled conflict plus imbalance, conflict only, imbalance only, and neither. A caption explains that conflict means the two tasks read different input features and imbalance means task B's target is three times larger. The first panel plots mean normalised MSE for naive summation in red against PCGrad in green with error bars: 0.125 against 0.076, then 0.024 against 0.019, then 0.059 against 0.037, then 0.001 against 0.001. The second panel plots the median cosine per cell as bars: minus 0.44 and minus 0.30 in red for the two conflict cells, plus 0.42 and plus 0.51 in blue for the two without conflict. The third panel plots the percentage of steps on which the summed update increased task A's loss: 33.1%, 1.8%, 9.4% and 0.0%.

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.

Two panels of loss curves on a log scale, mean of eight seeds with a shaded 10th to 90th percentile band, for the pair that reads the same features at the same scale. In the left panel, task A, the red naive-summation curve and the green PCGrad curve lie on top of each other for the whole run and both end at 0.001, with their bands overlapping throughout. The right panel, task B, is the same picture, both curves ending at 0.001. Grey dotted lines mark 0.0001 and 0.0000 for the two tasks trained on their own.

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

A single panel plotting the ratio of task B's gradient norm to task A's over 3000 training steps on a log scale, median of eight seeds with a shaded 10th to 90th percentile band. The red curve for task B's target three times larger sits above the dashed line at 1.0 with an annotated median over training of 1.77. The blue curve for both targets the same size sits on the line with an annotated median of 1.00.

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.

A scatter plot with task A's normalised MSE on the horizontal axis and task B's on the vertical, lower and further left being better. Four grey points joined by a line trace the loss-weighting sweep: w equals 1/27 at 0.017 and 0.128, w equals 1/9 at 0.042 and 0.089, w equals 1/3 at 0.093 and 0.066, and the w equals 1 point at 0.182 and 0.069, which is marked with a red square as the naive sum. A green star marks PCGrad at 0.082 and 0.070, sitting on the sweep curve between the w equals 1/9 and w equals 1/3 points. A note records that w equals 3 lies off the chart at 0.69 and 0.06, and the title records that each task on its own reaches 0.0001 and 0.0007, far below the frame.

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 ϕij\phi_{ij} as the angle between two task gradients gig_i and gjg_j. We define the gradients as conflicting when cos⁡ϕij<0\cos \phi_{ij} < 0.

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:

Φ(gi,gj)=2∥gi∥2∥gj∥2∥gi∥22+∥gj∥22\Phi(g_i, g_j) = \frac{2 \|g_i\|_2 \|g_j\|_2}{\|g_i\|_2^2 + \|g_j\|_2^2}

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:

cos⁡ϕ12≤−Φ(g1,g2)\cos \phi_{12} \le -\Phi(g_1, g_2)

Read that against the algebra earlier in this post. When the two gradients are the same length, Φ=1\Phi = 1 and the condition demands a cosine of -1, which is exact opposition and does not occur. As the magnitudes diverge, Φ\Phi 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 Φ\Phi 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.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions