Training Execution
This document introduces how to launch model training scripts based on training resource configurations.
Single-Node Single-Device Scenario
This section introduces the configuration and startup method of single-device training scripts.
Environment Preparation
- See CANN Quick Installation to install the Ascend NPU driver and CANN software (including Toolkit, ops, and NNAL packages), and configure environment variables; see TorchNPU Installation to install the PyTorch framework, TorchNPU, and the APEX module (optional).
- Prepare the model environment based on actual requirements, such as conda, Docker, and third-party library dependencies.
Model Script Configuration
-
GPU to NPU
Typically, the model source code supports single-node single-device training on GPU. You can map the model source code to NPU by following the guidance in Model Migration to complete the model script configuration. The following example uses a simple custom model, with annotations for NPU adaptation.
import argparse import torch import torch_npu import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from torchvision import datasets, transforms class ToyModel(nn.Module): def __init__(self): super(ToyModel, self).__init__() self.net1 = nn.Linear(10, 10) self.relu = nn.ReLU() self.net2 = nn.Linear(10, 10) def forward(self, x): return self.net2(self.relu(self.net1(x))) def parse_args(): parser = argparse.ArgumentParser(description="command line arguments") parser.add_argument('--batch_size', type=int, default=64) parser.add_argument('--epochs', type=int, default=10) parser.add_argument('--learning_rate', type=float, default=0.0001) return parser.parse_args() def data_process(inputs, labels): inputs = inputs.view(inputs.size(0), -1)[:, :10] return inputs, labels def main(): # Get passed arguments args = parse_args() transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)) ]) train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) # Load dataset train_loader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True) # Transfer model to NPU device = torch.device("npu") model = ToyModel().to(device) # Define loss function criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=args.learning_rate) step = 0 for epoch in range(args.epochs): model.train() for inputs, labels in train_loader: # Data preprocessing: convert dataset data to required shape inputs, labels = data_process(inputs, labels) # Transfer data to NPU for processing inputs, labels = inputs.to(device), labels.to(device) optimizer.zero_grad() outputs = model(inputs) # Transfer loss to NPU for processing loss = criterion(outputs, labels).to(device) loss.backward() optimizer.step() # Add print for each step. You can modify it as needed print(f"step == {step}") step += 1 if __name__ == "__main__": main() -
CPU to NPU
If the model source code only uses CPU programming and does not support single-node single-device training on GPU, use the following command to place data and models on NPU for training.
import torch import torch_npu import torch.nn as nn device = torch.device("npu") # Load data to NPU for data in dataloader: if torch.npu.is_available(): data = data.to(device) # Load model to NPU model = Model() if torch.npu.is_available(): model = model.to(device) # Load loss function to NPU loss_fn = nn.CrossEntropyLoss() if torch.npu.is_available(): loss_fn = loss_fn.to(device)
Starting Training
Execute the following command to start single-node training. The following parameters are for reference only, and you can modify them according to actual conditions.
-
GPU to NPU
python3 main.py \ # main.py is the example name for the model script configuration above; you can define it as needed --learning_rate 0.0001 \ # learning rate --batch_size 1 \ # training batch size --epochs 1 # training epochs -
CPU to NPU
python3 main.py \ # main.py is the example name for the model script configuration above; you can define it as needed --batch_size 128 \ # training batch size --data_path /home/data/resnet50/imagenet \ # dataset path --lr 0.1 \ # learning rate --epochs 90 \ # training epochs --arch resnet50 \ # model architecture --world_size 1 \ # number of NPUs --rank 0 \ # local node ID --workers 40 \ # number of data loading processes --momentum 0.9 \ # momentum --weight_decay 1e-4 \ # weight decay --gpu 0 # device ID. The parameter name here remains gpu, but after migration is completed, the actual training device has been defined as npu in the code
Single-Node Multi-Device Scenario
This section describes how to start single-node multi-device distributed training.
Environment Preparation
-
See CANN Quick Installation to install the Ascend NPU driver and CANN software (including Toolkit, ops, and NNAL packages), and configure environment variables; see TorchNPU Installation to install the PyTorch framework, TorchNPU, and the APEX module (optional).
-
Prepare the model environment based on actual requirements, such as conda, docker, and third-party library dependencies.
Caution
In distributed training scenarios, HCCL uses some ports of the host server for cluster information collection, and the operating system needs to reserve these ports. Ports 60000-60015 are recommended. You can also specify the starting port of the host NIC through the environment variable
HCCL_IF_BASE_PORT. In this scenario, you need to reserve 16 ports starting from the specified port.-
If port reservation only needs to take effect temporarily, execute the following command. Configurations applied temporarily will become invalid after a restart.
sysctl -w net.ipv4.ip_local_reserved_ports=60000-60015 -
If port reservation needs to take effect permanently, perform the following operations:
-
Log in to the server as the root user and edit the
/etc/sysctl.conffile.vim /etc/sysctl.conf -
Add
net.ipv4.ip_local_reserved_ports=60000-60015to the end of the/etc/sysctl.conffile, save the file, and exit. -
Execute the following command to make the configuration take effect.
sysctl -p
-
-
Model Script Configuration
This section describes the core steps for changing a single-node single-device training script into a single-node multi-device training script.
-
Add the following code to the main function.
-
Add distributed logic, that is, obtain the
world_sizeandlocal_rankparameters from environment variables.world_size = int(os.environ["WORLD_SIZE"]) local_rank = int(os.environ["LOCAL_RANK"]) -
Use
local_rankto automatically obtain the device ID.device = torch.device(f'npu:{local_rank}') -
Initialize and set the communication method to
hccl.torch.distributed.init_process_group(backend="hccl", rank=local_rank, world_size=world_size)
-
-
After defining the model, enable DDP mode.
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank], output_device=local_rank) -
After obtaining the training dataset, set
train_sampler.train_sampler = torch.utils.data.distributed.DistributedSampler(train_data) -
Assign
train_samplerto the sampler inDataLoader.train_dataloader = DataLoader(dataset = train_data, batch_size=batch_size, sampler = train_sampler)
Starting Training
There are five script startup methods to start multi-device training:
- Shell script method
- mp.spawn method
- torch.distributed.launch method
- torchrun method
- torch_npu_run method (recommended for cluster scenarios): This method is an improved version of torchrun for large-scale cluster scenarios, enhancing cluster connection establishment performance.
Examples of Launching Multi-Device Training Scripts demonstrates the modification methods for the script code of each startup method and the adaptation methods for various startup methods, which you can refer to for learning.
Note
Collective communication has the following constraints:
- The computational graphs executed on different devices in data parallel mode are the same.
- For Atlas A2 training products/Atlas A3 training products: AllReduce and reduce_scatter only support int8, int32, float16, float32, and bfloat16 data types.
- For Atlas A2 training products/Atlas A3 training products, if you intend to perform 2-device training, rewrite the 8-device training script into a 2-device training script. Refer to the following modification methods:
- If the
batch_sizeof the eight-device script is eight times thebatch_sizeof the single-device script, divide both thebatch_sizeandlearning_ratefor eight-device training by 4 to obtain thebatch_sizeandlearning_ratefor two-device training. - Change
nproc_per_nodeto2.
- If the
- One device corresponds to one training process. Currently, multiple processes training on the same device is not supported.
Single-Node Multi-Device Training Example
Take the torchrun startup method as an example. A simple custom model is used to demonstrate sample model code and a startup script for single-node eight-device training.
-
The following example uses a simple custom model to describe script configuration. Pay attention to the annotations for NPU adaptation.
import argparse import os from datetime import timedelta import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim # Import the DDP module for distributed data parallelism from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import DataLoader # Import the DistributedSampler module for distributed training data sampling from torch.utils.data.distributed import DistributedSampler import torch_npu from torchvision import datasets, transforms DATA_DIR = "./data" def cleanup(): # Destroy the process group dist.destroy_process_group() class ToyModel(nn.Module): def __init__(self): super(ToyModel, self).__init__() self.layer1 = nn.Linear(784, 128) self.relu = nn.ReLU() self.layer2 = nn.Linear(128, 10) def forward(self, x): return self.layer2(self.relu(self.layer1(x))) def data_process(inputs, labels): inputs = inputs.view(-1, 784) labels = labels.view(-1) return inputs, labels def get_train_args(): parser = argparse.ArgumentParser(description="command line arguments") parser.add_argument("--batch_size", type=int, default=64) parser.add_argument("--epochs", type=int, default=1) parser.add_argument("--learning_rate", type=float, default=0.0001) args = parser.parse_args() return args def train(args): # When single-node multi-device training is started in torchrun mode, obtain the total number of NPU devices participating in training (world_size) and the NPU device index of the current process (local_rank_idx) through environment variables world_size = int(os.environ["WORLD_SIZE"]) local_rank_idx = int(os.environ["LOCAL_RANK"]) devices_per_node = torch.npu.device_count() # Initialize the process group and set the communication method to hccl dist.init_process_group("hccl", rank=local_rank_idx, world_size=world_size, timeout=timedelta(minutes=30)) # Set the NPU device index for the current process torch_npu.npu.set_device(local_rank_idx) # Transfer the model to the corresponding NPU device device_id = f"npu:{local_rank_idx}" model = ToyModel().to(device_id) transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)) ]) # Prepare the distributed sampler and dataloader for the dataset train_dataset = datasets.MNIST(root=DATA_DIR, train=True, download=True, transform=transform) train_sampler = DistributedSampler(train_dataset, num_replicas=devices_per_node, rank=local_rank_idx) train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=train_sampler) # Transfer the cross-entropy loss function to the corresponding NPU device criterion = nn.CrossEntropyLoss().to(device_id) optimizer = optim.Adam(model.parameters(), lr=args.learning_rate) # Wrap the model for distributed data parallel training model = DDP(model) for epoch in range(args.epochs): if local_rank_idx == 0: print(f"\nCurrent epoch: {epoch}") train_sampler.set_epoch(epoch) model.train() for i, (inputs, labels) in enumerate(train_dataloader): inputs, labels = data_process(inputs, labels) # Transfer data to the corresponding NPU device inputs, labels = inputs.to(device_id), labels.to(device_id) outputs = model(inputs) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() if local_rank_idx == 0: print(f"Current step: {i}, loss: {loss.item()}") cleanup() def main(): args = get_train_args() train(args) if __name__ == "__main__": main() -
Start training by running the startup script with
bash.-
Create a new startup script file, for example
train_8p_torchrun.py, and place the sample code in 1 into it. -
Execute the following command via
bashto start the script.torchrun --nnodes=1 --nproc_per_node=8 --master_addr localhost --master_port 12345 train_8p_torchrun.py
-
Multi-Node Multi-Device Scenario
This section describes how to start multi-node multi-device training.
Environment Preparation
In a cluster environment, each single node in the cluster must be deployed according to Environment Preparation to ensure that each single node can run normally.
In addition, perform the following operations for cluster setup.
Caution
-
In distributed training scenarios, HCCL uses some ports of the host server for cluster information collection, and the operating system needs to reserve these ports. Ports 60000-60015 are recommended. You can also specify the starting port of the host NIC through the environment variable
HCCL_IF_BASE_PORT. In this scenario, you need to reserve 16 ports starting from the specified port. For training on a physical machine, you need to configure the following commands on the physical machine; for training in a container, you need to configure the following commands in the container.-
If port reservation only needs to take effect temporarily, run the following command. Configurations applied temporarily will become invalid after a restart.
sysctl -w net.ipv4.ip_local_reserved_ports=60000-60015 -
If port reservation needs to take effect permanently, perform the following operations:
-
Log in to the server as the root user and edit the
/etc/sysctl.conffile.vim /etc/sysctl.conf -
Add
net.ipv4.ip_local_reserved_ports=60000-60015to the end of the/etc/sysctl.conffile, save the file, and exit. -
Run the following command to make the configuration take effect.
sysctl -p
-
-
-
Collective communication only supports allocation at 1/2/4/8P granularity.
-
The following operations, except for model modification, only need to be configured and executed once.
-
Set up the networking (two-server eight-device as an example).
Set up the computing networking through switches or direct optical port connection.
-
Configure the device IP.
-
Configure the device IP on AI Server0. The following IPs are examples.
hccn_tool -i 0 -ip -s address 10.***.***.2 netmask 255.255.255.0 hccn_tool -i 1 -ip -s address 10.***.***.3 netmask 255.255.255.0 hccn_tool -i 2 -ip -s address 10.***.***.4 netmask 255.255.255.0 hccn_tool -i 3 -ip -s address 10.***.***.5 netmask 255.255.255.0 hccn_tool -i 4 -ip -s address 10.***.***.6 netmask 255.255.255.0 hccn_tool -i 5 -ip -s address 10.***.***.7 netmask 255.255.255.0 hccn_tool -i 6 -ip -s address 10.***.***.8 netmask 255.255.255.0 hccn_tool -i 7 -ip -s address 10.***.***.9 netmask 255.255.255.0 -
Configure the device IP on AI Server1. The following IPs are examples.
hccn_tool -i 0 -ip -s address 10.***.***.2 netmask 255.255.255.0 hccn_tool -i 1 -ip -s address 10.***.***.3 netmask 255.255.255.0 hccn_tool -i 2 -ip -s address 10.***.***.4 netmask 255.255.255.0 hccn_tool -i 3 -ip -s address 10.***.***.5 netmask 255.255.255.0 hccn_tool -i 4 -ip -s address 10.***.***.6 netmask 255.255.255.0 hccn_tool -i 5 -ip -s address 10.***.***.7 netmask 255.255.255.0 hccn_tool -i 6 -ip -s address 10.***.***.8 netmask 255.255.255.0 hccn_tool -i 7 -ip -s address 10.***.***.9 netmask 255.255.255.0Note
The following rules must be observed when configuring device IPs:
- For Atlas A2 training products/Atlas A3 training products, only the NPUs of multiple nodes need to be on the same network segment.
- Each IP must be unique. IPs on the same network segment must be differentiated by the last 8 bits.
-
Use hccn_tool to configure the IP of the network detection target, performing the configuration eight times from device0 to device7.
hccn_tool -i 0 -netdetect -s address xx.xx.xx.xxTable 1 Parameter description
Parameter Description -i Device ID. Value range: 0 to 7. -s address IP address of the NPU network detection target, used to check the network connection status of the NPU NIC. This IP must be able to communicate with the NPU NIC IP address. It is usually configured as the gateway address on the same network segment as the NPU NIC IP address. The training node periodically checks whether the communication between the NPU NIC and the gateway address is normal. -
Run the following command to check the network health status and ensure that all devices between the two servers are connected.
for i in {0..7}; do hccn_tool -i $i -net_health -g; doneCommand output:
net health status: SuccessTable 2 Command output description
Field Description net health status Network health status. Status information: 0: Success; 1: Socket fail; 2: Receive timeout; 3: Unreachable; 4: Time exceeded; 5: Fault; 6: Init; 7: Thread error; 8: Detect ip set; Others: Unknown. -
Use hccn_tool to verify whether the device IP is configured correctly.
-
Query the IP of each device.
hccn_tool -i 0 -ip -g -
Print the query result.
ipaddr:10.***.***.2 netmask:255.255.***.0If the above output is returned, it indicates that the connection is established.
-
-
-
Disable the firewall.
-
Debian system
ufw disable -
openEuler system
systemctl stop firewalld
-
-
Confirm that the switch status is normal.
Run the following command. If the return value is not empty, the status is normal.
for i in {0..7}; do hccn_tool -i $i -lldp -g; done -
Modify the model by referring to the multi-node multi-device training example and upload the model script to any path on AI Server0 and AI Server1.
-
The number of concurrent connections allowed by the primary node is limited by the Linux kernel parameters
somaxconnandtcp_max_syn_backlog. For large-scale cluster setups, if the values ofsomaxconnandtcp_max_syn_backlogare too small, some clients may exit abnormally in advance, causing cluster initialization to fail.In large-scale cluster scenarios, it is recommended that you adjust the values of the
somaxconnandtcp_max_syn_backlogparameters appropriately based on the cluster size. For example:sysctl -w net.core.somaxconn=65535 sysctl -w net.ipv4.tcp_max_syn_backlog=65535Note
For training in a physical machine scenario, the above commands must be configured on the physical machine; For training in a container scenario, they must be configured within the container.
-
Start multi-node multi-device training. Note the following key points:
- Specify the total number of participating compute nodes (
--nnodes). - Specify the current node rank (
--node_rank). - Specify the number of NPU devices participating in computation within a node (
--nproc_per_node). - Specify the IP address of the primary node (
--master_addr) and the port number of the primary node (--master_port).
- Specify the total number of participating compute nodes (
-
View the host logs.
All host logs are uniformly saved in the
~/ascend/logpath. You can view the device logs of each host in this path.
Model Script Configuration
This section introduces the core steps for changing single-device training script into a multi-device training script.
-
Add the following code in the main function.
-
Add distributed logic, that is, obtain the
local_rankparameter from environment variables.local_rank = int(os.environ.get("LOCAL_RANK", 0)) -
Use
local_rankto automatically obtain the device ID.device = torch.device(f'npu:{local_rank}') -
Initialize and set the communication method to
hccl.torch.distributed.init_process_group(backend="hccl",rank=(args.node_rank)*(args.nproc_per_node) + local_rank)
-
-
After defining the model, enable DDP mode.
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank], output_device=local_rank) -
After obtaining the training dataset, set
train_sampler.train_sampler = torch.utils.data.distributed.DistributedSampler(train_data) -
Assign
train_samplerto the sampler inDataLoader.train_dataloader = DataLoader(dataset = train_data, batch_size=batch_size, sampler = train_sampler)
Starting Training
Five startup methods are provided to start multi-device training:
- Shell script method
- mp.spawn method
- torch.distributed.launch method
- torchrun method
- torch_npu_run method (recommended for cluster scenarios): This method is an improved version of torchrun for large cluster scenarios, enhancing cluster connection establishment performance.
Examples of Starting Multi-Device Training Scripts demonstrates the modification methods for each startup method's script code and the adaptation methods for various startup methods.
Note
- Collective communication has the following constraints:
- In data parallel mode, the computational graphs executed on different devices are the same.
- For Atlas A2 training products/Atlas A3 training products: AllReduce and reduce_scatter only support int8, int32, float16, float32, and bfloat16 data types.
- For Atlas A2 training products/Atlas A3 training products, in a server cluster scenario (i.e., a training server cluster consisting of a cluster management node and a group of training servers), the number of NPUs participating in collective communication must be (1~8)*n (where n is the number of servers participating in training, with an upper limit of 1152). When n is a power of 2, the cluster performance is optimal. It is recommended that you prioritize this method for cluster networking. It is also recommended that the number of NPUs participating in collective communication in each server be kept consistent; otherwise, performance degradation will occur.
- For Atlas A2 training products/Atlas A3 training products, if you intend to perform two-device training, rewrite the eight-device training script into a two-device training script. Refer to the following modification methods:
- If the
batch_sizeof the eight-device script is eight times thebatch_sizeof the single-device script, divide both thebatch_sizeandlearning_rateduring eight-device training by 4 to obtain thebatch_sizeandlearning_ratefor two-device training. - Change
nproc_per_nodeto2.
- If the
- One device corresponds to one training process. Currently, multiple processes training on the same device are not supported.
Multi-Node Multi-Device Training Example
Taking the torchrun startup mode as an example, this section demonstrates the model code and startup script examples for multi-node multi-device using a simple custom model.
-
The following example uses a simple custom model to describe script configuration. Pay attention to the annotations for NPU adaptation.
import argparse import os from datetime import timedelta import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim # Import the DDP module for distributed data parallelism from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import DataLoader # Import the DistributedSampler module for distributed training data sampling from torch.utils.data.distributed import DistributedSampler import torch_npu from torchvision import datasets, transforms DATA_DIR = "./data" def cleanup(): # Destroy the process group dist.destroy_process_group() class ToyModel(nn.Module): def __init__(self): super(ToyModel, self).__init__() self.layer1 = nn.Linear(784, 128) self.relu = nn.ReLU() self.layer2 = nn.Linear(128, 10) def forward(self, x): return self.layer2(self.relu(self.layer1(x))) def data_process(inputs, labels): inputs = inputs.view(-1, 784) labels = labels.view(-1) return inputs, labels def get_train_args(): parser = argparse.ArgumentParser(description="command line arguments") parser.add_argument("--batch_size", type=int, default=64) parser.add_argument("--epochs", type=int, default=1) parser.add_argument("--learning_rate", type=float, default=0.0001) args = parser.parse_args() return args def train(args): # When multi-node multi-device training is started in torchrun mode, obtain the total number of NPUs participating in training (world_size), the global index of the NPU where the current process resides (global_rank_idx), and the local index of the NPU where the current process resides (local_rank_idx) through environment variables world_size = int(os.environ["WORLD_SIZE"]) global_rank_idx = int(os.environ["RANK"]) local_rank_idx = int(os.environ["LOCAL_RANK"]) # Initialize the process group and set the communication method to hccl dist.init_process_group("hccl", rank=global_rank_idx, world_size=world_size, timeout=timedelta(minutes=30)) # Set the index of the NPU where the current process resides torch_npu.npu.set_device(local_rank_idx) # Transfer the model to the corresponding NPU device device_id = f"npu:{local_rank_idx}" model = ToyModel().to(device_id) transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)) ]) # Prepare the distributed sampler and dataloader for the dataset train_dataset = datasets.MNIST(root=DATA_DIR, train=True, download=True, transform=transform) train_sampler = DistributedSampler(train_dataset, num_replicas=world_size, rank=global_rank_idx) train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=train_sampler) # Transfer the cross-entropy loss function to the corresponding NPU device criterion = nn.CrossEntropyLoss().to(device_id) optimizer = optim.Adam(model.parameters(), lr=args.learning_rate) # Wrap the model into a distributed data parallel training state model = DDP(model) for epoch in range(args.epochs): if local_rank_idx == 0: print(f"\nCurrent epoch: {epoch}") train_sampler.set_epoch(epoch) model.train() for i, (inputs, labels) in enumerate(train_dataloader): inputs, labels = data_process(inputs, labels) # Transfer the data to the corresponding NPU device inputs, labels = inputs.to(device_id), labels.to(device_id) outputs = model(inputs) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() if local_rank_idx == 0: print(f"Current step: {i}, loss: {loss.item()}") cleanup() def main(): args = get_train_args() train(args) if __name__ == "__main__": main() -
Configure the training script, and launch it via
bash. The script needs to be executed on each node in sequence.-
Create a new startup script file, for example
train_16p_torchrun.py, and place the sample code from 1 into it. -
Execute the following command via
bashon the primary node, where--master_addrspecifies the IP address of the primary node:torchrun --nnodes 2 --node_rank 0 --nproc_per_node 8 --master_addr xxxx --master_port 12345 train_16p_torchrun.py -
Execute the following command via
bashon the secondary node, where--master_addrspecifies the IP address of the primary node:torchrun --nnodes 2 --node_rank 1 --nproc_per_node 8 --master_addr xxxx --master_port 12345 train_16p_torchrun.py
-