code: def recursive_sum(
      obj, weight: torch.Tensor, distributed: bool = False
  ):
      assert weight.dim() == 1, weight.size()
      if isinstance(obj, (tuple, list)):
          return type(obj)(
              recursive_sum(v, weight, distributed) for v in obj
          )
      elif isinstance(obj, dict):
          return {
              k: recursive_sum(v, weight, distributed)
              for k, v in obj.items()
          }
      elif isinstance(obj, torch.Tensor):
          assert obj.size() == weight.size(), (
              obj.size(),
              weight.size(),
          )
          obj = (obj * weight.type(obj.dtype)).sum()
          if distributed:
              lst = [
                  torch.empty_like(obj)
                  for _ in range(torch.distributed.get_world_size())
              ]
              torch.distributed.all_gather(lst, obj)
              if all([torch.isnan(o) for o in lst]):
                  obj = torch.sum(torch.stack(lst))
              else:
                  # NOTE(wangyou): not using torch.nansum here to compensate for the
                  # reduced samples.
                  # This is important so that the condition-specific loss values reported
                  # in Reporter will be consistent with the general loss value.
                  obj = torch.nanmean(torch.stack(lst)) * len(lst)
          return obj
      elif obj is None:
          return None
      else:
          raise ValueError(type(obj))
  
label_desc: Use image node_id 1 for calling a global function with example usage: recursive_sum(obj, weight, distributed) and returns: type, unknown, obj, None