@@ -215,58 +215,7 @@ losses with Jacobian descent using [UPGrad](https://torchjd.org/stable/docs/aggr
215215```
216216
217217You can even go one step further by considering the multiple tasks and each element of the batch
218- independently. We call that Instance-Wise Multitask Learning (IWMTL).
219-
220- ``` python
221- import torch
222- from torch.nn import Linear, MSELoss, ReLU, Sequential
223- from torch.optim import SGD
224-
225- from torchjd.aggregation import Flattening, UPGradWeighting
226- from torchjd.autogram import Engine
227-
228- shared_module = Sequential(Linear(10 , 5 ), ReLU(), Linear(5 , 3 ), ReLU())
229- task1_module = Linear(3 , 1 )
230- task2_module = Linear(3 , 1 )
231- params = [
232- * shared_module.parameters(),
233- * task1_module.parameters(),
234- * task2_module.parameters(),
235- ]
236-
237- optimizer = SGD(params, lr = 0.1 )
238- mse = MSELoss(reduction = " none" )
239- weighting = Flattening(UPGradWeighting())
240- engine = Engine(shared_module, batch_dim = 0 )
241-
242- inputs = torch.randn(8 , 16 , 10 ) # 8 batches of 16 random input vectors of length 10
243- task1_targets = torch.randn(8 , 16 ) # 8 batches of 16 targets for the first task
244- task2_targets = torch.randn(8 , 16 ) # 8 batches of 16 targets for the second task
245-
246- for input , target1, target2 in zip (inputs, task1_targets, task2_targets):
247- features = shared_module(input ) # shape: [16, 3]
248- out1 = task1_module(features).squeeze(1 ) # shape: [16]
249- out2 = task2_module(features).squeeze(1 ) # shape: [16]
250-
251- # Compute the matrix of losses: one loss per element of the batch and per task
252- losses = torch.stack([mse(out1, target1), mse(out2, target2)], dim = 1 ) # shape: [16, 2]
253-
254- # Compute the gramian (inner products between pairs of gradients of the losses)
255- gramian = engine.compute_gramian(losses) # shape: [16, 2, 2, 16]
256-
257- # Obtain the weights that lead to no conflict between reweighted gradients
258- weights = weighting(gramian) # shape: [16, 2]
259-
260- # Do the standard backward pass, but weighted using the obtained weights
261- losses.backward(weights)
262- optimizer.step()
263- optimizer.zero_grad()
264- ```
265-
266- > [ !NOTE]
267- > Here, because the losses are a matrix instead of a simple vector, we compute a * generalized
268- > Gramian* and we extract weights from it using a
269- > [ GeneralizedWeighting] ( https://torchjd.org/stable/docs/aggregation/#torchjd.aggregation.GeneralizedWeighting ) .
218+ independently (Instance-Wise Multitask Learning). See [ this example] ( https://torchjd.org/stable/examples/iwmtl/ ) for more details.
270219
271220More usage examples can be found [ here] ( https://torchjd.org/stable/examples/ ) .
272221
0 commit comments