code: def _run_test_clip_gradients(fabric, clip_type):
      in_features, out_features = 32, 2
      model = torch.nn.Linear(in_features, out_features, bias=False)
      model.weight.data.fill_(0.01)
  
      optimizer = torch.optim.Adam(model.parameters(), lr=0.1)
      model, optimizer = fabric.setup(model, optimizer)
  
      batch = torch.full((1, in_features), 0.1, device=fabric.device)
      loss = model(batch).sum()
  
      # The example is constructed such that the gradients are all the same
      fabric.backward(loss)
  
      if clip_type == "norm":
          norm = torch.linalg.vector_norm(
              model.weight.grad.detach().cpu(), 2, dtype=torch.float32
          ).item()
          new_norm = norm / 2.0
          fabric.clip_gradients(model, optimizer, max_norm=new_norm)
          assert torch.allclose(
              torch.linalg.vector_norm(
                  model.weight.grad.detach().cpu(),
                  2,
                  dtype=torch.float32,
              ),
              torch.tensor(new_norm),
          )
      elif clip_type == "val":
          val = model.weight.grad.view(-1)[0].item()
          new_val = val / 2.0
          fabric.clip_gradients(model, optimizer, clip_val=new_val)
          assert torch.allclose(
              model.weight.grad,
              torch.full_like(model.weight.grad, new_val),
          )
      else:
          raise AssertionError(f"Unknown clip type: {clip_type}")
  
      optimizer.step()
      optimizer.zero_grad()
  
file_path: pytorch-lightning/tests/tests_fabric/strategies/test_single_device.py
imports: from unittest.mock import Mock
  import pytest
  import torch
  from lightning.fabric import Fabric
  from lightning.fabric.strategies import SingleDeviceStrategy
  from tests_fabric.helpers.runif import RunIf
label_desc: Use image node_id 7 for calling a global function with example usage: _run_test_clip_gradients(fabric, clip_type) without return types