[源码解析] PyTorch 分布式(2) ----- DataParallel(上)

0x00 摘要

从本文开始,我们介绍 PyTorch 的数据并行,本文是第一篇,介绍 DataPrallel,因为字数太多(1万两千多字,因此拆分成两篇文章发布)。

本系列其他文章如下:

深度学习利器之自动微分(1)

深度学习利器之自动微分(2)

[源码解析]深度学习利器之自动微分(3) --- 示例解读

[源码解析]PyTorch如何实现前向传播(1) --- 基础类(上)

[源码解析]PyTorch如何实现前向传播(2) --- 基础类(下)

[源码解析] PyTorch如何实现前向传播(3) --- 具体实现

[源码解析] Pytorch 如何实现后向传播 (1)---- 调用引擎

[源码解析] Pytorch 如何实现后向传播 (2)---- 引擎静态结构

[源码解析] Pytorch 如何实现后向传播 (3)---- 引擎动态逻辑

[源码解析] PyTorch 如何实现后向传播 (4)---- 具体算法

[源码解析] PyTorch 分布式(1)------历史和概述

[源码解析] PyTorch 如何使用GPU

注 : 本文深度借鉴了以下两篇文章,特此深表感谢。

Distributed data parallel training using Pytorch on AWS

PyTorch 源码解读之 DP & DDP:模型并行和分布式训练解析

0x01 综述

我们首先从各个角度来看看DataParallel。

1.1 从流程上看

DataParallel 从流程上来看,是通过将整个小批次(minibatch)数据加载到主线程上,然后将子小批次(ub-minibatches)数据分散到整个GPU网络中来工作。

  1. 把 minibatch 数据从page-locked memory 传输到 GPU 0(master),Master GPU 也持有模型,其他GPU拥有模型的 stale copy。
  2. 在 GPUs 之间 scatter minibatch 数据。具体是将输入一个 minibatch 的数据均分成多份,分别送到对应的 GPU 进行计算。
  3. 在 GPUs 之间复制模型。与 Module 相关的所有数据也都会复制多份。
  4. 在每个GPU之上运行前向传播,计算输出。PyTorch 使用多线程来并行前向传播,每个 GPU 在单独的线程上将针对各自的输入数据独立并行地进行 forward 计算。
  5. 在 master GPU 之上收集(gather)输出,计算损失。即通过将网络输出与批次中每个元素的真实数据标签进行比较来计算损失函数值。
  6. 把损失在 GPUs 之间 scatter,在各个GPU之上运行后向传播,计算参数梯度。
  7. 在 GPU 0 之上归并梯度。
  8. 更新梯度参数。
    • 进行梯度下降,并更新主GPU上的模型参数。
    • 由于模型参数仅在主GPU上更新,而其他从属GPU此时并不是同步更新的,所以需要将更新后的模型参数复制到剩余的从属 GPU 中,以此来实现并行。

1.2 从模式角度看

首先我们先给出一个技术上的概括,从模式角度看:

  • DP 可以被认为是类似参数服务器的应用。
  • DDP 可以被认为是集合通讯的应用。

参数服务器大致可以分为 master 和 worker,而DP 基于单机多卡,所以对应关系如下:

  • worker :所有GPU(包括GPU 0)都是worker,都负责计算和训练网络。
  • master :GPU 0(并非 GPU 真实标号,而是输入参数 device_ids 的首位)也负责整合梯度,更新参数。

所以我们重点看看 GPU 0。

DataParallel会将网络模型默认放在GPU 0上,然后把模型从GPU 0 拷贝到其他的GPU,各个GPU开始并行训练,接着 GPU 0 作为master来进行梯度的汇总和模型的更新,最后将计算任务下发给其他GPU。这非常类似参数服务器的机制。

从官方图也可以看到同样的信息。

1.3 从操作系统角度看

从操作系统角度看,DP 和 DDP 有如下不同(我们属于提前剧透):

  • DataParallel 是单进程,多线程的并行训练方式,并且只能在单台机器上运行。
  • DistributedDataParallel 是多进程,并且适用于单机和多机训练。DistributedDataParallel 还预先复制模型,而不是在每次迭代时复制模型,并避免了全局解释器锁定。

1.4 低效率

DP 有如下缺陷:

  • 冗余数据副本

    • 数据先从主机复制到主GPU,然后将微批次( sub-minibatches)在其他GPU之间发布(scatter)。
  • 在前向传播之前需要跨GPU进行模型复制。
    • 由于模型参数是在主GPU上更新的,因此模型必须在每次正向传播开始时重新同步。
  • 每个batch都会有线程创建/销毁开销。
    • 并行前向传播是在多个线程中实现的(这可能只是PyTorch的一个issue)。
  • 有一个把梯度规约流水线化的机会但是没有利用。
    • 在Pytorch 1.0.1数据并行实现中,梯度下降发生在反向传播的末尾,这可以进行流水线化。
  • 在主GPU上不必要地收集模型输出output。
  • GPU利用率不均,负载不均衡。主GPU的内存和使用率会比其他显卡的高,因为:
    • 在主GPU上执行损失loss计算。
    • 梯度规约和更新参数均发生在主GPU之上。

0x02 综述

2.1 示例

我们使用一个例子来看看,具体逻辑是:

  • 给本程序设置可见GPU。

    • 对应代码就是使用 args.gpu_id="2,7" 和 os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id 来配置 gpu 序号,其实目的就是设置 os.environ['CUDA_VISIBLE_DEVICES'] = "2,7",这样 device_ids[0]对应的就是物理上第2号卡,device_ids[1]对应的就是物理上第7号卡。
    • 也可以在运行时临时指定,比如:CUDA_VISIBLE_DEVICES='2,7' Python train.py。
  • 把模型参数和缓冲区放在device_ids[0]上,在运行DataParallel模块前,并行化模块必须在device_ids [0]上具有其参数和缓冲区。

    • 代码就是 model=model.cuda() 。
  • 构建DP模型。DP 的好处是使用起来非常方便,只需要将原来单卡的 module 用 DP 改成多卡。

    • 代码就是 model=torch.nn.DaraParallel(model)。
    • 实际上 DP 是一个Pytorch的nn.Module,所以模型和优化器都需要使用.module来得到实际的模型和优化器。
  • 把数据载入到主GPU。

    • data,label= data.cuda(),label.cuda()
  • 进行前向传播。

    • DP 会把模型module 在每个device上复制一份。
    • DP 会把输入数据再切分为多个小块,把这些小块数据分发到不同的GPU之中进行计算,每个模型只需要处理自己分配到的数据。
  • 进行后向传播。

    • DP 会把每个GPU 计算出来的梯度累加到GPU 0之中进行汇总。

