[源码解析] PyTorch 分布式(1) --- 数据加载之DistributedSampler

0x00 摘要

为了更好的介绍参数服务器Paracel的数据加载,我们临时插入两篇PyTorch的数据加载(因为字数太长,所以拆成两篇),主要是从分布式的角度进行切入。本文只算是开胃甜点,后续会有专门系列分析PyTorch分布式。

参数服务器系列其他文章如下:

[源码解析] 机器学习参数服务器ps-lite 之(1) ----- PostOffice

[源码解析] 机器学习参数服务器ps-lite(2) ----- 通信模块Van

[源码解析] 机器学习参数服务器ps-lite 之(3) ----- 代理人Customer

[源码解析]机器学习参数服务器ps-lite(4) ----- 应用节点实现

[源码解析] 机器学习参数服务器 Paracel (1)-----总体架构

[源码解析] 机器学习参数服务器 Paracel (2)--------SSP控制协议实现

0x01 数据加载

1.1 加速途径

当分布式训练时候,为了加速训练,有三个层面的工作需要处理。

  • 数据加载层面
  • 多机通讯层面
  • 代码层面

数据层面,可以使用多进程并行加载来加速数据预处理过程,也有利用GPU特点来加速,比如Nvidia DALI 通过将数据预处理放到 GPU 处理来解决 CPU 瓶颈问题。

多机通讯层面,有各种集合通信库可以利用,比如NCCL,OpenMPI, Gloo 等。

代码层面,可以使用框架提供的分布式API,或者利用 Horovod 来改造单机版代码,使其支持分布式任务。

接下来我们就看看数据层面如何加速。

1.2 并行处理

AI框架的数据处理主要如下并行处理:

  • 数据加载/处理使用CPU。
  • 训练使用GPU。

在理想状态下,应该是每轮迭代训练之前,CPU就完成加载,准备好训练数据,这样训练就可以持续无缝迭代。

然而,GPU算力每年会提升一倍,CPU的提升速度远远落后于GPU,所以CPU会是拖后腿的那个角色。这里不仅仅是CPU算力不足的问题,也包括村存储中读取数据速度不足的问题。

因此,机器学习对于数据加载和前期预处理的要求越来越高,必须在GPU计算时间内,完成下一迭代数据的准备工作,不能让GPU因为等待训练数据而空闲。

1.3 流水线

对于机器学习训练,加载数据可以分为三个步骤:

  • 将数据从磁盘或者分布式存储加载到主机(CPU)。
  • 将数据从主机可分页内存传输到主机固定内存。
  • 将数据从主机固定内存转移到主机GPU。

因此,流行的深度学习框架会依据加载步骤的特点和异构硬件的特点来进行流水线处理,从而提高数据处理过程的吞吐量。

流水线一般包括多个算子,每个算子内部由数据队列组成一个缓冲区,上游算子完成处理之后会传给给下游算子进行处理。这样每个算子任务会彼此独立,算子内部可以使用细粒度的多线程/多进程来并行加速,每个算子可以独立控制处理速度和内存以适配不同网络对于处理速度的需求。

如果算子内部数据队列不为空,模型就会一直源源不断获得数据,就不会因为等待训练数据而产生瓶颈。

下面是串行处理逻辑:

  1. +------+ +-----------+ +---------------------------+
  2. | | | | | |
  3. | Data +----------> | Load Data +---------> | Transfer to Pinned Memory |
  4. | | | | | |
  5. +------+ +-----------+ +---------------------------+

下面是并行流水线逻辑:

  1. +------------+
  2. +--------+ | |
  3. | | | Process 1 |
  4. | Data 1 +--------> | +------+
  5. | | | Load Data | |
  6. +--------+ | | |
  7. +------------+ |
  8. |
  9. |
  10. |
  11. +------------+ | +-----------------------------------+
  12. +--------+ | | | | |
  13. | | | Process 2 | +------> | Pin-memory process |
  14. | Data 2 +--------> | | | |
  15. | | | Load Data +-------------> | |
  16. +--------+ | | | Transfer to Pinned Memory |
  17. +------------+ +-----> | |
  18. | | |
  19. | +-----------------------------------+
  20. |
  21. +--------+ +------------+ |
  22. | | | | |
  23. | Data 3 +--------> | Process 3 +-------+
  24. | | | |
  25. +--------+ | Load Data |
  26. | |
  27. +------------+

1.4 GPU

本文到现在是解决CPU侧的数据传输问题,即:从磁盘加载数据,从可分页到固定内存。

