cuda runtime error (10) : invalid device ordinal at torch/csrc/cuda/Module.cpp:88

赞赏码 & 联系方式 & 个人闲话

我在执行torch.load时遇到该报错,感到非常奇怪。因为我只有一块GPU,怎么会出现无效的设备序号呢?

查找__init__.py报错源码,发现self.idx的值确实为1,然而应该为0。仔细看load函数的注释会发现已经写明解决方法。

"""Loads an object saved with :func:`torch.save` from a file.

    torch.load uses Python's unpickling facilities but treats storages,
    which underlie tensors, specially. They are first deserialized on the
    CPU and are then moved to the device they were saved from. If this fails
    (e.g. because the run time system doesn't have certain devices), an exception
    is raised. However, storages can be dynamically remapped to an alternative
    set of devices using the map_location argument.

    If map_location is a callable, it will be called once for each serialized
    storage with two arguments: storage and location. The storage argument
    will be the initial deserialization of the storage, residing on the CPU.
    Each serialized storage has a location tag associated with it which
    identifies the device it was saved from, and this tag is the second
    argument passed to map_location. The builtin location tags are 'cpu' for
    CPU tensors and 'cuda:device_id' (e.g. 'cuda:2') for CUDA tensors.
    map_location should return either None or a storage. If map_location returns
    a storage, it will be used as the final deserialized object, already moved to
    the right device. Otherwise, torch.load will fall back to the default behavior,
    as if map_location wasn't specified.

    If map_location is a dict, it will be used to remap location tags
    appearing in the file (keys), to ones that specify where to put the
    storages (values).

    User extensions can register their own location tags and tagging and
    deserialization methods using register_package.

    Args:
        f: a file-like object (has to implement fileno that returns a file
            descriptor, and must implement seek), or a string containing a file
            name
        map_location: a function or a dict specifying how to remap storage
            locations
        pickle_module: module used for unpickling metadata and objects (has to
            match the pickle_module used to serialize file)

    Example:
        >>> torch.load('tensors.pt')
        # Load all tensors onto the CPU
        >>> torch.load('tensors.pt', map_location=lambda storage, loc: storage)
        # Load all tensors onto GPU 1
        >>> torch.load('tensors.pt', map_location=lambda storage, loc: storage.cuda(1))
        # Map tensors from GPU 1 to GPU 0
        >>> torch.load('tensors.pt', map_location={'cuda:1':'cuda:0'})

    """

最后的例子比较重要哈,如果我们想把GPU1修正到GPU0需要使用例子中的这句话(修改tensors.pt为自己的文件哈)

torch.load('tensors.pt', map_location={'cuda:1':'cuda:0'})

将GPU1映射到GPU0,问题成功解决。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章