MindCluster cluster scheduling components provide the diagnosis function for performance degradation (slow nodes) in a cluster based on the profiling capability provided by MindStudio. This function provides the capability of dynamic dotting and data persistence, allowing dotting to be enabled or disabled in real time without requiring job restart for diagnosis, ensuring uninterrupted training.
Table 1 describes the supported dotting data.
Dotting Data Type |
Supported Framework |
Required Component |
|---|---|---|
FP (forward propagation data) |
PyTorch NOTE:
Only the single-operator scenario is supported. |
mstx_torch_plugin |
Step (step latency) |
PyTorch, MindSpore |
|
Communication (communication operator) |
PyTorch, MindSpore |
|
SaveCheckpoint (time consumed by SaveCheckpoint) |
PyTorch, MindSpore |
|
DataLoader (time consumed by DataLoader) |
PyTorch, MindSpore |
|
Package |
Required (Yes/No) |
Description |
How to Obtain |
Scenario |
|---|---|---|---|---|
mstx_torch_plugin |
No |
The collection and parsing of msproftx data function in Ascend PyTorch Profiler includes built-in dotting of communication operators. To capture time consumption data of more key phases without modifying the service code, mstx_torch_plugin adds dotting of the dataloader, forward, step, and save_checkpoint functions to Ascend PyTorch Profiler. NOTE:
|
Click here. |
PyTorch |
This solution applies only to TaskD 7.1.RC1 or later. If you use TaskD with a version earlier than 7.1.RC1, see Using TaskD of Other Versions.
pip install mstx_torch_plugin-1.0-py3-none-any.whl
Ensure that it is imported after torch and torch_npu are imported.
import torch import torch_npu import mstx_torch_plugin
def train(forward_step_func, model, optimizer, opt_param_scheduler,
train_data_iterator, valid_data_iterator,
process_non_loss_data_func, config):
# Cache into one-logger for callback
…
…
if is_profile_enabled():
prof = get_profiler()
prof.start()
step_id = iteration
while iteration < args.train_iters:
stream = torch.npu.current_stream() # Obtain the environment's execution stream to capture the time consumed by NPUs.
range_id = torch.npu.mstx.range_start(f"step {step_id}", stream) # Start of a training step.
…
…
if args.manual_gc:
if args.manual_gc_interval != 0 and iteration % args.manual_gc_interval == 0:
gc.collect()
if is_profile_enabled():
prof.step()
step_id +=1 # Increase the training step by 1 to identify the next step.
torch.npu.mstx.range_end(range_id) # End of a training step.
source /usr/local/Ascend/cann/set_env.sh
export LD_PRELOAD=/usr/local/Ascend/cann/lib64/libmspti.so:/usr/local/python3.10.5/lib/python3.10/site-packages/taskd/python/cython_api/libs/libtaskd.so
You can run the following command to query the path where TaskD is located. The Location field in the command output is the target path.
pip show taskd
from taskd.api import init_taskd_manager, start_taskd_manager
import os
job_id=os.getenv("MINDX_TASK_ID")
node_nums=XX # Total number of nodes (set by yourself)
proc_per_node=XX # Number of training processes on each node (set by yourself)
init_taskd_manager({"job_id":job_id, "node_nums": node_nums, "proc_per_node": proc_per_node})
start_taskd_manager()
For details about the parameters in the manager.py file, see def init_taskd_manager(config:dict) -> bool:.
sed -i '/import os/i import taskd.python.adaptor.patch' $(pip3 show torch | grep Location | awk -F ' ' '{print $2}')/torch/distributed/run.py
if [[ "${RANK}" -eq 0 ]]; then
export MASTER_ADDR=${POD_IP}
python manager.py &
fi
torchrun ...
from taskd.api import init_taskd_manager, start_taskd_manager
import os
job_id=os.getenv("MINDX_TASK_ID")
node_nums=XX # Total number of nodes (set by yourself)
proc_per_node=XX # Number of training processes on each node (set by yourself)
init_taskd_manager({"job_id":job_id, "node_nums": node_nums, "proc_per_node": proc_per_node})
start_taskd_manager()
For details about the parameters in the manager.py file, see def init_taskd_manager(config:dict) -> bool:.
if [[ "${MS_SCHED_HOST}" -eq "${POD_IP}" ]]; then
python manager.py &
fi
msrun ...
...
if ("TTP:1" in tft_env) or ("UCE:1" in tft_env) or ("ARF:1" in tft_env):
try:
from taskd.python.framework.agent.ms_mgr.msrun_plugin import MSRunPlugin
from taskd .api.taskd_proxy_api import init_taskd_proxy
from taskd.python.framework.common.type import CONFIG_UPSTREAMIP_KEY, LOCAL_HOST
import threading
proxy = threading.Thread(target=init_taskd_proxy, args=({CONFIG_UPSTREAMIP_KEY : os.getenv("MS_SCHED_HOST", LOCAL_HOST)},))
proxy.daemon = True
proxy.start()
self.msmgr = MSRunPlugin()
self.msmgr.register_callbacks("KILL_WORKER", self.kill_workers)
self.msmgr.register_callbacks("START_ALL_WORKER", self.start_all_workers)
self.msmgr.register_callbacks("START_WORKER_LIST", self.start_worker_list)
self.msmgr.register_callbacks("MONITOR", self.monitor_rank_status)
self.enable_mindx = True
os.environ["MS_ENABLE_RECOVERY"] = str(1)
...
def pretrain(train_valid_test_dataset_provider,
model_provider,
model_type,
forward_step_func,
process_non_loss_data_func=None,
extra_args_provider=None,
args_defaults={}):
print_rank_0('time to initialize megatron (seconds): {:.3f}'.format(
time.time() - _TRAIN_START_TIME))
print_datetime('after megatron is initialized')
import torch.distributed as dist
if dist.is_initialized():
rank = dist.get_rank()
from taskd.api.taskd_worker_api import init_taskd_worker
from taskd.api.taskd_worker_api import start_taskd_worker
init_taskd_worker(rank,5000)
start_taskd_worker()
app_metrics['app_model_init_finish_time'] = one_logger_utils.get_timestamp_in_ms()
one_logger_utils.on_pretrain_start()
def training_process(
self,
config: Optional[Union[dict, MindFormerConfig, ConfigArguments, TrainingArguments]] = None,
network: Optional[Union[Cell, PreTrainedModel]] = None,
dataset: Optional[Union[BaseDataset, GeneratorDataset]] = None,
optimizer: Optional[Optimizer] = None,
callbacks: Optional[Union[Callback, List[Callback]]] = None,
compute_metrics: Optional[Union[dict, set]] = None,
**kwargs):
…
…
logger.info(".........Starting Training Model..........")
if get_real_rank() % 8 == 0:
pprint(config)
logger.info(".........Model Compiling, Please Wait a Moment...........")
try:
rank = get_rank()
from taskd.api.taskd_worker_api import init_taskd_worker
from taskd.api.taskd_worker_api import start_taskd_worker
init_taskd_worker(rank,5000)
start_taskd_worker()
except Exception as e:
print("failed to call mindcluster taskd")
model.train(config.runner_config.epochs, dataset,
callbacks=callbacks,
dataset_sink_mode=config.runner_config.sink_mode,
sink_size=config.runner_config.sink_size,
initial_epoch=config.runner_config.initial_epoch)
In the preceding code, 5000 in init_taskd_worker(rank,5000) indicates the upper limit of the value of /user/cluster-info/profiling. For details, see upper_limit_of_disk_in_mb in def init_taskd_worker(rank_id: int, upper_limit_of_disk_in_mb: int = 5000, framework: str = "pt") -> bool.
...
spec:
...
containers:
...
ports:
- containerPort: 9601
name: taskd-port
...
volumeMounts: - name: profilingdata mountPath: /user/cluster-info/ - name: profileswitch mountPath: /user/cluster-info/datatrace-config
volumes:
- name: profileswitch
hostPath:
path: /user/cluster-info/datatrace-config/default.data-trace-default-test-pytorch-fault-mixtral
- name: profilingdata
hostPath:
path: /home/profilingdatapath
If lightweight profiling is enabled to obtain flushed data through the gRPC interface provided by ClusterD, the lifecycle of the created data-trace-<Job name> ConfigMap is deleted with the job. If the job does not exist, the interface fails to be called.
kubectl get cm
apiVersion: v1
kind: ConfigMap
metadata:
name: data-trace-default-test-pytorch-fault-mixtral # The name of cm must be constructed by prefixing it with data-trace and appending the job name.
labels:
reset: "true"
data:
profilingSwitch: '{"CommunicationOperator":"off","Step":"on","SaveCheckpoint":"on","FP":"on","DataLoader":"on"}'
kubectl apply -f datacm.yaml
If the following information is displayed, the ConfigMap is created successfully.
[root@master~]# kubectl apply -f datacm.yaml configmap/data-trace-default-test-pytorch-fault-mixtral created
kubectl edit cm data-trace-default-test-pytorch-fault-mixtral
apiVersion: v1
data:
profilingSwitch: '{"CommunicationOperator":"on","Step":"on","SaveCheckpoint":"on","FP":"on","DataLoader":"on"}'
Enabling communication operators may deteriorate training performance. Therefore, you are advised not to enable them.