但是,从固定内存到GPU的数据传输(tensor.cuda())也可以使用CUDA流进行流水线处理。

另外,深度学习应用程序需要复杂的多阶段数据处理管道,包括加载、解码、裁剪、调整大小和许多其他增强功能。这些目前在 CPU 上执行的数据处理管道已经成为瓶颈,限制了训练和推理的性能和可扩展性。

Nvidia DALI 通过将数据预处理放到 GPU 处理来解决 CPU 瓶颈问题,用户可以依据自己模型的特点,构建基于 GPU 的 pipeline,或者基于CPU的pipeline。

接下来我们就介绍PyTorch的数据加载,而且主要是从分布式的角度进行切入。

0x02 PyTorch分布式加载

2.1 DDP

pytorch为数据分布式训练提供了多种选择。随着应用从简单到复杂,从原型到产品,常见的开发轨迹可以是:

  • 如果数据和模型能放入单个GPU,使用单设备训练,此时不用担心训练速度;
  • 如果服务器上有多个GPU,并且你在代码修改量最小的情况下加速训练,使用单个机器多GPU DataParallel;
  • 如果你想进一步加速训练并且愿意写一点代码来启动,使用单个机器多个GPU DistributedDataParallel;
  • 如果应用程序跨机器边界扩展,使用多机器DistributedDataParallel和启动脚本;
  • 如果预期有错误(比如OOM)或者资源在训练过程中可以动态连接和分离,使用torchelastic来启动分布式训练。

与本文最相关的部分就是DDP,Distributed Data-Parallel Training(DDP)是一个广泛采用的单程序多数据训练方法。使用DDP,模型会被复制到每个进程,然后每个模型副本会被输入数据样本的不同子集。DDP负责梯度通信以保持模型副本的同步,并将其与梯度计算重叠以加快训练速度。

2.2 分布式加载

我们首先要看看分布式加载的总体结构。

给出示例代码,可以看到主要使用了 DataSet, DistributedSampler,DataLoader 这三个实体。

  1. sampler = DistributedSampler(dataset) if is_distributed else None
  2. loader = DataLoader(dataset, shuffle=(sampler is None), sampler=sampler)
  3. for epoch in range(start_epoch, n_epochs):
  4. if is_distributed:
  5. sampler.set_epoch(epoch)
  6. train(loader)

这三个概念的逻辑关系如下:

  • Dataset : 从名字可以知道,是数据集的意思。负责对原始训练数据的封装,将其封装成 Python 可识别的数据结构,Dataset的派生类必须提供接口一边获取单个数据。
  • Sampler : 从名字可知,是采样器,负责采样方式或者说是采样策略,实现某种提取/采样策略从Dataset之中拿到数据索引,供DataLoade使用。可以认为,Sampler 是指挥者,负责决定战斗在哪里开展。
  • DataLoader : 负责依据索引来从数据集中加载数据。支持 Map-style 和 Iterable-style 两种Dataset,支持单进程/多进程加载。Loader 就是具体作战的斗士,负责按照 Sampler的命令进行战斗。

具体如下图,简要说就是:

  1. DataSet 把数据集数目发给DistributedSampler。
  2. Sampler 按照某种规则发送数据indices给Loader。
  3. Loader 依据indices加载数据。
  4. Loader 把数据发给模型,进行训练。
  1. +------------------------+ +-----------+
  2. |DistributedSampler | |DataLoader |
  3. | | 2 indices | |
  4. | Some strategy +-------------------> | |
  5. | | | |
  6. |-------------+----------| | |
  7. ^ | | 4 data +-------+
  8. | | -------------->+ train |
  9. 1 | length | | +-------+
  10. | | |
  11. +-------------+----------+ | |
  12. |DataSet | | |
  13. | +---------+ | 3 Load | |
  14. | | Data +-------------------------> | |
  15. | +---------+ | | |
  16. | | | |
  17. +------------------------+ +-----------+

因为数据集不是分布式训练重点,所以本文接下来主要分析 Sampler。

Sampler 的重点就是:如何让每个worker在数据集中只加载自己所属的部分,并且worker之间实现对数据集的正交分配

0x03 DistributedSampler

对于数据并行和分布式训练,DistributedSampler 负责其数据采样的任务。

DistributedSampler 是 Sampler 的派生类。当 DistributedDataParallel 使用DistributedSampler 时,每个并行的进程都会得到一个DistributedSampler 实例,这个DistributedSampler 实例会给DataLoader发送指示,从而 DataLoader 加载具体数据。