具体代码如下:

  1. args.gpu_id="2,7" ; #指定gpu id
  2. args.cuda = not args.no_cuda and torch.cuda.is_available() #是否使用cpu
  3. # 配置环境 也可以在运行时临时指定,比如:CUDA_VISIBLE_DEVICES='2,7' Python train.py
  4. os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id # 赋值必须是字符串
  5. device_ids=range(torch.cuda.device_count()) #torch.cuda.device_count()=2
  6. # device_ids=[0,1] ---- 也可以这么使用。这里的0 就是上述指定 2,是主gpu, 1就是7,模型和数据由主gpu分发
  7. if arg.cuda:
  8. model=model.cuda() #将模型复制到gpu ,默认是cuda('0'),即转到第一个GPU 2
  9. if len(device_id)>1:
  10. model=torch.nn.DataParallel(model);#构建DP,前提是model已经.cuda()了
  11. optimizer = torch.optim.SGD(model.parameters(), args.lr,
  12. momentum=args.momentum,
  13. weight_decay=args.weight_decay)
  14. #前向传播时,数据也要执行cuda(),即把数据复制到主gpu里
  15. for batch_idx, (data, label) in pbar:
  16. if args.cuda:
  17. data,label= data.cuda(),label.cuda(); # 数据放到了默认GPU
  18. data_v = Variable(data)
  19. target_var = Variable(label)
  20. prediction= model(data_v,target_var,args)
  21. #这里的prediction 预测结果是由两个gpu合并过的,并行计算只存在于前向传播里
  22. #前向传播每个gpu计算量为 batch_size/len(device_ids),等前向传播完了将结果归并到主gpu里
  23. #prediction的长度等于batch_size
  24. criterion = nn.CrossEntropyLoss()
  25. loss = criterion(prediction,target_var) # 在默认GPU之上计算loss
  26. optimizer.zero_grad()
  27. loss.backward()
  28. optimizer.step()

2.2 相关知识

DP 在每次网络传播开始前,会把master节点上的parameters和buffer广播给其他节点,以此来维持状态的统一。这部分相关知识主要是如何把模型拷贝到GPU之上以及如何调用GPU核函数,具体可以参见前文 [源码解析] PyTorch 如何使用GPU

0x03 定义

3.1 定义

我们通过 DataParallel 的初始化函数来看看 DataParallel 的结构。

__init__ 三个输入参数定义如下:

  • module : 模型,
  • device_ids :训练的device,
  • output_device :保存输出结果的device。默认是在device_ids[0],即第一块卡。

代码如下:

  1. import operator
  2. import torch
  3. import warnings
  4. from itertools import chain
  5. from ..modules import Module
  6. from .scatter_gather import scatter_kwargs, gather
  7. from .replicate import replicate
  8. from .parallel_apply import parallel_apply
  9. from torch._utils import (
  10. _get_all_device_indices,
  11. _get_available_device_type,
  12. _get_device_index,
  13. _get_devices_properties
  14. )
  15. class DataParallel(Module):
  16. # TODO: update notes/cuda.rst when this class handles 8+ GPUs well
  17. def __init__(self, module, device_ids=None, output_device=None, dim=0):
  18. super(DataParallel, self).__init__()
  19. # 得到可用的GPU
  20. device_type = _get_available_device_type()
  21. if device_type is None:
  22. self.module = module
  23. self.device_ids = []
  24. return
  25. # 没有输入的情况下,使用所有可见的GPU
  26. if device_ids is None:
  27. device_ids = _get_all_device_indices()
  28. # 把GPU列表上第一个作为输出,也会作为master
  29. if output_device is None:
  30. output_device = device_ids[0]
  31. self.dim = dim
  32. self.module = module
  33. self.device_ids = [_get_device_index(x, True) for x in device_ids]
  34. self.output_device = _get_device_index(output_device, True)
  35. self.src_device_obj = torch.device(device_type, self.device_ids[0])
  36. # 检查负载均衡
  37. _check_balance(self.device_ids)
  38. # 单卡就直接使用
  39. if len(self.device_ids) == 1:
  40. self.module.to(self.src_device_obj)

3.2 负载均衡

虽然输入数据是均等划分并且并行分配,但是output loss每次都会在第一块GPU聚合相加计算,所以第一块GPU的内存负载和使用率会大于其他显卡。

_check_balance 函数会检查负载是否平衡, 如果内存或者处理器 max/min > 0.75 会有警告。

  1. def _check_balance(device_ids):
  2. imbalance_warn = """
  3. There is an imbalance between your GPUs. You may want to exclude GPU {} which
  4. has less than 75% of the memory or cores of GPU {}. You can do so by setting
  5. the device_ids argument to DataParallel, or by setting the CUDA_VISIBLE_DEVICES
  6. environment variable."""
  7. device_ids = [_get_device_index(x, True) for x in device_ids]
  8. dev_props = _get_devices_properties(device_ids)
  9. def warn_imbalance(get_prop):
  10. values = [get_prop(props) for props in dev_props]
  11. min_pos, min_val = min(enumerate(values), key=operator.itemgetter(1))
  12. max_pos, max_val = max(enumerate(values), key=operator.itemgetter(1))
  13. if min_val / max_val < 0.75:
  14. warnings.warn(imbalance_warn.format(device_ids[min_pos], device_ids[max_pos]))
  15. return True
  16. return False
  17. if warn_imbalance(lambda props: props.total_memory):
  18. return
  19. if warn_imbalance(lambda props: props.multi_processor_count):
  20. return

0x04 前向传播

DataParallel并行计算只存在在前向传播过程之中。

4.1 总述

之前示例之中已经用 cuda() 函数来把模型放到 GPU[0] 之上,GPU[0] 这里已经有了模型的parameters 和 buffers。

  1. model=model.cuda()

所以forward函数之中,就不用作这一步,而是从分发模型和数据开始,需要注意的是:每次前向传播的时候都会分发模型。具体分为几个步骤。

  • 验证:遍历module的parameters和buffers,看看是否都在GPU[0]之上,如果不在,报错。
  • 分发((Scatter)输入数据:将输入数据根据其第一个维度(一般是 batch 大小)划分多份,传送到多个 GPU;
  • 复制(Replicate)模型:将模型分别拷贝到多个 GPU;
  • 并行应用(parallel_apply):在多个模型之上并行进行前向传播。因为 GPU device_ids[0] 和 base parallelized module 共享存储,所以在device[0] 上的 in-place 更新也会被保留下来,其他的GPU则不会。
  • 收集(Gather):收集从多个 GPU 上传送回来的数据;

具体代码如下:

  1. def forward(self, *inputs, **kwargs):
  2. with torch.autograd.profiler.record_function("DataParallel.forward"):
  3. # 如果机器上没有GPU,则直接用CPU运行
  4. if not self.device_ids:
  5. return self.module(*inputs, **kwargs)
  6. # 遍历module的parameters和buffers,看看是否都在GPU[0]之上,如果不在,报错。
  7. for t in chain(self.module.parameters(), self.module.buffers()):
  8. if t.device != self.src_device_obj:
  9. raise RuntimeError("module must have its parameters and buffers "
  10. "on device {} (device_ids[0]) but found one of "
  11. "them on device: {}".format(self.src_device_obj, t.device))
  12. # 现在GPU[0]上有了模型,开始训练
  13. # 首先分发输入
  14. inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
  15. # for forward function without any inputs, empty list and dict will be created
  16. # so the module can be executed on one device which is the first one in device_ids
  17. if not inputs and not kwargs:
  18. inputs = ((),)
  19. kwargs = ({},)
  20. # 如果只有单卡,直接使用
  21. if len(self.device_ids) == 1:
  22. return self.module(*inputs[0], **kwargs[0])
  23. # 分发模型
  24. replicas = self.replicate(self.module, self.device_ids[:len(inputs)])
  25. # 并行训练
  26. outputs = self.parallel_apply(replicas, inputs, kwargs)
  27. # 把前向传播的结果收集到master
  28. return self.gather(outputs, self.output_device)

4.2 分发(输入)

上面代码之中,如下语句完成了数据分发操作。

  1. inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)

