code: def _torch2paddle(
      torch_tensor: "torch.Tensor",
      device: str = None,
      no_gradient: bool = None,
  ) -> "paddle.Tensor":
      """
      将 :class:`torch.Tensor` 转换为 :class:`paddle.Tensor`，并且能够保留梯度进行反向传播。
  
      :param torch_tensor: 要转换的 **torch** 张量；
      :param device: 是否将转换后的张量迁移到特定设备上，输入为 ``None`` 时，和输入的张量相同；
      :param no_gradient: 是否保留原张量的梯度。为 ``None`` 时，新的张量与输入张量保持一致；
          为 ``True`` 时，全部不保留梯度；为 ``False`` 时，全部保留梯度；
      :return: 转换后的 **paddle** 张量；
      """
      no_gradient = (
          not torch_tensor.requires_grad
          if no_gradient is None
          else no_gradient
      )
      if device is None:
          if torch_tensor.is_cuda:
              device = f"gpu:{torch_tensor.device.index}"
          else:
              device = "cpu"
  
      if not no_gradient:
          # 保持梯度并保持反向传播
          # paddle的stop_gradient和torch的requires_grad表现是相反的
          paddle_tensor = paddle.to_tensor(
              torch_tensor.detach().cpu().numpy(), stop_gradient=False
          )
          hook = paddle_tensor.register_hook(
              lambda grad: torch.autograd.backward(
                  torch_tensor, torch.tensor(grad.numpy())
              )
          )
      else:
          paddle_tensor = paddle.to_tensor(
              torch_tensor.detach().cpu().numpy(), stop_gradient=True
          )
  
      paddle_tensor = paddle_to(paddle_tensor, device)
  
      return paddle_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 2 for calling a global function with example usage: _torch2paddle(torch_tensor, device, no_gradient) and returns: paddle_tensor