PyNorch/norch/csrc/distributed.cpp

67 lines
1.5 KiB
C++
Raw Permalink Normal View History

2024-05-24 18:19:39 -03:00
#include <nccl.h>
2024-05-24 15:12:53 -03:00
#include <stdio.h>
#include <stdlib.h>
#include "distributed.h"
2024-05-24 18:19:39 -03:00
#include "cuda.h"
2024-05-24 15:12:53 -03:00
#include <mpi.h>
2024-05-24 18:19:39 -03:00
#include <nccl.h>
int rank;
int world_size;
ncclComm_t nccl_comm;
2024-05-24 15:12:53 -03:00
extern "C" {
2024-05-24 18:19:39 -03:00
void init_process_group(int env_rank, int env_world_size) {
rank = env_rank;
world_size = env_world_size;
// init MPI
MPI_CHECK(MPI_Init(NULL, NULL));
ncclUniqueId nccl_id;
if (rank == 0) {
ncclGetUniqueId(&nccl_id);
}
// send nccl unique id to all processes
MPI_CHECK(MPI_Bcast((void *)&nccl_id, sizeof(nccl_id), MPI_BYTE, 0, MPI_COMM_WORLD));
2024-05-31 19:40:58 -03:00
cudaSetDevice(rank);
2024-05-24 18:19:39 -03:00
// init NCCL communication group
NCCL_CHECK(ncclCommInitRank(&nccl_comm, world_size, nccl_id, rank));
2024-05-24 15:12:53 -03:00
}
void broadcast_tensor(Tensor* tensor, int src) {
2024-05-24 18:19:39 -03:00
cudaStream_t stream;
cudaStreamCreate(&stream);
NCCL_CHECK(ncclBroadcast(tensor->data, tensor->data, tensor->size * sizeof(float), ncclFloat, src, nccl_comm, stream));
2024-05-24 18:19:39 -03:00
cudaStreamSynchronize(stream);
cudaStreamDestroy(stream);
}
2024-05-24 18:31:59 -03:00
void allreduce_sum_tensor(Tensor* tensor) {
2024-05-24 18:19:39 -03:00
cudaStream_t stream;
cudaStreamCreate(&stream);
// Perform NCCL AllReduce operation to calculate the sum of all tensors across all processes
NCCL_CHECK(ncclAllReduce(tensor->data, tensor->data, tensor->size, ncclFloat, ncclSum, nccl_comm, stream));
cudaStreamSynchronize(stream);
cudaStreamDestroy(stream);
}
void end_process_group() {
MPI_CHECK(MPI_Finalize());
NCCL_CHECK(ncclCommDestroy(nccl_comm));
}
}