Here is a pytorch geometric code that crashes when used with torchrun --nproc-per-node=2 torchrun.py import os
import time
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler
from edges import *
from regressors import *
from training import *
from mlflow_utils import *
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts
from torch_geometric.data import Batch
if multigpu:
torch.cuda.set_device(device)
dist.init_process_group(backend="nccl", init_method="env://")
if rank == 0:
print(f"[DDP] Initialized process {rank} of {world_size}", flush=True)
if rank == 0:
mlflow.start_run(run_name="all-6")
# === Dataset Processing ===
train_set, test_set = process_and_combine_cached_datasets(
configs, root="data", upcast=True, compressed=True
)
if multigpu:
dist.barrier()
set_deterministic(42)
# === Data Loaders ===
if multigpu:
train_sampler = DistributedSampler(train_set, num_replicas=world_size, rank=rank, shuffle=True, seed=42)
train_loader = DataLoader(train_set, batch_size=size, sampler=train_sampler, num_workers=workers, pin_memory=True)
else:
train_loader = DataLoader(train_set, batch_size=size, shuffle=True, num_workers=workers, pin_memory=True)
test_loader = DataLoader(test_set, batch_size=size, num_workers=workers, pin_memory=True)
# === Model ===
model = TransformerRegressor(
hidden_dim=12, edge_dim=1, pooling='set2set', mlp_factor=4,
dropout=0.0, num_layers=6, heads=6, use_embeddings=True
).to(device)
if multigpu:
model = DDP(model, device_ids=[local_rank])
optimizer = torch.optim.AdamW(
model.parameters(),
lr=2e-4,
weight_decay=0.001,
betas=(0.9, 0.999),
eps=1e-8,
fused=True
)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer, mode='min', factor=0.5, patience=8, min_lr=1e-6,
)
if rank == 0:
describe_model(model)
log_full_experiment_config(model=model, optimizer=optimizer, scheduler=scheduler)
best_val_loss = float('inf')
save_path = "best_model.pt"
start_epoch = 1
loss_type = 'mse'
for epoch in range(start_epoch, 401):
if multigpu:
train_sampler.set_epoch(epoch)
start_wall = time.time()
start_cpu = time.process_time()
train_loss = train(model, train_loader, optimizer, loss_fn, loss_type=loss_type)
if rank == 0 and mlflow.active_run():
mlflow.log_metric("train_loss_mse", train_loss, step=epoch)
val_loss, loss_table = evaluate_and_log_per_size(
model, test_loader, epoch=epoch, overall_loss_type=loss_type
)
if epoch == 150:
for param_group in optimizer.param_groups:
param_group['lr'] = 5e-5
scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=60, T_mult=1, eta_min=2e-6)
elif epoch == 210:
scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=80, T_mult=1, eta_min=2e-6)
scheduler.step(val_loss if isinstance(scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau) else None)
wall_time = time.time() - start_wall
cpu_time = time.process_time() - start_cpu
current_lr = optimizer.param_groups[0]['lr']
if rank == 0:
print(f"Epoch {epoch:03d}: Train Loss = {train_loss:.6e}, Val Loss = {val_loss:.6e}, "
f"LR = {current_lr:.6f} Wall Time: {wall_time:.2f} s CPU Time: {cpu_time:.2f} s", flush=True)
if val_loss < best_val_loss:
best_val_loss = val_loss
if rank == 0:
torch.save(
model.module.state_dict() if multigpu else model.state_dict(),
save_path
)
save_predictions(model, test_loader, filepath="results_best.txt")
plot_loss_per_size(epoch)
print(f"Saved new best model at epoch {epoch} with val loss {val_loss:.6e}", flush=True)
if rank == 0:
torch.save({
'epoch': epoch,
'model_state_dict': model.module.state_dict() if multigpu else model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'val_loss': best_val_loss,
}, 'checkpoint.pt')
if rank == 0:
model.load_state_dict(torch.load(save_path, map_location=device))
model.eval()
save_predictions(model, test_loader, filepath="results_best.txt")
if multigpu:
dist.destroy_process_group()
if name == "main":
main(). Here is the full error: torchrun --nproc-per-node=2 torchrun.py
W0710 22:56:50.140000 13375 site-packages/torch/distributed/run.py:766]
W0710 22:56:50.140000 13375 site-packages/torch/distributed/run.py:766] *****************************************
W0710 22:56:50.140000 13375 site-packages/torch/distributed/run.py:766] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed.
W0710 22:56:50.140000 13375 site-packages/torch/distributed/run.py:766] *****************************************
[DDP] Initialized process 0 of 2
[LOAD] C52-100 train: data/processed/C52-100_train_77e2e446_flat.pt.zst
[LOAD] C52-100 train: data/processed/C52-100_train_77e2e446_flat.pt.zst
[LOAD] C52-100 test: data/processed/C52-100_test_a7940bfb_flat.pt.zst
[LOAD] C52-100 test: data/processed/C52-100_test_a7940bfb_flat.pt.zst
/venv/main/lib/python3.12/site-packages/torch/distributed/distributed_c10d.py:4631: UserWarning: No device id is provided via init_process_group or barrier . Using the current device set by the user.
warnings.warn( # warn only once
[rank1]:[W710 22:57:23.126778537 ProcessGroupNCCL.cpp:4718] [PG ID 0 PG GUID 0 Rank 1] using GPU 1 as device used by this process is currently unknown. This can potentially cause a hang if this rank to GPU mapping is incorrect. You can pecify device_id in init_process_group() to force use of a particular device.
/venv/main/lib/python3.12/site-packages/torch/distributed/distributed_c10d.py:4631: UserWarning: No device id is provided via init_process_group or barrier . Using the current device set by the user.
warnings.warn( # warn only once
[rank0]:[W710 22:57:24.064157983 ProcessGroupNCCL.cpp:4718] [PG ID 0 PG GUID 0 Rank 0] using GPU 0 as device used by this process is currently unknown. This can potentially cause a hang if this rank to GPU mapping is incorrect. You can pecify device_id in init_process_group() to force use of a particular device.
W0710 22:57:26.523000 13375 site-packages/torch/distributed/elastic/multiprocessing/api.py:900] Sending process 13441 closing signal SIGTERM
E0710 22:57:27.190000 13375 site-packages/torch/distributed/elastic/multiprocessing/api.py:874] failed (exitcode: -11) local_rank: 0 (pid: 13440) of binary: /venv/main/bin/python3
Traceback (most recent call last):
File "/venv/main/bin/torchrun", line 10, in
sys.exit(main())
^^^^^^
File "/venv/main/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/init.py", line 355, in wrapper
return f(*args, **kwargs)
^^^^^^^^^^^^^^^^^^
File "/venv/main/lib/python3.12/site-packages/torch/distributed/run.py", line 892, in main
run(args)
File "/venv/main/lib/python3.12/site-packages/torch/distributed/run.py", line 883, in run
elastic_launch(
File "/venv/main/lib/python3.12/site-packages/torch/distributed/launcher/api.py", line 139, in call
return launch_agent(self._config, self._entrypoint, list(args))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/main/lib/python3.12/site-packages/torch/distributed/launcher/api.py", line 270, in launch_agent
raise ChildFailedError(
torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
torchrun.py FAILED
Failures:
<NO_OTHER_FAILURES>
Root Cause (first observed failure):
[0]:
time : 2025-07-10_22:57:26
host : c3644b06480a
rank : 0 (local_rank: 0)
exitcode : -11 (pid: 13440)
error_file: <N/A>
traceback : Signal 11 (SIGSEGV) received by PID 13440
Help me finding the problem
Assistant
The crash you're experiencing with a segmentation fault (SIGSEGV, exit code -11) when running your PyTorch Geometric code with torchrun --nproc-per-node=2 is likely due to an issue with the NCCL backend initialization in the distributed process group. This is indicated by the warnings in the error log:
The UserWarning from torch/distributed/distributed_c10d.py states: "No device id is provided via init_process_group or barrier. Using the current device set by the user."
The NCCL warnings (e.g., "[PG ID 0 PG GUID 0 Rank 1] using GPU 1 as device used by this process is currently unknown") suggest that NCCL is unable to correctly identify the GPU device assigned to each process, which can lead to hangs, deadlocks, or segmentation faults.
Root Cause Analysis
Based on the error log and your code, the problem stems from how the distributed process group is initialized. Specifically:
In your main function, you call dist.init_process_group(backend="nccl", init_method="env://") without specifying the device_id. While torch.cuda.set_device(device) is called earlier to set the CUDA device for the process, this is not always sufficient for NCCL to correctly map processes to GPUs in a distributed setting.
NCCL (NVIDIA Collective Communications Library) requires explicit device ID information to avoid mismatches between processes and GPUs. When device_id is not provided, NCCL may default to an incorrect or unknown device, leading to invalid memory access or synchronization issues, which can manifest as a segmentation fault.
The crash occurs shortly after process group initialization (around the time of the NCCL warnings), before the training loop starts, indicating that the issue is related to the setup phase rather than the model or data loading itself.
Other potential contributing factors include:
Concurrent dataset loading: Both processes load the same dataset files (e.g., C52-100_train_77e2e446_flat.pt.zst) before the dist.barrier(). While this is generally fine for read-only files, it could exacerbate synchronization issues if there's any shared state or if the loading process is not perfectly thread-safe.
Environment setup: If your CUDA or NCCL versions are incompatible, or if the GPUs are not properly configured (e.g., not visible via nvidia-smi), this could contribute to the problem. However, the primary warning points to the device ID issue.
Distributed setup: Using torchrun should handle environment variables correctly, but explicitly specifying device_id in is a best practice for NCCL backend to avoid such warnings and potential crashes.
To fix the issue, modify the dist.init_process_group call to explicitly specify the device_id using the local_rank variable. This ensures that NCCL knows which GPU to use for each process, reducing the risk of hangs or segmentation faults.
Here's the updated code snippet for the relevant part:
python
if multigpu:
torch.cuda.set_device(device) # Keep this, as it sets the current CUDA device
dist.init_process_group(backend="nccl", init_method="env://", device_id=local_rank) # Add device_id=local_rank
if rank == 0:
print(f"[DDP] Initialized process {rank} of {world_size}", flush=True)
Full updated main function for clarity:
python
def main():
local_rank = int(os.environ["LOCAL_RANK"])
rank = int(os.environ["RANK"])
world_size = int(os.environ["WORLD_SIZE"])
device = torch.device(f"cuda:{local_rank}" if torch.cuda.is_available() else "cpu")
if multigpu:
torch.cuda.set_device(device) # Set the CUDA device explicitly
dist.init_process_group(backend="nccl", init_method="env://", device_id=local_rank) # Specify device_id
if rank == 0:
print(f"[DDP] Initialized process {rank} of {world_size}", flush=True)
if rank == 0:
mlflow.start_run(run_name="all-6")
# === Dataset Processing ===
train_set, test_set = process_and_combine_cached_datasets(
configs, root="data", upcast=True, compressed=True
)
if multigpu:
dist.barrier() # Ensure all processes have loaded data before proceeding
set_deterministic(42)
# === Data Loaders ===
if multigpu:
train_sampler = DistributedSampler(train_set, num_replicas=world_size, rank=rank, shuffle=True, seed=42)
train_loader = DataLoader(train_set, batch_size=size, sampler=train_sampler, num_workers=workers, pin_memory=True)
else:
train_loader = DataLoader(train_set, batch_size=size, shuffle=True, num_workers=workers, pin_memory=True)
test_loader = DataLoader(test_set, batch_size=size, num_workers=workers, pin_memory=True)
# === Model ===
model = TransformerRegressor(
hidden_dim=12, edge_dim=1, pooling='set2set', mlp_factor=4,
dropout=0.0, num_layers=6, heads=6, use_embeddings=True
).to(device)
if multigpu:
model = DDP(model, device_ids=[local_rank]) # Ensure device_ids is specified for DDP
optimizer = torch.optim.AdamW(
model.parameters(),
lr=2e-4,
weight_decay=0.001,
betas=(0.9, 0.999),
eps=1e-8,
fused=True
)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer, mode='min', factor=0.5, patience=8, min_lr=1e-6,
)
if rank == 0:
describe_model(model)
log_full_experiment_config(model=model, optimizer=optimizer, scheduler=scheduler)
best_val_loss = float('inf')
save_path = "best_model.pt"
start_epoch = 1
loss_type = 'mse'
for epoch in range(start_epoch, 401):
if multigpu:
train_sampler.set_epoch(epoch)
start_wall = time.time()
start_cpu = time.process_time()
train_loss = train(model, train_loader, optimizer, loss_fn, loss_type=loss_type)
if rank == 0 and mlflow.active_run():
mlflow.log_metric("train_loss_mse", train_loss, step=epoch)
val_loss, loss_table = evaluate_and_log_per_size(
model, test_loader, epoch=epoch, overall_loss_type=loss_type
)
if epoch == 150:
for param_group in optimizer.param_groups:
param_group['lr'] = 5e-5
scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=60, T_mult=1, eta_min=2e-6)
elif epoch == 210:
scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=80, T_mult=1, eta_min=2e-6)
scheduler.step(val_loss if isinstance(scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau) else None)
wall_time = time.time() - start_wall
cpu_time = time.process_time() - start_cpu
current_lr = optimizer.param_groups[0]['lr']
if rank == 0:
print(f"Epoch {epoch:03d}: Train Loss = {train_loss:.6e}, Val Loss = {val_loss:.6e}, "
f"LR = {current_lr:.6f} Wall Time: {wall_time:.2f} s CPU Time: {cpu_time:.2f} s", flush=True)
if val_loss < best_val_loss:
best_val_loss = val_loss
if rank == 0:
torch.save(
model.module.state_dict() if multigpu else model.state_dict(),
save_path
)
save_predictions(model, test_loader, filepath="results_best.txt")
plot_loss_per_size(epoch)
print(f"Saved new best model at epoch {epoch} with val loss {val_loss:.6e}", flush=True)
if rank == 0:
torch.save({
'epoch': epoch,
'model_state_dict': model.module.state_dict() if multigpu else model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'val_loss': best_val_loss,
}, 'checkpoint.pt')
if rank == 0:
model.load_state_dict(torch.load(save_path, map_location=device))
model.eval()
save_predictions(model, test_loader, filepath="results_best.txt")
if multigpu:
dist.destroy_process_group()
Why This Should Fix the Issue
Explicit Device ID Specification: By adding device_id=local_rank to init_process_group, you're telling NCCL exactly which GPU to use for each process. This should eliminate the "device used by this process is currently unknown" warning and prevent NCCL from making incorrect assumptions.
DDP Wrapper Update: In the DDP wrapping, you already specify device_ids=[local_rank], which is good. The change to init_process_group should align with this.
Barrier for Synchronization: The existing dist.barrier() after dataset loading helps ensure all processes are synchronized, which is a good practice. Keep it as is.
Additional Recommendations
Test the Fix: After making this change, run your script again with torchrun --nproc-per-node=2 torchrun.py and check if the NCCL warnings disappear and the crash is resolved.
Check GPU Environment:
Run nvidia-smi to ensure both GPUs are visible and not overcommitted.
Verify CUDA and NCCL versions for compatibility. For example:
Use nvcc --version to check CUDA version.
Use nccl-tests or similar tools to test NCCL setup.
Ensure PyTorch is built with the correct CUDA version (e.g., pip install torch --extra-index-url https://download.pytorch.org/whl/cu118 for CUDA 11.8).
Dataset Loading Optimization:
If dataset loading is slow or causing issues, consider moving it inside a synchronized block or using a custom dataset class that handles distributed loading more efficiently. However, with num_workers=0, this is less likely to be the root cause.
Error Handling and Debugging:
Add more print statements or logging after key steps (e.g., after init_process_group and dist.barrier()) to pinpoint where the crash occurs.
Run with a single process (torchrun --nproc-per-node=1) to isolate if the issue is specific to multi-GPU setup.
If the crash persists, enable more verbose logging for NCCL by setting the environment variable NCCL_DEBUG=INFO or NCCL_DEBUG=DEBUG when running torchrun.
Best Practices for Distributed Training:
Always specify device_id in init_process_group for NCCL backend when using torchrun or similar launchers.
Consider using torch.distributed.launch instead of torchrun if you're on an older PyTorch version, but torchrun is generally fine.
If you're using PyTorch Geometric, ensure that your data (e.g., graphs) is properly batched and doesn't contain any shared tensors that could cause memory issues in distributed mode.
This fix should resolve the segmentation fault by addressing the device mapping issue. If you encounter further errors, provide additional logs or details about your environment (e.g., PyTorch version, CUDA version, GPU hardware) for more targeted debugging.