DistributedSampler 加载策略负责只提供加载数据集中的一个子集,这些DistributedSampler 提供的子集之间不重叠,不交叉

3.1 初始化

__init__初始化代码主要是设置了本worker节点的各种信息,比如数据集dataset,rank(全局GPU序号),num_replicas 副本数目。并且计算出来所有样本数目total_size。

几个参数如下:

  • dataset : 就是采样的数据集。
  • num_replicas :参与分布式训练的进程数目,如果没有设置,则从group之中得到world_size作为进程数目。
  • rank : 当前进程的序号,如果没有设置,则从group之中得到。
  • shuffle :采样是否需要打乱indices。
  • seed :如果需要打乱,则设定一个random seed。
  • drop_last :如果不能均匀分割数据,是否需要把无法分配的尾部数据丢掉。
  • epoch :每次epoch都会shuffle数据集,如何保持shuffle之后数据集一致性?就是通过epoch完成。

具体代码如下,省略了异常处理。

  1. class DistributedSampler(Sampler[T_co]):
  2. def __init__(self, dataset: Dataset, num_replicas: Optional[int] = None,
  3. rank: Optional[int] = None, shuffle: bool = True,
  4. seed: int = 0, drop_last: bool = False) -> None:
  5. self.dataset = dataset
  6. self.num_replicas = num_replicas
  7. self.rank = rank
  8. self.epoch = 0
  9. self.drop_last = drop_last
  10. # If the dataset length is evenly divisible by # of replicas, then there
  11. # is no need to drop any data, since the dataset will be split equally.
  12. if self.drop_last and len(self.dataset) % self.num_replicas != 0: # type: ignore[arg-type]
  13. # Split to nearest available length that is evenly divisible.
  14. # This is to ensure each rank receives the same amount of data when
  15. # using this Sampler.
  16. self.num_samples = math.ceil(
  17. # `type:ignore` is required because Dataset cannot provide a default __len__
  18. # see NOTE in pytorch/torch/utils/data/sampler.py
  19. (len(self.dataset) - self.num_replicas) / self.num_replicas # type: ignore[arg-type]
  20. )
  21. else:
  22. self.num_samples = math.ceil(len(self.dataset) / self.num_replicas) # type: ignore[arg-type]
  23. self.total_size = self.num_samples * self.num_replicas
  24. self.shuffle = shuffle
  25. self.seed = seed

3.2 迭代方法

DistributedSampler 被实现成一个迭代器(类似于循环),因此会用到 python 抽象类的魔法方法:

  • __len__(self): 当被 len() 函数调用时的行为,一般返回迭代器中元素的个数。
  • __iter__(self): 当迭代容器中元素时的行为,实际上是返回是一个迭代器(通常是迭代器本身),每一次迭代得到的结果会被用来作为下一次迭代的初始值。

__iter__ 代码的一个技术细节是:

indices = indices[self.rank:self.total_size:self.num_replicas]

当一个list之中有双引号,比如 list[start:end:step],其意义是:

  • start: 起始位置
  • end: 结束位置
  • step: 步长

我们用一个例子来看看,比如:

  1. a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
  2. print(a[0:15:3])
  3. print(a[1:15:3])
  4. print(a[2:15:3])

得到:

  1. [1, 4, 7, 10, 13]
  2. [2, 5, 8, 11, 14]
  3. [3, 6, 9, 12, 15]

因为 indices[self.rank:self.total_size:self.num_replicas] 之中,num_replicas 实际就是rank的总数,所以这里每个worker就会严格返回自己rank对应的那部分数据序号

总结一下DistributedSampler的分配方法是:每段连续的 num_replicas 个数据被拆成一个一个,分给 num_replicas 个进程,而且是通过每个worker 的 rank 来获取数据,这样就达到了不重叠不交叉的目的,但也要注意的是:这样每个进程拿到的数据是不连续的