对应我们传播图是:

所以我们先看看如何分发。

scatter 实际就是 scatter_kwargs 的封装,所以我们直接看 scatter_kwargs。

  1. def scatter(self, inputs, kwargs, device_ids):
  2. return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim)

4.2.1 scatter_kwargs

scatter_kwargs 调用了 scatter 分别对input和 kwargs 进行分发。

  1. def scatter_kwargs(inputs, kwargs, target_gpus, dim=0):
  2. r"""Scatter with support for kwargs dictionary"""
  3. # 分发input
  4. inputs = scatter(inputs, target_gpus, dim) if inputs else []
  5. # 分发kwargs
  6. kwargs = scatter(kwargs, target_gpus, dim) if kwargs else []
  7. # 用空项补齐,这样可以让 inputs 和 kwargs 长度相等
  8. if len(inputs) < len(kwargs):
  9. inputs.extend([() for _ in range(len(kwargs) - len(inputs))])
  10. elif len(kwargs) < len(inputs):
  11. kwargs.extend([{} for _ in range(len(inputs) - len(kwargs))])
  12. # 返回 tuple
  13. inputs = tuple(inputs)
  14. kwargs = tuple(kwargs)
  15. return inputs, kwargs

4.2.2 scatter

从注释中可以知道,tensor 会切分成大致相等的块,然后在给定的GPU之间分配。就是将一个 batch 数据近似等分成更小的 batch。对于其他类型的变量,会根据不同类型进行不同操作,比如调用 scatter_map 对其内部进行递归处理。

  1. def scatter(inputs, target_gpus, dim=0):
  2. r"""
  3. Slices tensors into approximately equal chunks and
  4. distributes them across given GPUs. Duplicates
  5. references to objects that are not tensors.
  6. """
  7. def scatter_map(obj):
  8. if isinstance(obj, torch.Tensor):
  9. # 针对张量会调用Scatter.apply处理
  10. return Scatter.apply(target_gpus, None, dim, obj)
  11. if is_namedtuple(obj):
  12. # 调用 scatter_map 对其子模块进行递归处理。
  13. return [type(obj)(*args) for args in zip(*map(scatter_map, obj))]
  14. if isinstance(obj, tuple) and len(obj) > 0:
  15. # 调用 scatter_map 对其子模块进行递归处理。
  16. return list(zip(*map(scatter_map, obj)))
  17. if isinstance(obj, list) and len(obj) > 0:
  18. # 调用 scatter_map 对其子模块进行递归处理。
  19. return [list(i) for i in zip(*map(scatter_map, obj))]
  20. if isinstance(obj, dict) and len(obj) > 0:
  21. # 调用 scatter_map 对其子模块进行递归处理。
  22. return [type(obj)(i) for i in zip(*map(scatter_map, obj.items()))]
  23. return [obj for targets in target_gpus]
  24. # After scatter_map is called, a scatter_map cell will exist. This cell
  25. # has a reference to the actual function scatter_map, which has references
  26. # to a closure that has a reference to the scatter_map cell (because the
  27. # fn is recursive). To avoid this reference cycle, we set the function to
  28. # None, clearing the cell
  29. try:
  30. res = scatter_map(inputs)
  31. finally:
  32. scatter_map = None
  33. return res

4.2.3 Scatter

前面提到了 Scatter.apply 处理张量,我们就接着看看。Scatter 拓展了 Function,逻辑如下:

  • 如果 cuda 可用,则得到 streams 列表,这样可以在后台流进行 CPU 到 GPU 的拷贝。
  • 调用 comm.scatter 进行分发。
  • 调用 wait_stream 和 record_stream 对拷贝流进行同步。
  1. class Scatter(Function):
  2. @staticmethod
  3. def forward(ctx, target_gpus, chunk_sizes, dim, input):
  4. target_gpus = [_get_device_index(x, True) for x in target_gpus]
  5. ctx.dim = dim
  6. ctx.input_device = input.get_device() if input.device.type != "cpu" else -1
  7. streams = None
  8. # 对于cuda,进行处理
  9. if torch.cuda.is_available() and ctx.input_device == -1:
  10. # Perform CPU to GPU copies in a background stream
  11. streams = [_get_stream(device) for device in target_gpus]
  12. # 调用C++进行操作
  13. outputs = comm.scatter(input, target_gpus, chunk_sizes, ctx.dim, streams)
  14. # Synchronize with the copy stream
  15. if streams is not None:
  16. for i, output in enumerate(outputs):
  17. with torch.cuda.device(target_gpus[i]):
  18. main_stream = torch.cuda.current_stream()
  19. main_stream.wait_stream(streams[i]) # 同步
  20. output.record_stream(main_stream) # 同步
  21. return outputs
  22. @staticmethod
  23. def backward(ctx, *grad_output):
  24. return None, None, None, Gather.apply(ctx.input_device, ctx.dim, *grad_output)

4.2.4 comm.scatter

该函数主要是调用 torch._C._scatter,这样就进入了C++世界。

  1. def scatter(tensor, devices=None, chunk_sizes=None, dim=0, streams=None, *, out=None):
  2. """Scatters tensor across multiple GPUs. """
  3. tensor = _handle_complex(tensor)
  4. if out is None:
  5. devices = [_get_device_index(d) for d in devices]
  6. return tuple(torch._C._scatter(tensor, devices, chunk_sizes, dim, streams))
  7. else:
  8. return tuple(torch._C._scatter_out(tensor, out, dim, streams))

4.2.5 C++

