REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Project conflicting task gradients without mutating their owners

Return a detached [tasks, parameters] matrix of PCGrad gradients. For each task, visit the other ORIGINAL task gradients in a seed-local shuffled order. If the current projected gradient has a negative dot product with an original peer, remove that component. Skip zero-norm peers. Do not mutate the input or global RNG. The caller chooses how to combine the projected rows; this Lab does not assert that a mean improves every task.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Project conflicting task gradients without mutating their owners →

Your task

Return a detached [tasks, parameters] matrix of PCGrad gradients. For each task, visit the other ORIGINAL task gradients in a seed-local shuffled order. If the current projected gradient has a negative dot product with an original peer, remove that component. Skip zero-norm peers. Do not mutate the input or global RNG. The caller chooses how to combine the projected rows; this Lab does not assert that a mean improves every task.

Starter

import random
import torch

def project_conflicts(gradients, seed=0):
    # TODO: implement project_conflicts under the declared contract.
    return None
Inspect the worked answer
import random
import torch

def project_conflicts(gradients, seed=0):
    if gradients.ndim!=2 or gradients.shape[0]<2 or gradients.shape[1]==0 or not gradients.is_floating_point() or not torch.isfinite(gradients).all():
        raise ValueError('Expected finite floating [tasks>=2, parameters>0] gradients.')
    original=gradients.detach().clone()
    projected=original.clone()
    rng=random.Random(seed)
    for task in range(len(original)):
        order=[j for j in range(len(original)) if j!=task]
        rng.shuffle(order)
        for peer in order:
            norm=original[peer].square().sum()
            conflict=torch.dot(projected[task],original[peer])
            if norm>0 and conflict<0:
                projected[task]=projected[task]-conflict/norm*original[peer]
    return projected

About this algorithm

How Project conflicting task gradients without mutating their owners works

The idea

When one network is trained on several tasks, each task has its own gradient, and two of them can point in opposing directions. Adding them up lets one task cancel another's progress. PCGrad, short for projecting conflicting gradients, edits each task's gradient before they are combined.

Two gradients conflict when their dot product is negative. In that case project_conflicts subtracts from the first the part that points against the second. What is left stands at a right angle to the second gradient, so it no longer undoes that task's progress. Gradients that already agree are left alone. Each task is compared with the other tasks' original gradients, in an order shuffled by a local seed, and the function returns one projected row per task for the caller to combine.

How it works

  1. Require a finite floating matrix with at least two task rows and at least one parameter column.
  2. Detach and clone it into original, clone that into projected, and create a private random.Random(seed).
  3. For each task, list the other tasks and shuffle that list with the private generator.
  4. For each peer, compute conflict, the dot product of the task's current projected row with the peer's original row.
  5. If conflict < 0 and the peer's squared norm is positive, subtract conflict / norm * original[peer] from the task's row.
  6. Return projected, leaving the input tensor and the global random state untouched.

What it costs

Time
O(T² · P)
Memory
O(T · P)
Scales with
tasks T, parameters P

Every task is compared with every other task, and each comparison is a dot product over all P parameters; producing the T gradients takes T backward passes before this function runs.

Where it is used

  • Yu and co-authors introduced PCGrad in the 2020 paper Gradient Surgery for Multi-Task Learning, for supervised and reinforcement learning.
  • The Meta-World MT10 and MT50 robot manipulation suites were among the multi-task problems PCGrad was evaluated on.
  • The LibMTL library for multi-task learning in PyTorch includes PCGrad among its gradient weighting strategies.

Watch out for

  • Projecting onto a peer's already projected row: PCGrad uses each peer's original gradient, so keep original separate from projected.
  • Projecting when the dot product is positive too, which strips out the part two tasks agree on and shrinks useful gradients.
  • Shuffling with the global random module or editing the input tensor in place. The Lab checks for both.