Untitled

Anonymous
Plain Text
09/18/2025 9:47 PM
3.5 KB
21
Indexable
Never
# master.py
# master.py
import os
import time
import torch
import torch.distributed as dist

# -------------- 配置(直接在这里修改) ----------------
MASTER_ADDR = "x3014c0s31b1n0"   # <- 把这里改成 master 自己可达的 IP(worker 可访问)
MASTER_PORT = 12355
WORLD_SIZE = 2
RANK = 0
ITERS = 20
CUDA_DEVICE = 0  # 使用 local cuda:0
# -----------------------------------------------------

def now():
    return f"{time.time():.6f}"

def main():
    device = torch.device(f"cuda:{CUDA_DEVICE}")
    torch.cuda.set_device(device)

    # 设置网络接口环境变量,适配 Polaris
    os.environ['GLOO_SOCKET_IFNAME'] = 'hsn0'  # Polaris 的高速网络接口
    os.environ['TP_SOCKET_IFNAME'] = 'hsn0'
    
    init_method = f"tcp://{MASTER_ADDR}:{MASTER_PORT}"
    # 使用 gloo backend 进行跨节点通信,避免 NCCL 跨节点问题
    try:
        dist.init_process_group(backend="gloo", init_method=init_method, rank=RANK, world_size=WORLD_SIZE, timeout=torch.distributed.constants.default_pg_timeout)
        print(f"[{now()}] master successfully initialized distributed group")
    except Exception as e:
        print(f"[{now()}] master failed to initialize distributed group: {e}")
        raise
    print(f"[{now()}] master init done rank={dist.get_rank()} world_size={dist.get_world_size()}")

    # 明确创建 group,仅包含 rank 0 与 1
    master_worker_group = dist.new_group(ranks=[0, 1])
    print(f"[{now()}] master created group: {master_worker_group}")

    N = 4
    D0 = 5120
    D1 = 5160
    dtype = torch.bfloat16  # 若环境不支持 bfloat16,请改为 torch.float16
    
    print(f"[{now()}] master tensor config: N={N}, D0={D0}, D1={D1}, dtype={dtype}")
    print(f"[{now()}] master broadcast shape: ({N}, {D0}), gather shape: ({N}, {D1})")

    for it in range(ITERS):
        # optional: broadcast an iter id scalar first to avoid shape mismatch issues
        iter_id = torch.tensor([it], dtype=torch.int64, device=device)
        print(f"[{now()}] master before broadcast(iter_id) it={it}")
        dist.broadcast(iter_id, src=0, group=master_worker_group)
        print(f"[{now()}] master after broadcast(iter_id) it={it} got iter_id={int(iter_id.item())}")

        time.sleep(1)

        # master 构造要广播的 tensor
        q = torch.randn((N, D0), device=device, dtype=dtype) + float(it)
        print(f"[{now()}] master before broadcast tensor it={it} q.shape={tuple(q.shape)} dtype={q.dtype}")
        dist.broadcast(q, src=0, group=master_worker_group)  # blocking on group
        print(f"[{now()}] master after broadcast tensor it={it}")

        # 准备 gather_list(长度等于 world_size)
        reply = torch.randn((N, D1), device=device, dtype=dtype) + float(it) + float(RANK)
        gather_list = [torch.empty_like(reply, device=device) for _ in range(WORLD_SIZE)]
        print(f"[{now()}] master before gather it={it} reply.shape={tuple(reply.shape)} gather_list_len={len(gather_list)}")
        for i, tensor in enumerate(gather_list):
            print(f"[{now()}] master gather_list[{i}].shape={tuple(tensor.shape)}")
        dist.gather(reply, gather_list=gather_list, dst=0, group=master_worker_group)
        print(f"[{now()}] master after gather it={it}")

        if WORLD_SIZE > 1:
            from_worker = gather_list[1]
            print(f"[{now()}] master received from worker it={it} sum={float(from_worker.float().sum()):.6f}")

    dist.destroy_process_group()
    print(f"[{now()}] master finished.")

if __name__ == "__main__":
    main()
Editor is loading...
Leave a Comment