在转换文件之中,可以看到 scatter 是我们想分析的目标。

  1. .def(
  2. "_scatter",
  3. [](at::Tensor& tensor,
  4. std::vector<int64_t>& devices,
  5. c10::optional<std::vector<int64_t>> chunk_sizes,
  6. int64_t dim,
  7. c10::optional<py::object> py_streams) {
  8. c10::optional<std::vector<c10::optional<at::cuda::CUDAStream>>> streams;
  9. if (py_streams) {
  10. py::handle handle = *py_streams;
  11. streams = THPUtils_PySequence_to_CUDAStreamList(handle.ptr());
  12. }
  13. // Note: We're holding the GIL up to here.
  14. pybind11::gil_scoped_release no_gil;
  15. // 实际需要看这里
  16. return scatter(tensor, devices, chunk_sizes, dim, streams);
  17. },
  18. py::arg("tensor"),
  19. py::arg("devices"),
  20. py::arg("chunk_sizes"),
  21. py::arg("dim"),
  22. py::arg("streams"))

在 scatter 之中可以看到,scatter就是把数据分布到各个GPU之上,逻辑如下:

  • 首先调用 split_with_sizes 或者chunk 把tensor分割成 chunks。
  • 其次把 chunks 分布到各个GPU之上,具体是通过 to 分发完成的。
  1. std::vector<at::Tensor> scatter(
  2. const at::Tensor& tensor,
  3. at::IntArrayRef devices,
  4. const c10::optional<std::vector<int64_t>>& chunk_sizes,
  5. int64_t dim,
  6. const c10::optional<std::vector<c10::optional<at::cuda::CUDAStream>>>&
  7. streams) {
  8. dim = at::maybe_wrap_dim(dim, tensor);
  9. // 首先把tensor分割成 chunks
  10. std::vector<at::Tensor> chunks = chunk_sizes
  11. ? tensor.split_with_sizes(/*split_sizes=*/*chunk_sizes, /*dim=*/dim)
  12. : tensor.chunk(/*chunks=*/devices.size(), /*dim=*/dim);
  13. at::cuda::OptionalCUDAStreamGuard cuda_guard;
  14. // 其次把 chunks 分布到各个GPU之上
  15. for (size_t i = 0; i < chunks.size(); ++i) {
  16. const auto device_index = static_cast<int16_t>(devices[i]);
  17. if (device_index != tensor.get_device()) {
  18. if (i < (streams ? streams->size() : 0U) && (*streams)[i]) {
  19. cuda_guard.reset_stream(*(*streams)[i]);
  20. }
  21. chunks[i] = chunks[i].to( // 拷贝
  22. {DeviceType::CUDA, device_index},
  23. /*non_blocking=*/true,
  24. /*copy=*/false,
  25. /*memory_format=*/at::MemoryFormat::Preserve);
  26. }
  27. }
  28. return chunks; // 返回结果
  29. }

4.3 复制(模型)

目前,我们已经使用 Scatter 函数将数据从 device[0] 分配并复制到不同的卡,下面会用 Replicate 函数将模型从 device[0] 复制到不同的卡。

  1. # 分发模型
  2. replicas = self.replicate(self.module, self.device_ids[:len(inputs)])

对应我们传播图是:

replicate 只是转发,我们还需要接着看。

  1. def replicate(self, module, device_ids):
  2. return replicate(module, device_ids, not torch.is_grad_enabled())

4.3.1 replicate

replicate 具体逻辑是:

  • 使用 _replicatable_module 看看是否可以安全的复制模型。

  • 看看有多少个GPU,需要复制多少份。

  • 复制操作。

    • 复制 parameters。

      • 使用 _broadcast_coalesced_reshape 来把parameters拷贝到各个GPU。
    • 复制buffers。
      • 首先统计一下buffers。
      • 记录需要求导的 buffer 的 index。
      • 记录不需要求导的 buffer 的 index。
      • 对于两种buffers分别使用_broadcast_coalesced_reshape拷贝到各个GPU。
    • 复制模型。
      • modules()返回一个包含当前模型所有模块的迭代器。转变成list,可以认为把模型打平了。
      • 遍历modules,往每个module_copies里面添加模型的每一层。
      • 最终,module_copies[j] 里面包含了模型的每一层,即module_copies[j][i] 就是模型的第 i 层。
  • 配置操作。

    • 就是配置模型网络,把GPU中数据的 reference 配置到 modules 数组的每一个module 之中,这样这些 module 就是完备模型了。
    • 因为之前是把嵌套的模型网络打散了分别拷贝到GPU:buffers和parameters也分别拷贝到了GPU。现在需要把它们重新配置到浅拷贝的模型之中,这样就把模型逻辑补齐了。
    • 遍历模型每个子模块,只配置需要的部分参数。
      • 处理 其子_modules_
      • 处理 其_parameters。
      • 处理 其 _buffers。
  • 后续并行操作时候,每一个 worker 会得到 modules 数组的每一个module,就在这个 module 之上进行训练。