具体代码如下:

  1. class DistributedSampler(Sampler[T_co]):
  2. def __iter__(self) -> Iterator[T_co]:
  3. if self.shuffle: # 如果需要shuffle,则会基于epoch和seed进行处理
  4. # deterministically shuffle based on epoch and seed
  5. g = torch.Generator()
  6. g.manual_seed(self.seed + self.epoch)
  7. indices = torch.randperm(len(self.dataset), generator=g).tolist() # type: ignore[arg-type]
  8. else: # 否则直接返回数据集长度序列
  9. indices = list(range(len(self.dataset))) # type: ignore[arg-type]
  10. # 是否需要补齐数据
  11. if not self.drop_last:
  12. # add extra samples to make it evenly divisible
  13. padding_size = self.total_size - len(indices)
  14. if padding_size <= len(indices):
  15. indices += indices[:padding_size]
  16. else:
  17. indices += (indices * math.ceil(padding_size / len(indices)))[:padding_size]
  18. else:
  19. # remove tail of data to make it evenly divisible.
  20. indices = indices[:self.total_size]
  21. assert len(indices) == self.total_size
  22. # subsample
  23. # 依据自己的rank,依次返回自己的数据序号
  24. indices = indices[self.rank:self.total_size:self.num_replicas]
  25. assert len(indices) == self.num_samples
  26. return iter(indices)
  27. def __len__(self) -> int:
  28. return self.num_samples
  29. def set_epoch(self, epoch: int) -> None:
  30. r"""
  31. Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas
  32. use a different random ordering for each epoch. Otherwise, the next iteration of this
  33. sampler will yield the same ordering.
  34. Args:
  35. epoch (int): Epoch number.
  36. """
  37. self.epoch = epoch

内部变量之间逻辑如下:

  1. 从数据集获取长度length;
  2. 从配置得到 num_replicas(有几个rank),本身rank;
  3. 依据 数据集长度 和 num_replicas得到 num_samples 和 total_size;
  4. 最终给出 indices = indices[rank: total_size: num_replicas];
  5. 返回 indices 给DataLoader
  1. +-----------------------------------------------------------+
  2. | DistributedSampler |
  3. | |
  4. | 2 2 |
  5. | rank +---+ num_replicas |
  6. | + | + |
  7. | | | | 3 |
  8. | | | | |
  9. | | | v |
  10. | | | num_samples = ceil(len(dataset)/ num_replicas) |
  11. | | | + |
  12. | | | | |
  13. | | | | 3 |
  14. | | | v |
  15. | | | total_size = num_samples * num_replicas |
  16. | | | + |
  17. | |4 |4 |4 |
  18. | | | | |
  19. | v v v |
  20. | +-+----+------------+--------------------------------+ | +-------------+
  21. | | | | indices | |
  22. | | indices = indices[rank: total_size: num_replicas] +------------->+ DataLoader |
  23. | | ^ | | 5 | |
  24. | | | | | +-------------+
  25. | | | | |
  26. | +----------------------------------------------------+ |
  27. +-----------------------------------------------------------+
  28. |
  29. 1 | length
  30. +------+--------+
  31. | DataSet |
  32. +---------------+

3.3 shuffle数据集

每次epoch都会shuffle数据集,但是不同进程如何保持shuffle之后数据集一致性

DistributedSampler 使用当前的epoch作为随机数种子,在计算index之前就进行配置,从而保证不同进程都使用同样的随机数种子,这样shuffle出来的数据就能确保一致。

3.3.1 使用

从下面代码可以看出来,如果需要分布式训练,就对 sampler 设置 epoch。

  1. sampler = DistributedSampler(dataset) if is_distributed else None
  2. loader = DataLoader(dataset, shuffle=(sampler is None), ...,
  3. sampler=sampler)
  4. for epoch in range(start_epoch, n_epochs):
  5. if is_distributed:
  6. sampler.set_epoch(epoch) # 这设置epoch
  7. train(loader)

3.3.2 python

具体对应 DistributedSampler 的实现。

设置 epoch 很简单,就是配置下。

  1. def set_epoch(self, epoch: int) -> None:
  2. r"""
  3. Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas
  4. use a different random ordering for each epoch. Otherwise, the next iteration of this
  5. sampler will yield the same ordering.
  6. Args:
  7. epoch (int): Epoch number.
  8. """
  9. self.epoch = epoch

设置 random 种子的具体使用是在迭代函数之中:

  1. def __iter__(self) -> Iterator[T_co]:
  2. if self.shuffle:
  3. # deterministically shuffle based on epoch and seed
  4. g = torch.Generator()
  5. g.manual_seed(self.seed + self.epoch) # 这里设置随机种子
  6. indices = torch.randperm(len(self.dataset), generator=g).tolist() # type: ignore[arg-type]
  7. else:
  8. indices = list(range(len(self.dataset))) # type: ignore[arg-type]
  9. # 省略其他代码

3.3.3 C++

我们也可以提前看看在C++ 代码的DistributedRandomSampler,这是C++ API,也起到python同样作用。

