code: def test_cmnrl_same_grad(
      train_samples_mnrl: List[InputExample],
      train_samples_cmnrl: List[InputExample],
      same_grad: bool,
      scaler: float,
      precision: float,
  ):
      # Given:
      sbert = SentenceTransformer("distilbert-base-uncased")
      sbert.to("cpu")
      optimizer = Adam(sbert.parameters())
      # train_samples_mnrl
      # train_samples_cmnrl
      # same_grad
      # scaler  # This simulates AMP scenarios
      # precision
  
      # When:
      # First run with MNRL
      set_seed(42)
      optimizer.zero_grad()
      loss_mnrl = losses.MultipleNegativesRankingLoss(sbert)
      loss_mnrl_value: torch.Tensor = (
          loss_mnrl.forward(
              *sbert.smart_batching_collate(train_samples_mnrl)
          )
          * scaler
      )
      loss_mnrl_value.backward()
      grad_expected = {
          name: p.grad.clone()
          for name, p in loss_mnrl.named_parameters()
          if p.grad is not None
      }
  
      # Then run with this cached version:
      set_seed(42)
      optimizer.zero_grad()
      loss_cmnrl = losses.CachedMultipleNegativesRankingLoss(
          sbert, mini_batch_size=2
      )
      loss_cmnrl_value = (
          loss_cmnrl.forward(
              *sbert.smart_batching_collate(train_samples_cmnrl)
          )
          * scaler
      )
      loss_cmnrl_value.backward()
      grad = {
          name: p.grad.clone()
          for name, p in loss_cmnrl.named_parameters()
          if p.grad is not None
      }
  
      # Then:
      if same_grad:
          assert (
              pytest.approx(loss_mnrl_value.item())
              == loss_cmnrl_value.item()
          )
      else:
          assert (
              pytest.approx(loss_mnrl_value.item())
              != loss_cmnrl_value.item()
          )
  
      nclose = 0
      for name in tqdm.tqdm(grad_expected):
          nclose += torch.allclose(
              grad[name], grad_expected[name], precision, precision
          )
  
      if same_grad:
          assert nclose == len(grad_expected)
      else:
          assert nclose != len(grad_expected)
  
file_path: sentence-transformers/tests/test_cmnrl.py
imports: from contextlib import nullcontext
  from typing import List
  import pytest
  from sentence_transformers import SentenceTransformer, InputExample, losses
  import tqdm
  from transformers import set_seed
  import torch
  from torch.optim import Adam
label_desc: Use image node_id 1 for calling a global function with example usage: test_cmnrl_same_grad(train_samples_mnrl, train_samples_cmnrl, same_grad, scaler, precision) without return types