具体代码如下:

  1. def replicate(network, devices, detach=False):
  2. if not _replicatable_module(network):
  3. raise RuntimeError("Cannot replicate network where python modules are "
  4. "childrens of ScriptModule")
  5. if not devices:
  6. return []
  7. # 看看有多少个GPU,需要复制多少份
  8. devices = [_get_device_index(x, True) for x in devices]
  9. num_replicas = len(devices) # 复制这些份
  10. # 1)复制操作
  11. # 复制参数 parameters
  12. params = list(network.parameters())
  13. param_indices = {param: idx for idx, param in enumerate(params)}
  14. # 拷贝到各个GPU,我们随后会讲解_broadcast_coalesced_reshape
  15. param_copies = _broadcast_coalesced_reshape(params, devices, detach)
  16. # 复制buffers
  17. # 首先统计一下buffers
  18. buffers = list(network.buffers())
  19. buffers_rg = [] # 需要求导的
  20. buffers_not_rg = [] # 不需要求导的
  21. for buf in buffers:
  22. if buf.requires_grad and not detach:
  23. buffers_rg.append(buf)
  24. else:
  25. buffers_not_rg.append(buf)
  26. # 记录需要求导的 buffer 的 index
  27. buffer_indices_rg = {buf: idx for idx, buf in enumerate(buffers_rg)}
  28. # 记录不需要求导的 buffer 的 index
  29. buffer_indices_not_rg = {buf: idx for idx, buf in enumerate(buffers_not_rg)}
  30. # 对于两种buffers分别拷贝到各个GPU
  31. buffer_copies_rg = _broadcast_coalesced_reshape(buffers_rg, devices, detach=detach)
  32. buffer_copies_not_rg = _broadcast_coalesced_reshape(buffers_not_rg, devices, detach=True)
  33. # 准备拷贝模型网络
  34. modules = list(network.modules()) # modules()返回一个包含当前模型所有模块的迭代器。转变成list,可以认为把模型打平了
  35. module_copies = [[] for device in devices] # 为各个GPU准备好空list
  36. module_indices = {}
  37. # 得到模型的浅拷贝列表
  38. for i, module in enumerate(modules): # 遍历模型 list
  39. module_indices[module] = i
  40. for j in range(num_replicas):
  41. replica = module._replicate_for_data_parallel() # 获取浅拷贝
  42. # This is a temporary fix for DDP. DDP needs to access the
  43. # replicated model parameters. It used to do so through
  44. # `mode.parameters()`. The fix added in #33907 for DP stops the
  45. # `parameters()` API from exposing the replicated parameters.
  46. # Hence, we add a `_former_parameters` dict here to support DDP.
  47. replica._former_parameters = OrderedDict()
  48. module_copies[j].append(replica) # 往每个module_copies里面添加模型的每一层
  49. # 最终,module_copies[j] 里面包含了模型的每一层,即module_copies[j][i] 就是模型的第 i 层
  50. # 2)配置操作
  51. # 这一步的目的是:把GPU中数据的reference赋值到浅拷贝之中,变成完备模型。因为之前是把嵌套的模型网络打散了分别拷贝到GPU,buffers和parameters也分别拷贝到了GPU,现在把他们构建到浅拷贝的模型之中,把模型逻辑补齐。
  52. for i, module in enumerate(modules): # 遍历模型每个子模块,只赋值需要的部分参数
  53. # 处理其子_modules
  54. for key, child in module._modules.items():
  55. if child is None:
  56. for j in range(num_replicas):
  57. replica = module_copies[j][i] # module_copies[j]是第j个模型拷贝
  58. replica._modules[key] = None
  59. else:
  60. module_idx = module_indices[child]
  61. for j in range(num_replicas):
  62. replica = module_copies[j][i] # module_copies[j]是第j个模型拷贝
  63. setattr(replica, key, module_copies[j][module_idx]) # 设置第j个模型的对应部分,下同
  64. # 处理_parameters
  65. for key, param in module._parameters.items():
  66. if param is None:
  67. for j in range(num_replicas):
  68. replica = module_copies[j][i]
  69. replica._parameters[key] = None
  70. else:
  71. param_idx = param_indices[param]
  72. for j in range(num_replicas):
  73. replica = module_copies[j][i]
  74. param = param_copies[j][param_idx]
  75. # parameters in replicas are no longer leaves,
  76. # so setattr them as non-parameter attributes
  77. setattr(replica, key, param)
  78. # expose the parameter for DDP
  79. replica._former_parameters[key] = param
  80. # 处理 _buffers
  81. for key, buf in module._buffers.items():
  82. if buf is None:
  83. for j in range(num_replicas):
  84. replica = module_copies[j][i]
  85. replica._buffers[key] = None
  86. else:
  87. if buf.requires_grad and not detach:
  88. buffer_copies = buffer_copies_rg
  89. buffer_idx = buffer_indices_rg[buf]
  90. else:
  91. buffer_copies = buffer_copies_not_rg
  92. buffer_idx = buffer_indices_not_rg[buf]
  93. for j in range(num_replicas):
  94. replica = module_copies[j][i]
  95. setattr(replica, key, buffer_copies[j][buffer_idx])
  96. return [module_copies[j][0] for j in range(num_replicas)]

4.3.2 检查拷贝

_replicatable_module 用来检查模型是否可以安全拷贝。

  1. # Check if we can safely replicate the module.
  2. # there are two types of module:
  3. # 1. python modules
  4. # 2. ScriptModule
  5. #
  6. # currently a module cannot be replicated properly if the descendants of
  7. # any ScriptModule contains python module (type 1 above)
  8. def _replicatable_module(module, memo=None):
  9. # module.modules() contains module itself as the first element
  10. def descendant_modules(module):
  11. gen = module.modules()
  12. next(gen)
  13. return gen
  14. if not _is_jit_enabled():
  15. return True
  16. if memo is None:
  17. memo = set()
  18. # memoize visited modules
  19. memo.add(module)
  20. if _is_script_module(module):
  21. memo.update(descendant_modules(module))
  22. return all(_is_script_module(descendant) for
  23. descendant in descendant_modules(module))
  24. for child in module.children():
  25. # since any unreplicatable module will cause the check to return
  26. # False early, visited modules here can be safely ignored.
  27. if child in memo:
  28. continue
  29. if not _replicatable_module(child, memo):
  30. return False
  31. return True

4.3.3 共享拷贝

在 PyTorch 之中,有浅拷贝和深拷贝之分。

假定模型内部是一系列参数矩阵,model这个对象实际上是指向各个参数矩阵。

  • 浅拷贝(shadow copy) 则只是拷贝最外层的数值和指针,不拷贝更深层次的对象,就是只拷贝了父对象。model.state_dict()也是浅拷贝,如果令param=model.state_dict(),那么当你修改param,相应地也会修改model的参数。
  • 与之对应,深拷贝(deepcopy):拷贝数值、指针和指针指向的深层次内存空间,即拷贝了父对象及其子对象。

比如:

  1. import torch
  2. import copy
  3. # a引用指向某块内存空间
  4. a = torch.nn.Linear(in_features=5, out_features=1, bias=True)
  5. # 浅拷贝相当于拷贝一个引用,所以他们指向的内存空间是一样的
  6. b = copy.copy(a)
  7. # state_dict is shadow copy
  8. p = a.state_dict()
  9. print(id(a.state_dict()) == id(p)) # False,这两个不相等
  10. # 通过引用p去修改内存空间
  11. print(a.weight)
  12. p['weight'][0][0] = 8.8888
  13. # 可以看到a指向的内存空间也被修改了
  14. print(a.weight)

输出如下:

  1. False
  2. Parameter containing:
  3. tensor([[-0.2253, 0.0802, 0.3984, -0.1208, 0.3796]], requires_grad=True)
  4. Parameter containing:
  5. tensor([[ 8.8888, 0.0802, 0.3984, -0.1208, 0.3796]], requires_grad=True)

具体回到我们的分析,在 module类中,有 _replicate_for_data_parallel 方法,其用来返回一个副本,这些副本和原始模型共享存储,就是浅拷贝。

  1. def _replicate_for_data_parallel(self):
  2. replica = self.__new__(type(self))
  3. replica.__dict__ = self.__dict__.copy()
  4. # replicas do not have parameters themselves, the replicas reference the original
  5. # module.
  6. replica._parameters = OrderedDict()
  7. replica._buffers = replica._buffers.copy() # 浅拷贝
  8. replica._modules = replica._modules.copy() # 浅拷贝模型内部的子模块
  9. replica._is_replica = True
  10. return replica

