import torch
import torch.nn as nn
from torch.func import grad_and_value, vmap # or value_and_grad
# Define a function that computes loss AND metrics we need
def compute_loss_and_grad_sq_norms(params, buffers, model_functional, data, target, param_indices_to_watch):
# Reconstruct the stateful model functionally (if needed, or use functional models directly)
# preds = model_functional(params, buffers, data) # Simplified example
# loss = criterion(preds, target)
# Simplified: Assume 'model' can take params explicitly
# This usually requires using torch.func.functional_call or a functional model definition
output = torch.func.functional_call(model, (params, buffers), (data,))
loss = criterion(output, target)
# How to get grads here to compute norms is the tricky part.
# Maybe a nested grad call or directly compute based on output gradients?
# This part needs careful thought - standard grad() gives grads wrt inputs (params).
# We need the norms *of* those gradients.
# A more feasible approach with value_and_grad:
# First, get loss and grads
grad_fn = torch.func.grad(compute_loss) # compute_loss takes params, data, target -> loss
grads = grad_fn(params, buffers, model_functional, data, target)
# Now calculate norms from the explicit grads tensor/tuple
total_sq_norm = 0.0
# This loop is still in Python, but maybe operating on grads *returned* by torch.func
# is less disruptive than accessing .grad attributes? Needs testing.
watched_grads = [grads[i] for i in param_indices_to_watch] # Assuming grads match params order
for grad_tensor in watched_grads:
if grad_tensor is not None:
total_sq_norm += torch.pow(grad_tensor, 2).sum()
return loss, total_sq_norm # Return loss and the metric
# --- In the training loop ---
# params, buffers = dict(model.named_parameters()), dict(model.named_buffers())
# (loss, grad_sq_norm_sum), grads = torch.func.value_and_grad(
# compute_loss_and_grad_sq_norms, has_aux=True
# )(params, buffers, ...)
# accumulator.add_(grad_sq_norm_sum)
# optimizer.step(grads) # Need an optimizer compatible with functional grads
# xm.mark_step()