我们可以看到设置种子和shuffle如下:

  1. void DistributedRandomSampler::reset(optional<size_t> new_size) {
  2. size_ = new_size.value_or(size_);
  3. populate_indices();
  4. std::mt19937 rand(epoch_);
  5. std::shuffle(all_indices_.begin(), all_indices_.end(), rand);
  6. sample_index_ = begin_index_;
  7. }

3.3.4 小结

我们扩展目前逻辑如下:

  1. 从数据集获取长度length;
  2. 从配置得到 num_replicas(有几个rank),本身rank,epoch;
  3. 用 epoch 来设置random seed;
  4. 利用random seed 对数据集 indices 进行打乱,后续就会一直使用 这个打乱的indices;
  5. 依据 数据集长度 和 num_replicas得到 num_samples 和 total_size;
  6. 结合之上各种数据条件,最终给出 indices = indices[rank: total_size: num_replicas];
  7. 返回 indices 给DataLoader
  1. +-----------------------------------------------------------------+
  2. | DistributedSampler |
  3. | |
  4. | |
  5. | 2 3 |
  6. | epoch +------> manual_seed(seed + epoch) +---------> indices |
  7. | + |
  8. | | |
  9. | | |
  10. | 2 2 | |
  11. | rank +---+ num_replicas 4 | |
  12. | + | + | |
  13. | | | | 5 | |
  14. | | | | | |
  15. | | | v | |
  16. | | | num_samples = ceil(len(dataset)/ num_replicas) | |
  17. | | | + | |
  18. | | | | | |
  19. | | | | 5 | |
  20. | | | v | |
  21. | | | total_size = num_samples * num_replicas | |
  22. | | | + | |
  23. | |6 |6 |6 | |
  24. | | | | | |
  25. | v v v | |
  26. | +-+----+------------+--------------------------------+ | |
  27. | | | | |
  28. | | indices = indices[rank: total_size: num_replicas] | <----+ |
  29. | | ^ + | |
  30. | | | | | |
  31. | | | | | |
  32. | +----------------------------------------------------+ |
  33. +-----------------------------------------------------------------+
  34. | |
  35. 1 | length 7 v indices
  36. |
  37. +-------+--------+ +-------------+
  38. | | | |
  39. | DataSet | | DataLoader |
  40. | | | |
  41. +----------------+ +-------------+

3.4 Sampler in C++

因为某些公司是C++开发,他们也有迫切的使用pytorch的需求,所以pytorch也提供了C++ API,我们接下来就看看如何实现。

3.4.1 定义

其类定义在:torch\csrc\api\include\torch\data\samplers\distributed.h

我们可以看到,DistributedSampler 是基类,主要成员变量是:

  • size_t size_ 文件大小

  • size_t num_replicas_ 副本数目

  • size_t rank_ 本sampler 对应哪个进程或者GPU

  • size_t epoch 本次训练的epoch

  • bool allow_duplicates_ 是否允许备份