可以认为,在设置操作之前,拷贝如下:

  1. +---------------------------------------------------------------+
  2. | +----------------------+ |
  3. | CPU | Module | |
  4. | | | |
  5. | | _parameters | |
  6. | | | |
  7. | +--------------> _buffers <-------------+ |
  8. | | | | | |
  9. | | +-------> _modules <----------+ | |
  10. | | | | | | | |
  11. | | | +----------------------+ | | |
  12. | +---------------------+ | +----------------------+ | | |
  13. | | module_copies[0] | | | | module_copies[1] | | | |
  14. | | | | | | | | | |
  15. | | _parameters | | | | _parameters | | | |
  16. | | | | | | | | | |
  17. | | _buffers +----+ | | | _buffers +--------------+ |
  18. | | | | | | | |
  19. | | _modules +-------->+ | _modules +--------->+ |
  20. | | | | | |
  21. | +---------------------+ +----------------------+ |
  22. +---------------------------------------------------------------+
  23. +---------------------+ +----------------------+
  24. | GPU 0 | | GPU 1 |
  25. | | | |
  26. | _parameters | | _parameters |
  27. | | | |
  28. | _buffers | | _buffers |
  29. | | | |
  30. | | | |
  31. | | | |
  32. +---------------------+ +----------------------+

在设置操作之后,则如下:

  1. +-----------------------------------------------------------------+
  2. | CPU +----------------------+ |
  3. | | Module | |
  4. | | | |
  5. | | _parameters | |
  6. | | | |
  7. | | _buffers | |
  8. | | | |
  9. | | _modules | |
  10. | | | |
  11. | +----------------------+ |
  12. | +---------------------+ +----------------------+ |
  13. | | module_copies[0] | | module_copies[1] | |
  14. | | | | | |
  15. +---------+ _parameters | | _parameters +-----------+ |
  16. | | | | | | | |
  17. | | | _buffers +------------+ | _buffers +-----------+ | |
  18. | | | | | | | | | |
  19. | | | _modules | | | _modules | | | |
  20. | | | | | | | | | |
  21. | | +---------------------+ | +----------------------+ | | |
  22. | +-----------------------------------------------------------------+
  23. | | | |
  24. | +---------------------+ | +----------------------+ | |
  25. | | GPU 0 | | | GPU 1 | | |
  26. | | | | | | | |
  27. +---------> _parameters | | | _parameters <----------+
  28. | | | | | |
  29. | _buffers <----------+ | _buffers <--------+
  30. | | | |
  31. | | | |
  32. | | | |
  33. +---------------------+ +----------------------+

4.3.4 拷贝操作

4.3.4.1 _broadcast_coalesced_reshape

拷贝参数都用到了_broadcast_coalesced_reshape。

  1. def _broadcast_coalesced_reshape(tensors, devices, detach=False):
  2. from ._functions import Broadcast
  3. if detach:
  4. # 如果是detach,就直接调用
  5. return comm.broadcast_coalesced(tensors, devices)
  6. else:
  7. # Use the autograd function to broadcast if not detach
  8. if len(tensors) > 0:
  9. # 否则先用Broadcast过度一下,最后还是调用broadcast_coalesced
  10. tensor_copies = Broadcast.apply(devices, *tensors)
  11. return [tensor_copies[i:i + len(tensors)]
  12. for i in range(0, len(tensor_copies), len(tensors))]
  13. else:
  14. return []
4.3.4.2 Broadcast

使用 Broadcast 过度一下的原因是:因为张量不是 detached,所以除了广播之外,还需要在上下文中设置哪些不需要梯度。在某些情况下,用户自定义的Function可能需要知道此情况。

  1. class Broadcast(Function):
  2. @staticmethod
  3. def forward(ctx, target_gpus, *inputs):
  4. assert all(i.device.type != 'cpu' for i in inputs), (
  5. 'Broadcast function not implemented for CPU tensors'
  6. )
  7. target_gpus = [_get_device_index(x, True) for x in target_gpus]
  8. ctx.target_gpus = target_gpus
  9. if len(inputs) == 0:
  10. return tuple()
  11. ctx.num_inputs = len(inputs)
  12. # input 放在 device[0]
  13. ctx.input_device = inputs[0].get_device()
  14. # 和 detach 的情形一样
  15. outputs = comm.broadcast_coalesced(inputs, ctx.target_gpus)
  16. non_differentiables = []
  17. # 在上下文中设置哪些不需要梯度
  18. for idx, input_requires_grad in enumerate(ctx.needs_input_grad[1:]):
  19. if not input_requires_grad:
  20. for output in outputs:
  21. non_differentiables.append(output[idx])
  22. ctx.mark_non_differentiable(*non_differentiables)
  23. return tuple([t for tensors in outputs for t in tensors])
  24. @staticmethod
  25. def backward(ctx, *grad_outputs):
  26. return (None,) + ReduceAddCoalesced.apply(ctx.input_device, ctx.num_inputs, *grad_outputs)

其中,mark_non_differentiable 定义在 torch/csrc/autograd/custom_function.cpp,这里会在 AutogradContext 配置非微分的变量。

  1. void AutogradContext::mark_non_differentiable(const variable_list &outputs) {
  2. non_differentiable_.clear();
  3. non_differentiable_.reserve(outputs.size());
  4. for(auto& var : outputs) {
  5. non_differentiable_.insert(var.unsafeGetTensorImpl());
  6. }
  7. }
4.3.4.3 broadcast_coalesced

broadcast_coalesced 会跳转到 C++世界。

  1. def broadcast_coalesced(tensors, devices, buffer_size=10485760):
  2. """Broadcasts a sequence tensors to the specified GPUs.
  3. Small tensors are first coalesced into a buffer to reduce the number
  4. of synchronizations.
  5. Args:
  6. tensors (sequence): tensors to broadcast. Must be on the same device,
  7. either CPU or GPU.
  8. devices (Iterable[torch.device, str or int]): an iterable of GPU
  9. devices, among which to broadcast.
  10. buffer_size (int): maximum size of the buffer used for coalescing
  11. Returns:
  12. A tuple containing copies of :attr:`tensor`, placed on :attr:`devices`.
  13. """
  14. devices = [_get_device_index(d) for d in devices]
  15. tensors = [_handle_complex(t) for t in tensors]
  16. return torch._C._broadcast_coalesced(tensors, devices, buffer_size)
4.3.4.4 C++

从初始化代码中可以看到,具体在 broadcast_coalesced 完成。

  1. auto m = py::cast<py::module>(module);
  2. m.def(
  3. "_broadcast_coalesced",
  4. [](std::vector<at::Tensor>& tensors,
  5. std::vector<int64_t> devices,
  6. size_t buffer_size) {
  7. return broadcast_coalesced(tensors, devices, buffer_size);
  8. },
  9. py::arg("tensors"),
  10. py::arg("devices"),
  11. py::arg("buffer_size"),
  12. py::call_guard<py::gil_scoped_release>())

