code: def _paddle2torch(
      paddle_tensor: "paddle.Tensor",
      device: Optional[Union[str, int]] = None,
      no_gradient: bool = None,
  ) -> "torch.Tensor":
      """
      将 :class:`paddle.Tensor` 转换为 :class:`torch.Tensor` ，并且能够保留梯度进行反向传播
  
      :param paddle_tensor: 要转换的 **paddle** 张量；
      :param device: 是否将转换后的张量迁移到特定设备上，为 ``None``时，和输入的张量相同；
      :param no_gradient: 是否保留原张量的梯度。为 ``None`` 时，新的张量与输入张量保持一致；
          为 ``True`` 时，全部不保留梯度；为 ``False`` 时，全部保留梯度；
      :return: 转换后的 **torch** 张量；
      """
      no_gradient = (
          paddle_tensor.stop_gradient
          if no_gradient is None
          else no_gradient
      )
      paddle_numpy = paddle_tensor.numpy()
      if not np.issubdtype(paddle_numpy.dtype, np.inexact):
          no_gradient = True
  
      if device is None:
          if paddle_tensor.place.is_gpu_place():
              # paddlepaddle有两种Place，对应不同的device id获取方式
              if hasattr(paddle_tensor.place, "gpu_device_id"):
                  # paddle.fluid.core_avx.Place
                  # 在gpu环境下创建张量的话，张量的place是这一类型
                  device = f"cuda:{paddle_tensor.place.gpu_device_id()}"
              else:
                  # paddle.CUDAPlace
                  device = f"cuda:{paddle_tensor.place.get_device_id()}"
          else:
              # TODO: 可能需要支持xpu等设备
              device = "cpu"
  
      if not no_gradient:
          # 保持梯度，并保持反向传播
          # torch.tensor会保留numpy数组的类型
          torch_tensor = torch.tensor(
              paddle_numpy, requires_grad=True, device=device
          )
          hook = torch_tensor.register_hook(
              lambda grad: paddle.autograd.backward(
                  paddle_tensor, paddle.to_tensor(grad.cpu().numpy())
              )
          )
      else:
          # 不保留梯度
          torch_tensor = torch.tensor(
              paddle_numpy, requires_grad=False, device=device
          )
  
      return torch_tensor
  
file_path: fastNLP/fastNLP/modules/mix_modules/utils.py
imports: from typing import Any, Optional, Union
  import numpy
  from fastNLP.core.utils import paddle_to, apply_to_collection
  from fastNLP.core.log import logger
  from fastNLP.envs.imports import _NEED_IMPORT_JITTOR, _NEED_IMPORT_TORCH, _NEED_IMPORT_PADDLE
label_desc: Use image node_id 1 for calling a global function with example usage: _paddle2torch(paddle_tensor, device, no_gradient) and returns: torch_tensor