class_docstr: A subclass of :class:`~allennlp.common.testing.test_case.AllenNlpTestCase`
  with added methods for testing :class:`~allennlp.models.model.Model` subclasses.
class_docstr_tok: ["A","subclass","of",":","class",":","`","~allennlp.common.testing.test_case.AllenNlpTestCase","`","with","added","methods","for","testing",":","class",":","`","~allennlp.models.model.Model","`","subclasses","."]
code: def check_model_computes_gradients_correctly(model, model_batch):
      model.zero_grad()
      result = model(**model_batch)
      result["loss"].backward()
      has_zero_or_none_grads = {}
      for name, parameter in model.named_parameters():
          zeros = torch.zeros(parameter.size())
          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
                  ] = "zeros with shape ({tuple(parameter.grad.size())})"
          else:
              assert parameter.grad is None
  
      if has_zero_or_none_grads:
          for name, grad in list(has_zero_or_none_grads.items()):
              print("Parameter: {name} had incorrect gradient: {grad}")
          raise Exception(
              "Incorrect gradients found. See stdout for more info."
          )
  
file_path: magnitude/pymagnitude/third_party/allennlp/common/testing/model_test_case.py
imports: from __future__ import division
  from __future__ import absolute_import
  from __future__ import print_function
  import copy
  from numpy.testing import assert_allclose
  import torch
  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 DataIterator, DatasetReader, Vocabulary
  from allennlp.data.dataset import Batch
  from allennlp.models import Model, load_archive
label_desc: Use image node_id 4 for calling the ModelTestCase obj's underlying member method code with example usage: obj.check_model_computes_gradients_correctly(model, model_batch) without return types