具体代码位于 torch/csrc/cuda/comm.cpp。我们研究一下其注释。

  • broadcast_coalesced 会把变量分发给所有GPU。在broadcast_coalesced中,多个变量可以合并成一个大变量,然后广播到其他设备,然后会根据原始形状进行拆分(split)。

  • 拆分(split)时,视图操作将使所有变量一起广播以共享一个版本计数器,因为它们都是大变量的视图。但是,该大变量会立即被丢弃,并且所有这些变量根本不共享存储。

  • 例如,当两个缓冲区在“DataParallel”中一起广播,其中一个在“forward”期间执行in-place操作,而另一个在backward中被使用,autograd引擎将发出抱怨。因此,我们在广播后重新包装这些变量,并为它们提供单独的版本计数器。

  1. // broadcast_coalesced
  2. // ~~~~~~~~~~~~~~~~~~~
  3. //
  4. // In broadcast_coalesced, multiple variables may be coalesced into a single
  5. // large one, broadcast to other devices, and the get split according to the
  6. // original shapes.
  7. //
  8. // When splitting, the view operations will make all Variables broadcast
  9. // together to share a single version counter, because they are all views of the
  10. // large Variable. However, that large Variable is immediately discarded and all
  11. // these Variables do not share storage at all.
  12. //
  13. // For example, when two buffers are broadcast together in `DataParallel` and
  14. // one of them is modified in-place during `forward` but the other is needed in
  15. // backward, autograd engine will complain.
  16. //
  17. // We thus re-wrap these Variables after broadcasting (i.e., effectively doing
  18. // what is equivalent to .data in Python), and give them individual version
  19. // counters.

broadcast_coalesced 方法的具体参数解释如下:

  • tensors 必须在同一个设备,CPU 或者 GPU;
  • devices 即是要拷贝到的设备;
  • buffer_size 则是最大的buffer。这里用到 buffer 将小张量合并到缓冲区以减少同步次数;
  1. tensor_list2d broadcast_coalesced(
  2. TensorList tensors,
  3. IntArrayRef devices,
  4. size_t buffer_size) {
  5. TORCH_CHECK(
  6. std::all_of(
  7. tensors.begin(),
  8. tensors.end(),
  9. [&](const at::Tensor& t) { return t.get_device() == devices[0]; }),
  10. "All tensors must be on devices[0]: ",
  11. devices[0]);
  12. #ifdef USE_NCCL
  13. buffer_size = std::min(torch::cuda::nccl::get_max_count(), buffer_size);
  14. #endif
  15. tensor_list2d outputs(devices.size());
  16. outputs[0] = tensors.vec();
  17. for (auto& o : outputs)
  18. o.reserve(tensors.size());
  19. unique_type_checker type_checker;
  20. at::cuda::CUDAGuard device_guard(devices[0]);
  21. for (auto& chunk : utils::take_tensors(tensors, buffer_size)) {
  22. auto type_id = chunk.type_id();
  23. type_checker.show(type_id);
  24. std::vector<at::Tensor> results;
  25. if (chunk.options().is_sparse()) {
  26. auto flat_tuple = utils::flatten_sparse_tensors(chunk.tensors);
  27. auto broadcast_indices = broadcast(flat_tuple.first, devices); //这里进行广播
  28. auto broadcast_values = broadcast(flat_tuple.second, devices); //这里进行广播
  29. results.reserve(devices.size());
  30. for (size_t i = 1, num_devices = devices.size(); i < num_devices; ++i) {
  31. device_guard.set_index(devices[i]);
  32. auto& device_outputs = outputs[i];
  33. auto& inds = broadcast_indices[i];
  34. auto& vals = broadcast_values[i];
  35. for (auto& t :
  36. utils::unflatten_sparse_tensors(inds, vals, chunk.tensors)) {
  37. Variable var = t;
  38. device_outputs.push_back(make_variable(var.tensor_data(), false));
  39. }
  40. }
  41. } else {
  42. auto results = // 这里进行广播
  43. broadcast(utils::flatten_dense_tensors(chunk.tensors), devices);
  44. for (size_t i = 1, num_devices = devices.size(); i < num_devices; ++i) {
  45. device_guard.set_index(devices[i]);
  46. auto& device_outputs = outputs[i];
  47. for (auto& t :
  48. utils::unflatten_dense_tensors(results[i], chunk.tensors)) {
  49. Variable var = t;
  50. device_outputs.push_back(make_variable(var.tensor_data(), false));
  51. }
  52. }
  53. }
  54. }
  55. // If we only saw a single tensor type, then we can skip expensive reordering
  56. if (!type_checker.unique) {
  57. for (auto& o : outputs)
  58. utils::reorder_tensors_like(o, tensors);
  59. }
  60. return outputs;
  61. }

broadcast 方法如下:

  1. std::vector<Tensor> broadcast(const Tensor& tensor, IntArrayRef devices) {
  2. std::vector<Tensor> diff_device_dst_tensors;
  3. diff_device_dst_tensors.reserve(devices.size());
  4. for (auto device : devices) {
  5. if (device != tensor.get_device()) {
  6. diff_device_dst_tensors.push_back(at::empty(
  7. tensor.sizes(),
  8. tensor.options().device(
  9. at::Device(DeviceType::CUDA, device)))); // preserve memory format
  10. }
  11. }
  12. // 继续调用操作
  13. _broadcast_out_impl(tensor, diff_device_dst_tensors);
  14. std::vector<Tensor> dst_tensors;
  15. dst_tensors.reserve(devices.size());
  16. auto it = diff_device_dst_tensors.begin();
  17. for (auto device : devices) {
  18. if (device != tensor.get_device()) {
  19. dst_tensors.push_back(*it++);
  20. } else {
  21. dst_tensors.push_back(tensor);
  22. }
  23. }
  24. TORCH_INTERNAL_ASSERT(it == diff_device_dst_tensors.end());
  25. return dst_tensors;
  26. }