接下来是两个派生类: DistributedRandomSampler 和 DistributedSequentialSampler。

  1. /// A `Sampler` that selects a subset of indices to sample from and defines a
  2. /// sampling behavior. In a distributed setting, this selects a subset of the
  3. /// indices depending on the provided num_replicas and rank parameters. The
  4. /// `Sampler` performs a rounding operation based on the `allow_duplicates`
  5. /// parameter to decide the local sample count.
  6. template <typename BatchRequest = std::vector<size_t>>
  7. class DistributedSampler : public Sampler<BatchRequest> {
  8. public:
  9. DistributedSampler(
  10. size_t size,
  11. size_t num_replicas = 1,
  12. size_t rank = 0,
  13. bool allow_duplicates = true)
  14. : size_(size),
  15. num_replicas_(num_replicas),
  16. rank_(rank),
  17. epoch_(0),
  18. allow_duplicates_(allow_duplicates) {}
  19. /// Set the epoch for the current enumeration. This can be used to alter the
  20. /// sample selection and shuffling behavior.
  21. void set_epoch(size_t epoch) {
  22. epoch_ = epoch;
  23. }
  24. size_t epoch() const {
  25. return epoch_;
  26. }
  27. protected:
  28. size_t local_sample_count() {
  29. if (allow_duplicates_) {
  30. return (size_ + num_replicas_ - 1) / num_replicas_;
  31. } else {
  32. return size_ / num_replicas_;
  33. }
  34. }
  35. size_t size_;
  36. size_t num_replicas_;
  37. size_t rank_;
  38. size_t epoch_;
  39. bool allow_duplicates_;
  40. };
  41. /// Select samples randomly. The sampling order is shuffled at each `reset()`
  42. /// call.
  43. class TORCH_API DistributedRandomSampler : public DistributedSampler<> {
  44. public:
  45. DistributedRandomSampler(
  46. size_t size,
  47. size_t num_replicas = 1,
  48. size_t rank = 0,
  49. bool allow_duplicates = true);
  50. /// Resets the `DistributedRandomSampler` to a new set of indices.
  51. void reset(optional<size_t> new_size = nullopt) override;
  52. /// Returns the next batch of indices.
  53. optional<std::vector<size_t>> next(size_t batch_size) override;
  54. /// Serializes the `DistributedRandomSampler` to the `archive`.
  55. void save(serialize::OutputArchive& archive) const override;
  56. /// Deserializes the `DistributedRandomSampler` from the `archive`.
  57. void load(serialize::InputArchive& archive) override;
  58. /// Returns the current index of the `DistributedRandomSampler`.
  59. size_t index() const noexcept;
  60. private:
  61. void populate_indices();
  62. size_t begin_index_;
  63. size_t end_index_;
  64. size_t sample_index_;
  65. std::vector<size_t> all_indices_;
  66. };
  67. /// Select samples sequentially.
  68. class TORCH_API DistributedSequentialSampler : public DistributedSampler<> {
  69. public:
  70. DistributedSequentialSampler(
  71. size_t size,
  72. size_t num_replicas = 1,
  73. size_t rank = 0,
  74. bool allow_duplicates = true);
  75. /// Resets the `DistributedSequentialSampler` to a new set of indices.
  76. void reset(optional<size_t> new_size = nullopt) override;
  77. /// Returns the next batch of indices.
  78. optional<std::vector<size_t>> next(size_t batch_size) override;
  79. /// Serializes the `DistributedSequentialSampler` to the `archive`.
  80. void save(serialize::OutputArchive& archive) const override;
  81. /// Deserializes the `DistributedSequentialSampler` from the `archive`.
  82. void load(serialize::InputArchive& archive) override;
  83. /// Returns the current index of the `DistributedSequentialSampler`.
  84. size_t index() const noexcept;
  85. private:
  86. void populate_indices();
  87. size_t begin_index_;
  88. size_t end_index_;
  89. size_t sample_index_;
  90. std::vector<size_t> all_indices_;
  91. };

3.4.2 实现

类的具体实现位于:torch\csrc\api\src\data\samplers\distributed.cpp

3.4.2.1 DistributedRandomSampler

我们首先看看DistributedRandomSampler。

其作用就是依据本worker 的 rank_获取打乱的index。我们按照逻辑顺序讲解各个函数。

  • 初始化时候会调用 reset(size_) 进行 shuffle。
  • reset 函数作用是让sampler指向一组新的indices:
    • 首先调用 populate_indices() 设置对应本rank的起始index,终止index。
    • populate_indices 函数之中,会对数据index 进行设置,即配置了 all_indices_,也同时配置了本rank的起始index,终止index。
    • 然后对 all_indices_ 进行shuffle。
  • next 函数就相对简单了,因为主要工作被reset做了,所以此时数据已经被随机打乱了,所以找到起始位置,返回数据中对行数即可。

因为下面用到了 iota 函数,可能有的同学不熟悉,这里说明下iota的作用:

  1. std::vector<int> test;
  2. test.resize(10);
  3. std::iota(test.begin(), test.end(), 5);// 将从 5 开始的 10 次递增值赋值给 test
  4. //test结果:5 6 7 8 9 10 11 12 13 14

