torch多GPU并行计算data_paraller踩坑

更新时间:2023-07-08 01:37:05 阅读: 评论:0

torch多GPU并⾏计算data_paraller踩坑
```python
import operator
import torch
import warnings
from itertools import chain
from ..modules import Module
from .scatter_gather import scatter_kwargs, gather
from .replicate import replicate
from .parallel_apply import parallel_apply
from torch.cuda._utils import _get_device_index
def _check_balance(device_ids):
imbalance_warn = """
There is an imbalance between your GPUs. You may want to exclude GPU {} which
has less than 75% of the memory or cores of GPU {}. You can do so by tting
the device_ids argument to DataParallel, or by tting the CUDA_VISIBLE_DEVICES
environment variable."""
device_ids = list(map(lambda x: _get_device_index(x, True), device_ids))
dev_props = [_device_properties(i) for i in device_ids]小金杯
def warn_imbalance(get_prop):
values = [get_prop(props) for props in dev_props]
min_pos, min_val = min(enumerate(values), key=operator.itemgetter(1))
max_pos, max_val = max(enumerate(values), key=operator.itemgetter(1))
if min_val / max_val < 0.75:
warnings.warn(imbalance_warn.format(device_ids[min_pos], device_ids[max_pos]))
return True
return Fal
if warn_imbalance(lambda props: al_memory):
return
if warn_imbalance(lambda props: props.multi_processor_count):
return
class DataParallel(Module):
r"""Implements data parallelism at the module level.
This container parallelizes the application of the given :attr:`module` by
splitting the input across the specified devices by chunking in the batch
dimension (other objects will be copied once per device). In the forward
pass, the module is replicated on each device, and each replica handles a
portion of the input. During the backwards pass, gradients from each replica
are summed into the original module.
The batch size should be larger than the number of GPUs ud.
See also: :ref:`cuda-nn-dataparallel-instead`
Arbitrary positional and keyword inputs are allowed to be pasd into
DataParallel but some types are specially handled. tensors will be
**scattered** on dim specified (default 0). tuple, list and dict types will巧克力好处
be shallow copied. The other types will be shared among different threads
and can be corrupted if written to in the model's forward pass.
The parallelized :attr:`module` must have its parameters and buffers on
``device_ids[0]`` before running this :class:`~DataParallel`
module.
.. warning::
In each forward, :attr:`module` is **replicated** on each device, so any
updates to the running module in ``forward`` will be lost. For example,
if :attr:`module` has a counter attribute that is incremented in each
``forward``, it will always stay at the initial value becau the update
is done on the replicas which are destroyed after ``forward``. However,
:class:`~DataParallel` guarantees that the replica on
``device[0]`` will have its parameters and buffers sharing storage with
the ba parallelized :attr:`module`. So **in-place** updates to the
parameters or buffers on ``device[0]`` will be recorded. E.g.,
:class:`~BatchNorm2d` and :func:`~utils.spectral_norm`
rely on this behavior to update the buffers.
.. warning::
Forward and backward hooks defined on :attr:`module` and its submodules
will be invoked ``len(device_ids)`` times, each with inputs located on
a particular device. Particularly, the hooks are only guaranteed to be
executed in correct order with respect to operations on corresponding
devices. For example, it is not guaranteed that hooks t via
:meth:`~ister_forward_pre_hook` be executed before
`all` ``len(device_ids)`` :meth:`~Module.forward` calls, but
that each such hook be executed before the corresponding
:meth:`~Module.forward` call of that device.
.. warning::
When :attr:`module` returns a scalar (i.e., 0-dimensional tensor) in
:func:`forward`, this wrapper will return a vector of length equal to
春节素材number of devices ud in data parallelism, containing the result from
each device.
.
. note::
There is a subtlety in using the
``pack quence -> recurrent network -> unpack quence`` pattern in a三宁化工
:class:`~Module` wrapped in :class:`~DataParallel`.
See :ref:`pack-rnn-unpack-with-data-parallelism` ction in FAQ for
details.
Args:
module (Module): module to be parallelized
device_ids (list of int or torch.device): CUDA devices (default: all devices)
output_device (int or torch.device): device location of output (default: device_ids[0])    Attributes:
module (Module): the module to be parallelized
Example::
>>> net = DataParallel(model, device_ids=[0, 1, 2])
>>> output = net(input_var)  # input_var can be on any device, including CPU
"""
# TODO: update notes/cuda.rst when this class handles 8+ GPUs well
def __init__(lf, module, device_ids=None, output_device=None, dim=0):
韭菜肉馅
super(DataParallel, lf).__init__()
if not torch.cuda.is_available():
lf.device_ids = []
return
if device_ids is None:
device_ids = list(range(torch.cuda.device_count()))
if output_device is None:
output_device = device_ids[0]
lf.dim = dim
中国十大冰箱品牌排行榜名单
lf.device_ids = list(map(lambda x: _get_device_index(x, True), device_ids))
lf.output_device = _get_device_index(output_device, True)
lf.src_device_obj = torch.device("cuda:{}".format(lf.device_ids[0]))
_check_balance(lf.device_ids)
if len(lf.device_ids) == 1:
教学质量def forward(lf, *inputs, **kwargs):
if not lf.device_ids:
dule(*inputs, **kwargs)
for t in dule.parameters(), lf.module.buffers()):
if t.device != lf.src_device_obj:
rai RuntimeError("module must have its parameters and buffers "
"on device {} (device_ids[0]) but found one of "
"them on device: {}".format(lf.src_device_obj, t.device))
inputs, kwargs = lf.scatter(inputs, kwargs, lf.device_ids)
if len(lf.device_ids) == 1:
dule(*inputs[0], **kwargs[0])
replicas = lf.dule, lf.device_ids[:len(inputs)])
outputs = lf.parallel_apply(replicas, inputs, kwargs)
return lf.gather(outputs, lf.output_device)
def replicate(lf, module, device_ids):
return replicate(module, device_ids, not torch.is_grad_enabled())
def scatter(lf, inputs, kwargs, device_ids):
return scatter_kwargs(inputs, kwargs, device_ids, dim=lf.dim)
def parallel_apply(lf, replicas, inputs, kwargs):
return parallel_apply(replicas, inputs, kwargs, lf.device_ids[:len(replicas)])
def gather(lf, outputs, output_device):
return gather(outputs, output_device, dim=lf.dim)
def data_parallel(module, inputs, device_ids=None, output_device=None, dim=0, module_kwargs=None):    """Evaluates module(input) in parallel across the GPUs given in device_ids.
This is the functional version of the DataParallel module.
Args:
module (Module): the module to evaluate in parallel
inputs (Tensor): inputs to the module
device_ids (list of int or torch.device): GPU ids on which to replicate module
output_device (list of int or torch.device): GPU location of the output  U -1 to indicate the CPU.
(default: device_ids[0])
Returns:
a Tensor containing the result of module(input) located on
output_device
朴蔡琳"""
if not isinstance(inputs, tuple):
inputs = (inputs,)
if device_ids is None:
device_ids = list(range(torch.cuda.device_count()))
if output_device is None:
output_device = device_ids[0]
device_ids = list(map(lambda x: _get_device_index(x, True), device_ids))
output_device = _get_device_index(output_device, True)
src_device_obj = torch.device("cuda:{}".format(device_ids[0]))
for t in chain(module.parameters(), module.buffers()):
if t.device != src_device_obj:
rai RuntimeError("module must have its parameters and buffers "
"on device {} (device_ids[0]) but found one of "
"them on device: {}".format(src_device_obj, t.device))
inputs, module_kwargs = scatter_kwargs(inputs, module_kwargs, device_ids, dim)
if len(device_ids) == 1:
return module(*inputs[0], **module_kwargs[0])
return module(*inputs[0], **module_kwargs[0])
ud_device_ids = device_ids[:len(inputs)]
replicas = replicate(module, ud_device_ids)
outputs = parallel_apply(replicas, inputs, module_kwargs, ud_device_ids)    return gather(outputs, output_device, dim)

本文发布于:2023-07-08 01:37:05,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/1084642.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:出现   排行榜   品牌   冰箱   化工   韭菜
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图