最终调用到 _broadcast_out_impl,把源张量 (CPU or CUDA) 广播到一个CUDA设备列表上,其调用了nccl::broadcast(nccl_list)。

  1. static inline std::vector<Tensor>& _broadcast_out_impl(
  2. const Tensor& tensor,
  3. std::vector<Tensor>& out_tensors) {
  4. #ifdef USE_NCCL
  5. std::vector<Tensor> nccl_list;
  6. nccl_list.reserve(out_tensors.size() + 1);
  7. nccl_list.push_back(tensor);
  8. for (auto& out_tensor : out_tensors) {
  9. nccl_list.push_back(out_tensor);
  10. }
  11. if (nccl::is_available(nccl_list)) {
  12. nccl::broadcast(nccl_list); // 这里调用了 NCCL 操作
  13. } else {
  14. #else
  15. {
  16. #endif
  17. for (auto& out_tensor : out_tensors) {
  18. out_tensor.copy_(tensor, /*non_blocking=*/true);
  19. }
  20. }
  21. return out_tensors;
  22. }

至此,我们已经把数据和模型都分布到其他 GPU 之上。我们把目前的前向图先构建出来,大家可以有一个清晰的理解,replicate 调用了Broadcast.forward,同时往其context 存储了input_device和num_inputs。接下来可以进行前行传播。

  1. +----------------------------------------------------------------------------------------+
  2. | DataParallel.forward |
  3. | |
  4. | |
  5. | replicate +---------------> parallel_apply gather |
  6. | |
  7. +----------------------------------------------------------------------------------------+
  8. +---------------------------+
  9. | Broadcast |
  10. | |
  11. | |
  12. | |
  13. | forward() +----------->
  14. | |
  15. | |
  16. | +---------------------+ |
  17. | | ctx | |
  18. | | input_device | |
  19. | | | |
  20. | | num_inputs | |
  21. | | | |
  22. | +---------------------+ |
  23. | |
  24. | |
  25. | |
  26. | |
  27. | |
  28. | |
  29. +---------------------------+

因为篇幅所限,下一篇我们从并行操作(前向传播)开始继续分析。

0xFF 参考

PyTorch 源码解读之 torch.optim:优化算法接口详解

pytorch(分布式)数据并行个人实践总结——DataParallel/DistributedDataParallel

Pytorch的nn.DataParallel

PyTorch 源码解读之分布式训练了解一下?

https://discuss.pytorch.org/t/dataparallel-imbalanced-memory-usage/22551/20

[原创][深度][PyTorch] DDP系列第二篇:实现原理与源代码解析

Pytorch-CUDA从入门到放弃(二)

Pytorch踩坑记:赋值、浅拷贝、深拷贝三者的区别以及model.state_dict()和model.load_state_dict()的坑点

PyTorch 源码解读之 DP & DDP:模型并行和分布式训练解析

[源码解析] PyTorch 分布式(2) ----- DataParallel(上)的更多相关文章

  1. [源码解析] PyTorch 分布式(3) ----- DataParallel(下)

    [源码解析] PyTorch 分布式(3) ----- DataParallel(下) 目录 [源码解析] PyTorch 分布式(3) ----- DataParallel(下) 0x00 摘要 0 ...

  2. [源码解析] PyTorch 分布式 Autograd (5) ---- 引擎(上)

    [源码解析] PyTorch 分布式 Autograd (5) ---- 引擎(上) 目录 [源码解析] PyTorch 分布式 Autograd (5) ---- 引擎(上) 0x00 摘要 0x0 ...

  3. [源码解析] PyTorch 分布式(4)------分布式应用基础概念

    [源码解析] PyTorch 分布式(4)------分布式应用基础概念 目录 [源码解析] PyTorch 分布式(4)------分布式应用基础概念 0x00 摘要 0x01 基本概念 0x02 ...

  4. [源码解析] PyTorch分布式(5) ------ DistributedDataParallel 总述&如何使用

    [源码解析] PyTorch 分布式(5) ------ DistributedDataParallel 总述&如何使用 目录 [源码解析] PyTorch 分布式(5) ------ Dis ...

  5. [源码解析] PyTorch分布式(6) -------- DistributedDataParallel -- 初始化&store

    [源码解析] PyTorch分布式(6) ---DistributedDataParallel -- 初始化&store 目录 [源码解析] PyTorch分布式(6) ---Distribu ...

  6. [源码解析] PyTorch 分布式(7) ----- DistributedDataParallel 之进程组

    [源码解析] PyTorch 分布式(7) ----- DistributedDataParallel 之进程组 目录 [源码解析] PyTorch 分布式(7) ----- DistributedD ...

  7. [源码解析] PyTorch 分布式(8) -------- DistributedDataParallel之论文篇

    [源码解析] PyTorch 分布式(8) -------- DistributedDataParallel之论文篇 目录 [源码解析] PyTorch 分布式(8) -------- Distrib ...

  8. [源码解析] PyTorch 分布式(9) ----- DistributedDataParallel 之初始化

    [源码解析] PyTorch 分布式(9) ----- DistributedDataParallel 之初始化 目录 [源码解析] PyTorch 分布式(9) ----- DistributedD ...

  9. [源码解析] PyTorch 分布式(10)------DistributedDataParallel 之 Reducer静态架构

    [源码解析] PyTorch 分布式(10)------DistributedDataParallel之Reducer静态架构 目录 [源码解析] PyTorch 分布式(10)------Distr ...

随机推荐

  1. Navicat连接数据库成功,新建查询时提示错误“Cannot create file ……”

    Navicat连接数据库成功,新建查询时提示错误"Cannot create file --" 原因:编辑连接{高级}<设置位置>被修改,该oci.dll不正确 解决方 ...

  2. Windows下nginx报错解决:CreateFile() "xxx/logs/nginx.pid" failed

    写在前面 本文给出Windows下nginx报错:CreateFile() "xxx/logs/nginx.pid" failed 的解决方法并分析了出错原因,其中 xxx 表示n ...

  3. 测试用例 setup 和 和 teardown

    前言 学过unittest的都知道里面用前置和后置setup呾teardown非常好用,在每次用例开始前呾结束后都去执行一次.当然迓有更高级一点的 setupClass 呾 teardownClass ...

  4. NOIP 模拟 十一

    T1 math 分析性质,对于 $$ ax+by=c$$ 有 $$ gcd(x,y)|c$$ 所以 $$ gcd(a_1,a_2 .....,a_n)|num$$ 换句话说就是最后得到的数一定是 GC ...

  5. STAR-CCM+使用教程(开坑)

    前言: 之前在项目中经常使用STAR-CCM+做数值模拟,中间也陆陆续续折腾过许久,踩过一些坑.未来考虑转行,以后可能也会不再用到这CFD软件,所以正好趁这个机会在这做一个教程.记录下自己STAR-C ...

  6. Spring中IOC的理解

    Spring中IOC的理解 1.什么是IOC? (1)控制反转.把对象创建和对象间的调用过程交给Spring进行管理. (2)使用IOC的目的:为了耦合度降低. 2.IOC底层原理? (1)xml解析 ...

  7. 《面试八股文》之 JVM 20卷

    微信公众号:moon聊技术 关注选择" 星标 ", 重磅干货,第一 时间送达! [如果你觉得文章对你有帮助,欢迎关注,在看,点赞,转发] 大家好,我是 moon. <面试八股 ...

  8. Python - __all__ 变量

    import * 当我们向文件导入某个模块时,导入的是该模块中那些名称不以下划线(单下划线 _ 或者双下划线 __ )开头的变量.函数和类 因此,如果不想模块文件中的某个对象被引入到其它文件中使用,可 ...

  9. typora博客笔记上传图片时不能显示

    前言 markdown具有轻量化.易读易写等特性,并且对于图片.超链接.图片.数学公式都有支持. 但是最近在使用Typora的过程中我发现,在写文章笔记的时候导入的图片,因为图片保存在我们电脑本地,当 ...

  10. iOS Swift结构体与类的方法调度

    前言 hello,小伙伴们:在忙碌中闲暇之余给大家聊聊swift的知识点,今天给大家带来的是swift中结构体与类的方法调度详细区别,希望对你有所帮助,好了废话不用多说,接下来步入主题! 1.普通方法 ...