Python torchvision.__version__() Examples

The following are 5 code examples of torchvision.__version__(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module torchvision , or try the search function .
Example #1
Source File: __init__.py    From mlflow with Apache License 2.0 6 votes vote down vote up
def get_default_conda_env():
    """
    :return: The default Conda environment for MLflow Models produced by calls to
             :func:`save_model()` and :func:`log_model()`.
    """
    import torch
    import torchvision

    return _mlflow_conda_env(
        additional_conda_deps=[
            "pytorch={}".format(torch.__version__),
            "torchvision={}".format(torchvision.__version__),
        ],
        additional_pip_deps=[
            # We include CloudPickle in the default environment because
            # it's required by the default pickle module used by `save_model()`
            # and `log_model()`: `mlflow.pytorch.pickle_module`.
            "cloudpickle=={}".format(cloudpickle.__version__)
        ],
        additional_conda_channels=[
            "pytorch",
        ]) 
Example #2
Source File: collect_env.py    From mmdetection with Apache License 2.0 4 votes vote down vote up
def collect_env():
    """Collect the information of the running environments."""
    env_info = {}
    env_info['sys.platform'] = sys.platform
    env_info['Python'] = sys.version.replace('\n', '')

    cuda_available = torch.cuda.is_available()
    env_info['CUDA available'] = cuda_available

    if cuda_available:
        from torch.utils.cpp_extension import CUDA_HOME
        env_info['CUDA_HOME'] = CUDA_HOME

        if CUDA_HOME is not None and osp.isdir(CUDA_HOME):
            try:
                nvcc = osp.join(CUDA_HOME, 'bin/nvcc')
                nvcc = subprocess.check_output(
                    f'"{nvcc}" -V | tail -n1', shell=True)
                nvcc = nvcc.decode('utf-8').strip()
            except subprocess.SubprocessError:
                nvcc = 'Not Available'
            env_info['NVCC'] = nvcc

        devices = defaultdict(list)
        for k in range(torch.cuda.device_count()):
            devices[torch.cuda.get_device_name(k)].append(str(k))
        for name, devids in devices.items():
            env_info['GPU ' + ','.join(devids)] = name

    gcc = subprocess.check_output('gcc --version | head -n1', shell=True)
    gcc = gcc.decode('utf-8').strip()
    env_info['GCC'] = gcc

    env_info['PyTorch'] = torch.__version__
    env_info['PyTorch compiling details'] = torch.__config__.show()

    env_info['TorchVision'] = torchvision.__version__

    env_info['OpenCV'] = cv2.__version__

    env_info['MMCV'] = mmcv.__version__
    env_info['MMDetection'] = mmdet.__version__
    from mmdet.ops import get_compiler_version, get_compiling_cuda_version
    env_info['MMDetection Compiler'] = get_compiler_version()
    env_info['MMDetection CUDA Compiler'] = get_compiling_cuda_version()
    return env_info 
Example #3
Source File: prepare.py    From AutoDL-Projects with MIT License 4 votes vote down vote up
def main():
  save_path = Path(args.save)
  save_dir  = save_path.parent
  name      = args.name
  save_dir.mkdir(parents=True, exist_ok=True)
  assert not save_path.exists(), '{:} already exists'.format(save_path)
  print ('torchvision version : {:}'.format(torchvision.__version__))

  if name == 'cifar10':
    dataset = dset.CIFAR10 (args.root, train=True)
  elif name == 'cifar100':
    dataset = dset.CIFAR100(args.root, train=True)
  elif name == 'imagenet-1k':
    dataset = dset.ImageFolder(osp.join(args.root, 'train'))
  else: raise TypeError("Unknow dataset : {:}".format(name))

  if hasattr(dataset, 'targets'):
    targets = dataset.targets
  elif hasattr(dataset, 'train_labels'):
    targets = dataset.train_labels
  elif hasattr(dataset, 'imgs'):
    targets = [x[1] for x in dataset.imgs]
  else:
    raise ValueError('invalid pattern')
  print ('There are {:} samples in this dataset.'.format( len(targets) ))

  class2index = defaultdict(list)
  train, valid = [], []
  random.seed(111)
  for index, cls in enumerate(targets):
    class2index[cls].append( index )
  classes = sorted( list(class2index.keys()) )
  for cls in classes:
    xlist = class2index[cls]
    xtrain = random.sample(xlist, int(len(xlist)*args.ratio))
    xvalid = list(set(xlist) - set(xtrain))
    train += xtrain
    valid += xvalid
  train.sort()
  valid.sort()
  ## for statistics
  class2numT, class2numV = defaultdict(int), defaultdict(int)
  for index in train:
    class2numT[ targets[index] ] += 1
  for index in valid:
    class2numV[ targets[index] ] += 1
  class2numT, class2numV = dict(class2numT), dict(class2numV)
  torch.save({'train': train,
              'valid': valid,
              'class2numTrain': class2numT,
              'class2numValid': class2numV}, save_path)
  print ('-'*80) 
Example #4
Source File: collect_env.py    From detectron2 with Apache License 2.0 4 votes vote down vote up
def collect_env_info():
    data = []
    data.append(("sys.platform", sys.platform))
    data.append(("Python", sys.version.replace("\n", "")))
    data.append(("Numpy", np.__version__))
    try:
        from detectron2 import _C
    except ImportError:
        data.append(("detectron2._C", "failed to import"))
    else:
        data.append(("Detectron2 Compiler", _C.get_compiler_version()))
        data.append(("Detectron2 CUDA Compiler", _C.get_cuda_version()))

    data.append(get_env_module())
    data.append(("PyTorch", torch.__version__))
    data.append(("PyTorch Debug Build", torch.version.debug))
    try:
        data.append(("torchvision", torchvision.__version__))
    except AttributeError:
        data.append(("torchvision", "unknown"))

    has_cuda = torch.cuda.is_available()
    data.append(("CUDA available", has_cuda))
    if has_cuda:
        devices = defaultdict(list)
        for k in range(torch.cuda.device_count()):
            devices[torch.cuda.get_device_name(k)].append(str(k))
        for name, devids in devices.items():
            data.append(("GPU " + ",".join(devids), name))

        from torch.utils.cpp_extension import CUDA_HOME

        data.append(("CUDA_HOME", str(CUDA_HOME)))

        if CUDA_HOME is not None and os.path.isdir(CUDA_HOME):
            try:
                nvcc = os.path.join(CUDA_HOME, "bin", "nvcc")
                nvcc = subprocess.check_output("'{}' -V | tail -n1".format(nvcc), shell=True)
                nvcc = nvcc.decode("utf-8").strip()
            except subprocess.SubprocessError:
                nvcc = "Not Available"
            data.append(("NVCC", nvcc))

        cuda_arch_list = os.environ.get("TORCH_CUDA_ARCH_LIST", None)
        if cuda_arch_list:
            data.append(("TORCH_CUDA_ARCH_LIST", cuda_arch_list))
    data.append(("Pillow", PIL.__version__))

    try:
        import cv2

        data.append(("cv2", cv2.__version__))
    except ImportError:
        pass
    env_str = tabulate(data) + "\n"
    env_str += collect_torch_env()
    return env_str 
Example #5
Source File: __init__.py    From mlflow with Apache License 2.0 4 votes vote down vote up
def load_model(model_uri, **kwargs):
    """
    Load a PyTorch model from a local file or a run.

    :param model_uri: The location, in URI format, of the MLflow model, for example:

                      - ``/Users/me/path/to/local/model``
                      - ``relative/path/to/local/model``
                      - ``s3://my_bucket/path/to/model``
                      - ``runs:/<mlflow_run_id>/run-relative/path/to/model``
                      - ``models:/<model_name>/<model_version>``
                      - ``models:/<model_name>/<stage>``

                      For more information about supported URI schemes, see
                      `Referencing Artifacts <https://www.mlflow.org/docs/latest/concepts.html#
                      artifact-locations>`_.

    :param kwargs: kwargs to pass to ``torch.load`` method.
    :return: A PyTorch model.

    .. code-block:: python
        :caption: Example

        import torch
        import mlflow
        import mlflow.pytorch
        # Set values
        model_path_dir = ...
        run_id = "96771d893a5e46159d9f3b49bf9013e2"
        pytorch_model = mlflow.pytorch.load_model("runs:/" + run_id + "/" + model_path_dir)
        y_pred = pytorch_model(x_new_data)
    """
    import torch

    local_model_path = _download_artifact_from_uri(artifact_uri=model_uri)
    try:
        pyfunc_conf = _get_flavor_configuration(
            model_path=local_model_path, flavor_name=pyfunc.FLAVOR_NAME)
    except MlflowException:
        pyfunc_conf = {}
    code_subpath = pyfunc_conf.get(pyfunc.CODE)
    if code_subpath is not None:
        pyfunc_utils._add_code_to_system_path(
            code_path=os.path.join(local_model_path, code_subpath))

    pytorch_conf = _get_flavor_configuration(model_path=local_model_path, flavor_name=FLAVOR_NAME)
    if torch.__version__ != pytorch_conf["pytorch_version"]:
        _logger.warning(
            "Stored model version '%s' does not match installed PyTorch version '%s'",
            pytorch_conf["pytorch_version"], torch.__version__)
    torch_model_artifacts_path = os.path.join(local_model_path, pytorch_conf['model_data'])
    return _load_model(path=torch_model_artifacts_path, **kwargs)