code: def test_retain_grad_hidden_states_attentions(self):
      (
          config,
          input_dict,
      ) = self.model_tester.prepare_config_and_inputs_for_common()
      config.output_hidden_states = True
      config.output_attentions = self.has_attentions
  
      model = TrajectoryTransformerModel(config)
      model.to(torch_device)
  
      outputs = model(
          trajectories=input_dict["trajectories"],
          attention_mask=input_dict["attention_mask"],
          targets=input_dict["targets"],
          output_hidden_states=True,
          output_attentions=True,
          use_cache=True,
          return_dict=True,
      )
  
      output = outputs[0]
      hidden_states = outputs.hidden_states[0]
      hidden_states.retain_grad()
  
      if self.has_attentions:
          attentions = outputs.attentions[0]
          attentions.retain_grad()
  
      output.flatten()[0].backward(retain_graph=True)
  
      self.assertIsNotNone(hidden_states.grad)
  
      if self.has_attentions:
          self.assertIsNotNone(attentions.grad)
  
imports: import inspect
  import unittest
  import numpy
  from transformers import TrajectoryTransformerConfig, is_torch_available
  from transformers.testing_utils import require_torch, slow, torch_device
  from ...generation.test_generation_utils import GenerationTesterMixin
  from ...test_configuration_common import ConfigTester
  from ...test_modeling_common import ModelTesterMixin, _config_zero_init, random_attention_mask
label_desc: Use image node_id 7 for calling the TrajectoryTransformerModelTest obj's underlying member method code with example usage: obj.test_retain_grad_hidden_states_attentions() without return types