class_docstr: A subclass of [`AllenNlpTestCase`](./test_case.md)
  with added methods for testing [`Model`](../../models/model.md) subclasses.
class_docstr_tok: ["A","subclass","of","[","`","AllenNlpTestCase","`","]","(",".\/test_case.md",")","with","added","methods","for","testing","[","`","Model","`","]","(","..","\/","..","\/models\/model.md",")","subclasses","."]
code: def check_model_computes_gradients_correctly(
      model: Model,
      model_batch: Dict[str, Union[Any, Dict[str, Any]]],
      params_to_ignore: Set[str] = None,
      disable_dropout: bool = True,
      which_loss: str = "loss",
  ):
      print("Checking gradients")
      for p in model.parameters():
          p.grad = None
      model.train()
  
      original_dropouts: Dict[str, float] = {}
  
      if disable_dropout:
          # Remember original dropouts so we can restore them.
          for name, module in model.named_modules():
              if isinstance(module, torch.nn.Dropout):
                  original_dropouts[name] = getattr(module, "p")
                  setattr(module, "p", 0)
  
      result = model(**model_batch)
      result[which_loss].backward()
      has_zero_or_none_grads = {}
      for name, parameter in model.named_parameters():
          zeros = torch.zeros(parameter.size())
          if params_to_ignore and name in params_to_ignore:
              continue
          if parameter.requires_grad:
              if parameter.grad is None:
                  has_zero_or_none_grads[
                      name
                  ] = "No gradient computed (i.e parameter.grad is None)"
  
              elif (
                  parameter.grad.is_sparse
                  or parameter.grad.data.is_sparse
              ):
                  pass
  
              # Some parameters will only be partially updated,
              # like embeddings, so we just check that any gradient is non-zero.
              elif (parameter.grad.cpu() == zeros).all():
                  has_zero_or_none_grads[
                      name
                  ] = f"zeros with shape ({tuple(parameter.grad.size())})"
          else:
              assert parameter.grad is None
  
      if has_zero_or_none_grads:
          for name, grad in has_zero_or_none_grads.items():
              print(f"Parameter: {name} had incorrect gradient: {grad}")
          raise Exception(
              "Incorrect gradients found. See stdout for more info."
          )
  
      # Now restore dropouts if we disabled them.
      if disable_dropout:
          for name, module in model.named_modules():
              if name in original_dropouts:
                  setattr(module, "p", original_dropouts[name])
  
imports: import copy
  import json
  from os import PathLike
  import random
  from typing import Any, Dict, Iterable, Set, Union
  import torch
  import numpy
  from numpy.testing import assert_allclose
  from allennlp.commands.train import train_model_from_file
  from allennlp.common import Params
  from allennlp.common.testing.test_case import AllenNlpTestCase
  from allennlp.data import DatasetReader, Vocabulary
  from allennlp.data import DataLoader
  from allennlp.data.batch import Batch
  from allennlp.models import load_archive, Model
  from allennlp.training import GradientDescentTrainer
  from allennlp.confidence_checks.normalization_bias_verification import NormalizationBiasVerification
label_desc: Use image node_id 6 for calling the ModelTestCase obj's underlying member method code with example usage: obj.check_model_computes_gradients_correctly(model, model_batch, params_to_ignore, disable_dropout, which_loss) without return types