具体代码如下:

  1. DistributedRandomSampler::DistributedRandomSampler(
  2. size_t size,
  3. size_t num_replicas,
  4. size_t rank,
  5. bool allow_duplicates)
  6. : DistributedSampler(size, num_replicas, rank, allow_duplicates),
  7. begin_index_(0),
  8. end_index_(0),
  9. sample_index_(0) {
  10. // shuffle first time.
  11. reset(size_);
  12. }
  13. // 每次加载新epoch时候,都要调用reset
  14. void DistributedRandomSampler::reset(optional<size_t> new_size) {
  15. size_ = new_size.value_or(size_);
  16. populate_indices();
  17. std::mt19937 rand(epoch_);
  18. // 对于数据进行shuffle
  19. std::shuffle(all_indices_.begin(), all_indices_.end(), rand);
  20. sample_index_ = begin_index_;
  21. }
  22. void DistributedRandomSampler::populate_indices() {
  23. size_t num_local_samples = local_sample_count();
  24. // 得到样本数量
  25. size_t sample_count =
  26. num_replicas_ == 1 ? size_ : num_local_samples * num_replicas_;
  27. all_indices_.resize(sample_count);
  28. // std::iota 的作用是用顺序递增的值赋值指定范围内的元素
  29. // 这里是给all_indices_设置从0开始到sample_count这些数值
  30. std::iota(std::begin(all_indices_), std::end(all_indices_), 0);
  31. // 如果sample count大于size_,则需要给多出来的那些index再赋一些数值
  32. for (size_t i = size_; i < sample_count; ++i) {
  33. // we may have added duplicate samples to make all
  34. // replicas to have the same number of samples.
  35. all_indices_[i] = i - size_;
  36. }
  37. begin_index_ = rank_ * num_local_samples; // 对应本rank的起始index
  38. end_index_ = begin_index_ + num_local_samples; // 对应本rank的终止index
  39. sample_index_ = begin_index_;
  40. }
  41. size_t DistributedRandomSampler::index() const noexcept {
  42. return sample_index_;
  43. }
  44. // 注意,每次加载新epoch时候,都要调用reset,因此对于next函数来说,工作已经很小
  45. optional<std::vector<size_t>> DistributedRandomSampler::next(
  46. size_t batch_size) {
  47. if (sample_index_ == end_index_) { // 已经提取完数据
  48. return nullopt;
  49. }
  50. size_t end = sample_index_ + batch_size; // 本次迭代的终止位置
  51. if (end > end_index_) {
  52. end = end_index_;
  53. }
  54. auto iter = all_indices_.begin(); // 因为此时数据已经被随机打乱了,找到起始位置即可
  55. std::vector<size_t> res(iter + sample_index_, iter + end); // 从所有数据中提取前面若干行
  56. sample_index_ = end;
  57. return res;
  58. }
3.4.2.2 DistributedSequentialSampler

然后看看 DistributedSequentialSampler。

其作用就是依据本worker 的 rank_获取顺序的index。我们按照逻辑顺序讲解各个函数。

  • reset 函数就简单多了,使用populate_indices按照顺序设置index即可。
  • next 函数就相对复杂,不但要顺序返回index,还需要设置下次的起始位置。
  1. DistributedSequentialSampler::DistributedSequentialSampler(
  2. size_t size,
  3. size_t num_replicas,
  4. size_t rank,
  5. bool allow_duplicates)
  6. : DistributedSampler(size, num_replicas, rank, allow_duplicates),
  7. begin_index_(0),
  8. end_index_(0),
  9. sample_index_(0) {
  10. populate_indices(); // 这里会设定本rank对应的起始位置
  11. }
  12. void DistributedSequentialSampler::reset(optional<size_t> new_size) {
  13. size_t size = new_size.value_or(size_);
  14. if (size != size_) {
  15. size_ = size;
  16. populate_indices();
  17. } else {
  18. sample_index_ = begin_index_;
  19. }
  20. }
  21. void DistributedSequentialSampler::populate_indices() {
  22. begin_index_ = rank_ * local_sample_count(); // 本rank对应的起始位置
  23. end_index_ = begin_index_ + local_sample_count();
  24. sample_index_ = begin_index_;
  25. }
  26. size_t DistributedSequentialSampler::index() const noexcept {
  27. return sample_index_;
  28. }
  29. optional<std::vector<size_t>> DistributedSequentialSampler::next(
  30. size_t batch_size) {
  31. if (sample_index_ == end_index_) { // 已经循环结束
  32. return nullopt;
  33. }
  34. size_t end = sample_index_ + batch_size; // 本次的终止行
  35. if (end > end_index_) {
  36. end = end_index_;
  37. }
  38. std::vector<size_t> res(end - sample_index_); // 返回的vector大小
  39. // 给res设置从sample_index_开始递增(end - sample_index_)这么大的这些数值,这就是顺序返回了index
  40. std::iota(std::begin(res), std::end(res), sample_index_);
  41. if (end >= size_) {
  42. for (size_t& index : res) { //遍历 vector,得到本次的index
  43. index = index % size_;
  44. }
  45. }
  46. sample_index_ = end; // 设置下次开始行
  47. return res;
  48. }

0xFF 参考

卷积神经网络的并行化模型--One weird trick for parallelizing convolutional neural networks

AI框架中数据处理的挑战与解决思路

PyTorch 源码解读之 torch.utils.data:解析数据处理全流程

谈谈你对大规模机器学习这个领域的理解和认识?

Nvidia-DALI 从放弃到入门

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

[源码解析] PyTorch 分布式(1) --- 数据加载之DistributedSampler的更多相关文章

  1. [源码解析] PyTorch 分布式(2) --- 数据加载之DataLoader

    [源码解析] PyTorch 分布式(2) --- 数据加载之DataLoader 目录 [源码解析] PyTorch 分布式(2) --- 数据加载之DataLoader 0x00 摘要 0x01 ...

  2. [源码解析] PyTorch分布式优化器(2)----数据并行优化器

    [源码解析] PyTorch分布式优化器(2)----数据并行优化器 目录 [源码解析] PyTorch分布式优化器(2)----数据并行优化器 0x00 摘要 0x01 前文回顾 0x02 DP 之 ...

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

    [源码解析] PyTorch 分布式(1)------历史和概述 目录 [源码解析] PyTorch 分布式(1)------历史和概述 0x00 摘要 0x01 PyTorch分布式的历史 1.1 ...

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

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

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

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

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

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

  7. [源码解析] PyTorch 分布式 Autograd (3) ---- 上下文相关

    [源码解析] PyTorch 分布式 Autograd (3) ---- 上下文相关 0x00 摘要 我们已经知道 dist.autograd 如何发送和接受消息,本文再来看看如何其他支撑部分,就是如 ...

  8. [源码解析] PyTorch分布式优化器(1)----基石篇

    [源码解析] PyTorch分布式优化器(1)----基石篇 目录 [源码解析] PyTorch分布式优化器(1)----基石篇 0x00 摘要 0x01 从问题出发 1.1 示例 1.2 问题点 0 ...

  9. [源码解析] PyTorch 分布式(15) --- 使用分布式 RPC 框架实现参数服务器

    [源码解析] PyTorch 分布式(15) --- 使用分布式 RPC 框架实现参数服务器 目录 [源码解析] PyTorch 分布式(15) --- 使用分布式 RPC 框架实现参数服务器 0x0 ...

随机推荐

  1. 『心善渊』Selenium3.0基础 — 19、使用Selenium操作文件的上传和下载

    目录 1.Selenium实现文件上传 (1)页面中的文件上传说明 (2)文件上传示例 (3)总结 2.Selenium实现文件下载 (1)Firefox浏览器文件下载 1)操作步骤: 2)文件下载示 ...

  2. C. Learning Languages 求联通块的个数

    C. Learning Languages 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring&g ...

  3. Redis启动正常,一段时间后报错,连不上redis

    Redis报错 1.redis在最终目标上移动临时数据库文件时出错 错误:redis:Error moving temp DB file temp-13792.rdb on the final des ...

  4. SpringCloud:feign对象传参和普通传参及遇到的坑

    对象传参: #使用@RequestBody来指定传参对象 @RequestMapping(value = "/v2/matterCode/genCode", method = Re ...

  5. 用swoole实现异步任务队列

    应用场景如下: 假如要发100封邮件,for循环100遍,这种方法显然是不可取的. 在一些比较繁杂的业务里,我们很可能有超过1万的邮件要群发.那我们怎么处理这个延迟的问题? 答案就是用异步.把&quo ...

  6. 《PHP安全编程系列》系列分享专栏

    PHP安全编程系列收藏夹收藏了有关PHP安全编程方面的知识,对PHP安全编程提供学习参考 <PHP安全编程系列>已整理成PDF文档,点击可直接下载至本地查阅https://www.webf ...

  7. Java初级面试题整理

    先看再点赞,给自己一点思考的时间,如果对自己有帮助,微信搜索[程序职场]关注这个执着的职场程序员. 我有什么:职场规划指导,技能提升方法,讲不完的职场故事,个人成长经验. 1. Java语言有哪些特点 ...

  8. 「CF526F」 Pudding Monsters

    CF526F Pudding Monsters 传送门 模型转换:对于一个 \(n\times n\) 的棋盘,若每行每列仅有一个棋子,令 \(a_x=y\),则 \(a\) 为一个排列. 转换成排列 ...

  9. DHCP与配置命令

    1. DHCP简介 2. DHCP主要用途 3. 使用DHCP的好处 4.DHCP经典应用模式 5.DHCP交互过程 DHCP的IP地址自动获取工作原理 6.DHCP中继    应用场景   工作原理 ...

  10. C语言:指针

    #include <stdio.h> #include <stdlib.h> int sum(int a,int b) { int c; c=a+b; printf(" ...