Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
mindspeed_llm · 8 changed files
Base commit: 72c49a6260c73669678b8f39b1ba41a4789bb555
diff --git a/megatron/core/distributed/distributed_data_parallel.py b/megatron/core/distributed/distributed_data_parallel.pyindex 63ae456146996ad9a41497841b4dd901d9bcd181..b4c94dba54f180956b845899047aa0c25cc87ecf 100644--- a/megatron/core/distributed/distributed_data_parallel.py+++ b/megatron/core/distributed/distributed_data_parallel.py@@ -32,7 +32,8 @@ class DistributedDataParallel(_BaseDataParallel): module: Underlying model. disable_bucketing: If true, force assign all parameters to a single bucket. If false, use standard bucketing policy: assign parameters to smaller buckets and all-reduce- per bucket _if_ overlap_grad_reduce is True and pp_rank is 0.+ per bucket when overlap_grad_reduce is True. Later pipeline stages also+ retain buckets when overlap_param_gather is enabled. """ @@ -68,12 +69,17 @@ class DistributedDataParallel(_BaseDataParallel): f'Setting up DistributedDataParallel with config {self.ddp_config}', ) - # Turn off bucketing if we are on a pipeline stage that is not the first (since- # data-parallel communication on these stages is not on the critical path), or if- # disable_bucketing is True (e.g., we might not want to break up model parameters- # into buckets for model chunks after the first in the interleaved schedule).+ # Later pipeline stages can use a single bucket when parameter gathering+ # is synchronous. With overlapped parameter gathering, however, a single+ # bucket makes the first layer wait for the whole stage's parameters and+ # prevents prefetching subsequent layers. Retain bucketing on these stages+ # too; an explicit disable_bucketing (e.g. for later interleaved chunks)+ # still takes precedence. self.bucket_size = self.ddp_config.bucket_size- if parallel_state.get_pipeline_model_parallel_rank() > 0:+ if (+ parallel_state.get_pipeline_model_parallel_rank() > 0+ and not self.ddp_config.overlap_param_gather+ ): self.bucket_size = None if disable_bucketing: self.bucket_size = Nonediff --git a/megatron/core/distributed/finalize_model_grads.py b/megatron/core/distributed/finalize_model_grads.pyindex 9a28b07887c3f3e4f71198d8e3ed87b64adeb0c5..31120a735b37c4855dd3ccdd5495087322de5016 100644--- a/megatron/core/distributed/finalize_model_grads.py+++ b/megatron/core/distributed/finalize_model_grads.py@@ -116,6 +116,38 @@ def _allreduce_conditional_embedding_grads(model: List[torch.nn.Module], config: grad.copy_(grads[0]) +def _shared_embedding_grad_for_reduction(grad, weight, ddp_model):+ """Select the optimizer-owned part of an isolated shared embedding bucket."""+ ddp_config = ddp_model.ddp_config+ if (+ not ddp_config.use_distributed_optimizer+ or ddp_config.use_custom_fsdp+ or ddp_config.num_distributed_optimizer_instances != 1+ or not getattr(weight, 'shared_embedding', False)+ ):+ return grad++ bucket_group = getattr(ddp_model, 'param_to_bucket_group', {}).get(weight)+ if bucket_group is None:+ return grad+ bucket = bucket_group.param_to_bucket[weight]+ if (+ len(bucket.params) != 1+ or bucket.grad_data.numel() != grad.numel()+ or not grad.is_contiguous()+ or bucket.grad_data.data_ptr() != grad.data_ptr()+ ):+ return grad++ # DDP gives shared embeddings their own bucket so that the first and last+ # pipeline stages shard them identically. DP reduce-scatter has completed+ # before this call; only this rank's shard is consumed by the optimizer.+ # The other shards contain unreduced partial gradients and need no PP sync.+ shard_size = bucket.grad_data.numel() // bucket_group.intra_distributed_optimizer_instance_size+ start = shard_size * bucket_group.intra_distributed_optimizer_instance_rank+ return bucket.grad_data.narrow(0, start, shard_size)++ def _allreduce_word_embedding_grads(model: List[torch.nn.Module], config: TransformerConfig): """ All-reduce word embedding grads.@@ -135,6 +167,7 @@ def _allreduce_word_embedding_grads(model: List[torch.nn.Module], config: Transf else: # We do not support an interleaved schedule for models with encoders yet. model_module = model[0] + ddp_model = model_module ddp_config = model_module.ddp_config model_module = get_attr_wrapped_model(model_module, 'pre_process', return_model_obj=True) @@ -147,7 +180,8 @@ def _allreduce_word_embedding_grads(model: List[torch.nn.Module], config: Transf grad_attr = _get_main_grad_attr(weight, ddp_config.use_custom_fsdp) orig_grad = getattr(weight, grad_attr) grad = _unshard_if_dtensor(orig_grad)- torch.distributed.all_reduce(grad, group=parallel_state.get_embedding_group())+ grad_to_reduce = _shared_embedding_grad_for_reduction(grad, weight, ddp_model)+ torch.distributed.all_reduce(grad_to_reduce, group=parallel_state.get_embedding_group()) setattr(weight, grad_attr, _reshard_if_dtensor(grad, orig_grad)) diff --git a/mindspeed_llm/__init__.py b/mindspeed_llm/__init__.pyindex 7de8d340c493b265b21ff5fd44f8789d3dce38cb..a7deaf26e428ae13411a181b968a09024d328e6e 100644--- a/mindspeed_llm/__init__.py+++ b/mindspeed_llm/__init__.py@@ -13,7 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. import os+import sys+++def _is_training_supervisor():+ # Python imports the parent package before executing a module with -m.+ # The foreground supervisor only starts torchrun workers: applying model+ # patches here would import the entire training stack twice and would let+ # the adapter consume the supervisor's --help argument. Workers execute+ # pretrain_gpt.py and retain the usual eager adaptation below.+ command = getattr(sys, "orig_argv", ())+ return any(+ option == "-m" and module == "mindspeed_llm.training.qwen3_8b_4dev"+ for option, module in zip(command, command[1:])+ )+ backend = os.environ.get("TRAINING_BACKEND", "mcore").lower()-if backend == "mcore":+if backend == "mcore" and not _is_training_supervisor(): from mindspeed_llm.tasks import megatron_adaptor_v2 as megatron_adaptordiff --git a/mindspeed_llm/core/distributed/finalize_model_grads.py b/mindspeed_llm/core/distributed/finalize_model_grads.pyindex 87fd158146262d92f5abf7c714f5c5387cb83b58..d741de9d26b0e50e1b3ad682dd5a0ef08fcd12e8 100644--- a/mindspeed_llm/core/distributed/finalize_model_grads.py+++ b/mindspeed_llm/core/distributed/finalize_model_grads.py@@ -9,7 +9,11 @@ from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from megatron.core import parallel_state from megatron.core.transformer.transformer_config import TransformerConfig from megatron.core.utils import get_attr_wrapped_model-from megatron.core.distributed.finalize_model_grads import _reshard_if_dtensor, _unshard_if_dtensor+from megatron.core.distributed.finalize_model_grads import (+ _reshard_if_dtensor,+ _shared_embedding_grad_for_reduction,+ _unshard_if_dtensor,+) from megatron.training import get_args from mindspeed.core.tensor_parallel.tp_2d.group_api_2d import TPXCollectiveComm from mindspeed.core.optimizer.low_precision import finalize_model_grads as quant_finalize@@ -89,6 +93,7 @@ def _allreduce_word_embedding_grads(model: List[torch.nn.Module], config: Transf else: # We do not support an interleaved schedule for models with encoders yet. model_module = model[0] + ddp_model = model_module ddp_config = model_module.ddp_config model_module = get_attr_wrapped_model(model_module, 'pre_process', return_model_obj=True) @@ -111,5 +116,8 @@ def _allreduce_word_embedding_grads(model: List[torch.nn.Module], config: Transf if adjust_fn is not None: adjust_fn(grad, parallel_state.get_embedding_group()) - torch.distributed.all_reduce(grad, group=parallel_state.get_embedding_group())+ grad_to_reduce = grad+ if not args.use_quant_optimizer:+ grad_to_reduce = _shared_embedding_grad_for_reduction(grad, weight, ddp_model)+ torch.distributed.all_reduce(grad_to_reduce, group=parallel_state.get_embedding_group()) setattr(weight, grad_attr, _reshard_if_dtensor(grad, orig_grad))diff --git a/mindspeed_llm/core/tensor_parallel/cross_entropy.py b/mindspeed_llm/core/tensor_parallel/cross_entropy.pyindex 793efb05c23735e9225588da659cbc2f1e8bc13f..0188e40ab1d0c4dd6819f8336e36e85bf81128ba 100644--- a/mindspeed_llm/core/tensor_parallel/cross_entropy.py+++ b/mindspeed_llm/core/tensor_parallel/cross_entropy.py@@ -1,8 +1,45 @@+from functools import wraps from typing import Tuple import torch +def vocab_parallel_cross_entropy_wrapper(fn):+ """Fuse local-vocabulary cross entropy without changing FP32 loss arithmetic.++ With one tensor-parallel rank the entire vocabulary is local. The NPU+ cross-entropy operator can then combine log-softmax, target selection and+ their gradients, avoiding the separate full-vocabulary elementwise passes.+ Keep Megatron's implementation for partitioned vocabularies and smoothing+ (whose convention differs from the native operator's convention).+ """+ import torch_npu+ from megatron.core.parallel_state import get_tensor_model_parallel_world_size++ fused_cross_entropy = getattr(torch_npu, "npu_cross_entropy_loss", None)++ @wraps(fn)+ def wrapper(vocab_parallel_logits, target, label_smoothing=0.0):+ if (+ fused_cross_entropy is not None+ and vocab_parallel_logits.device.type == "npu"+ and get_tensor_model_parallel_world_size() == 1+ and label_smoothing == 0.0+ and target.dtype == torch.int64+ and vocab_parallel_logits.numel() > 0+ # The native operator accepts at most 200,000 token rows.+ and target.numel() <= 200000+ ):+ # Both the loss and saved log probabilities must remain FP32,+ # including when the model produces BF16/FP16 logits.+ logits = vocab_parallel_logits.reshape(-1, vocab_parallel_logits.size(-1)).float()+ loss = fused_cross_entropy(logits, target.reshape(-1), reduction="none")[0]+ return loss.reshape_as(target)+ return fn(vocab_parallel_logits, target, label_smoothing)++ return wrapper++ def calculate_logits_max( vocab_parallel_logits: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor]:diff --git a/mindspeed_llm/features_manager/affinity/affinity.py b/mindspeed_llm/features_manager/affinity/affinity.pyindex 339f55d1d6ea8b4aa617444b60c21b2e90b442c8..03a4bcee938dd5fa6a0cebb0d1ffe21738be583b 100644--- a/mindspeed_llm/features_manager/affinity/affinity.py+++ b/mindspeed_llm/features_manager/affinity/affinity.py@@ -1,13 +1,18 @@-# Copyright (c) 2025, Huawei Technologies Co., Ltd. All rights reserved.-from mindspeed.features_manager.feature import MindSpeedFeature---class AffinityFeature(MindSpeedFeature):- def __init__(self):- super(AffinityFeature, self).__init__('affinity', optimization_level=0)-- def register_patches(self, patch_manager, args):- from mindspeed_llm.core.tensor_parallel.cross_entropy import calculate_predicted_logits- # use logical negation followed by multiplication to achieve the same effect as setting selected elements to zero- patch_manager.register_patch('megatron.core.tensor_parallel.cross_entropy.VocabParallelCrossEntropy.calculate_predicted_logits',- calculate_predicted_logits)\ No newline at end of file+# Copyright (c) 2025, Huawei Technologies Co., Ltd. All rights reserved.+from mindspeed.features_manager.feature import MindSpeedFeature+++class AffinityFeature(MindSpeedFeature):+ def __init__(self):+ super(AffinityFeature, self).__init__('affinity', optimization_level=0)++ def register_patches(self, patch_manager, args):+ from mindspeed_llm.core.tensor_parallel.cross_entropy import (+ calculate_predicted_logits,+ vocab_parallel_cross_entropy_wrapper,+ )+ # use logical negation followed by multiplication to achieve the same effect as setting selected elements to zero+ patch_manager.register_patch('megatron.core.tensor_parallel.cross_entropy.VocabParallelCrossEntropy.calculate_predicted_logits',+ calculate_predicted_logits)+ patch_manager.register_patch('megatron.core.tensor_parallel.cross_entropy.vocab_parallel_cross_entropy',+ vocab_parallel_cross_entropy_wrapper)diff --git a/mindspeed_llm/training/qwen3_8b_4dev.md b/mindspeed_llm/training/qwen3_8b_4dev.mdnew file mode 100644index 0000000000000000000000000000000000000000..0809298e2f82561d5a5ceae4dd24d8280575941f--- /dev/null+++ b/mindspeed_llm/training/qwen3_8b_4dev.md@@ -0,0 +1,103 @@+# Four-device Qwen3 training++`mindspeed_llm.training.qwen3_8b_4dev` is a foreground entrypoint for the+`mindspeed_training_run_spec` JSON interface. It reads model dimensions,+optimizer settings, seed, sequence length, batch size, and update count from+the run specification and launches the normal `pretrain_gpt.py` workers.++```bash+python -B -m mindspeed_llm.training.qwen3_8b_4dev \+ --run-spec /path/to/run-spec.json \+ --device-ids 0,1,2,3 \+ --master-addr 127.0.0.1 --master-port 18024 \+ --runtime-dir /path/to/runtime --output-dir /path/to/output+```++For a checkpointed run, add `--checkpoint-dir /path/to/checkpoint --save-at N`.+This saves and exits at update N. To continue the same run in a fresh process,+use `--checkpoint-dir /path/to/checkpoint --resume` with the original total+update count in the specification. Megatron retains its model, optimizer,+scheduler, RNG, and consumed-sample checkpoint handling.++## Execution choices++- Two pipeline stages, two data-parallel replicas, tensor parallelism of one,+ and microbatch size one preserve the reference partitioning and sample order.+- BF16 model parameters use FP32 master parameters, Adam moments, accumulated+ gradients, gradient reduction, and loss arithmetic. The existing project ATB+ operator fuses matrix multiplication with FP32 weight-gradient accumulation.+- Both pipeline stages retain gradient buckets when parameter gathering is+ overlapped. Reductions start as buckets become ready in the last microbatch;+ parameter gathering can prefetch subsequent layers.+- Shared embeddings already occupy their own DDP bucket. After reduce-scatter,+ pipeline synchronization reduces only the gradient shard owned by the local+ optimizer. Padded buckets, custom FSDP, quantized optimizers, and multiple+ distributed optimizer instances retain the full reduction.+- Local-vocabulary cross entropy uses the native NPU operation in FP32.+ Partitioned vocabularies, label smoothing, and unsupported inputs retain+ Megatron's implementation.+- Gradient clipping scales floating-point buffers in place when input and+ output are the same tensor. Other cases retain the original copy semantics.+- The deterministic in-memory dataset uses zero loader workers. Torch's elastic+ supervisor retains foreground execution, signal forwarding, failure+ propagation, and worker reaping. The supervisor skips model adaptation during+ package import; training workers apply it normally.++Native operators use the existing source builders and the caller's isolated+`TORCH_EXTENSIONS_DIR`. No compiled libraries are part of this change.++Kernel fusion can change floating-point rounding. Validation compares the full+loss trajectory, work accounting, and checkpoint/restart observations with the+reference, in addition to checking the task's finite-loss and cleanup gates.++## Validation results++The public 30-update benchmark completed 480 samples and 983040 tokens on four+Ascend 910B devices. Its primary window starts after update 10 and includes+updates 11–30 and process shutdown (655360 scored tokens).++| Metric | Reference | Optimized |+| --- | ---: | ---: |+| Primary throughput, tokens/s | 7859.41 | 8447.07 |+| Mean reported update time, updates 11–30, ms | 3425.64 | 3137.22 |+| Host-timed scored window, s | 83.385 | 77.584 |+| End-to-end throughput, tokens/s | 5236.95 | 5519.35 |+| End-to-end time, s | 187.712 | 178.108 |+| Maximum observed HBM, MB | 59654 | 59753 |++Primary throughput improved **7.48%** and end-to-end throughput improved+**5.39%** in these runs. All measurement gates passed, including native-cache+isolation, source-bound native builds, full work completion, finite losses,+NPU activity, and cleanup. The maximum absolute difference across the 30+reported losses was **0.000953**; final losses were 7.390043 and 7.389971.++The public correctness probe saves update 1 and resumes updates 2 and 3 in a+fresh process with seed 173. Both the reference and optimized runs passed all+save, restart, finite-loss, work-accounting, and cleanup checks.++| Update | Consumed samples | Reference loss | Optimized loss |+| --- | ---: | ---: | ---: |+| 1, before save | 16 | 12.76026 | 12.76026 |+| 2, after restart | 32 | 12.69319 | 12.69304 |+| 3 | 48 | 12.51877 | 12.51879 |++The largest absolute loss difference is 0.00015. Every update reported zero+skipped iterations and zero NaN iterations.++The public `describe`, `smoke`, and explicit `cleanup` commands also passed.+Cleanup confirmed worker termination, release of the rendezvous port, and+removal of the generated dataset helper.++Additional regression checks passed:++- The upstream `tests_extend/unit_tests/ops/atb/test_matmul_add.py` test, plus+ representative projection shapes including the odd-sized full vocabulary.+- Native cross-entropy loss and gradients against an independent stable+ implementation, including the full 151937-token vocabulary.+- Distributed cross entropy with TP sizes one and two, FP32 and BF16 inputs,+ nonuniform masked output gradients, and unchanged label-smoothing behavior.+- Shared-embedding gradients and reconstructed parameters against a full+ all-reduce reference, for padded and unpadded buckets and both synchronous+ and overlapped parameter gathering, across three updates.+- 192 exact scaling comparisons covering FP16, BF16, FP32, FP64, integer,+ boolean, and complex tensors, including strided and aliased buffers.diff --git a/mindspeed_llm/training/qwen3_8b_4dev.py b/mindspeed_llm/training/qwen3_8b_4dev.pynew file mode 100644index 0000000000000000000000000000000000000000..d02f6e78e027855b0d18839a12ed5abe75151e73--- /dev/null+++ b/mindspeed_llm/training/qwen3_8b_4dev.py@@ -0,0 +1,165 @@+"""Foreground launcher for a four-device Qwen training run.++The run specification owns the model, optimizer, seed and amount of work.+This launcher uses two pipeline stages and two data parallel replicas, with+FP32 weight-gradient accumulation fused into the NPU matrix multiplication.+Torch's elastic launcher supervises the workers and propagates failures and+termination signals; no background training service is created.+"""++import argparse+import json+import os+from pathlib import Path+++def _positive_int(value):+ number = int(value)+ if number <= 0:+ raise argparse.ArgumentTypeError("expected a positive integer")+ return number+++def _device_ids(value):+ try:+ devices = tuple(int(part) for part in value.split(","))+ except ValueError as exc:+ raise argparse.ArgumentTypeError("device ids must be comma-separated integers") from exc+ if len(devices) != 4 or len(set(devices)) != 4 or min(devices) < 0:+ raise argparse.ArgumentTypeError("PP2-DP2 requires four distinct nonnegative device ids")+ return devices+++def training_arguments(spec, *, checkpoint_dir=None, save_at=None, resume=False):+ """Translate the supplied work into ordinary Megatron training arguments."""+ if spec.get("schema_version") != 1 or spec.get("kind") != "mindspeed_training_run_spec":+ raise ValueError("unsupported training run specification")+ model, optimizer, work = spec["model"], spec["optimizer"], spec["work"]+ if model["num_layers"] % 2 or work["global_batch_size"] % 2:+ raise ValueError("PP2-DP2 requires an even layer count and global batch size")+ if resume and save_at is not None:+ raise ValueError("resume and save-at are mutually exclusive")+ if (resume or save_at is not None) and checkpoint_dir is None:+ raise ValueError("checkpoint-dir is required for saving or resuming")+ if save_at is not None and not 0 < save_at <= work["optimizer_updates"]:+ raise ValueError("save-at must be within the requested training run")++ args = [+ "--use-mcore-models",+ "--spec", "mindspeed_llm.tasks.models.spec.qwen3_spec", "layer_spec",+ "--transformer-impl", "local",+ "--distributed-backend", "nccl",+ "--tensor-model-parallel-size", "1",+ "--pipeline-model-parallel-size", "2",+ "--context-parallel-size", "1",+ "--num-layers", str(model["num_layers"]),+ "--hidden-size", str(model["model_width"]),+ "--ffn-hidden-size", str(model["ffn_width"]),+ "--num-attention-heads", str(model["num_attention_heads"]),+ "--group-query-attention",+ "--num-query-groups", str(model["num_query_groups"]),+ "--kv-channels", str(model["kv_channels"]),+ "--qk-layernorm",+ "--seq-length", str(work["sequence_length"]),+ "--max-position-embeddings", str(work["sequence_length"]),+ "--micro-batch-size", "1",+ "--global-batch-size", str(work["global_batch_size"]),+ "--train-iters", str(work["optimizer_updates"]),+ "--lr", str(optimizer["learning_rate"]),+ "--min-lr", str(optimizer["minimum_learning_rate"]),+ "--lr-decay-style", optimizer["learning_rate_decay_style"],+ "--weight-decay", str(optimizer["weight_decay"]),+ "--adam-beta1", str(optimizer["adam_beta1"]),+ "--adam-beta2", str(optimizer["adam_beta2"]),+ "--clip-grad", str(optimizer["clip_grad"]),+ "--attention-dropout", "0.0",+ "--hidden-dropout", "0.0",+ "--seed", str(spec["seed"]),+ "--bf16",+ "--mock-data",+ # The deterministic in-memory dataset needs no I/O workers. Avoid+ # forking large training processes and transferring tiny batches by IPC.+ "--num-workers", "0",+ "--tokenizer-type", "NullTokenizer",+ "--vocab-size", str(model["vocab_size"]),+ "--make-vocab-size-divisible-by", "1",+ "--position-embedding-type", "rope",+ "--use-rotary-position-embeddings",+ "--rotary-base", str(model["rotary_base"]),+ "--disable-bias-linear",+ "--normalization", "RMSNorm",+ "--norm-epsilon", "1e-6",+ "--swiglu",+ "--attention-softmax-in-fp32",+ "--use-flash-attn",+ "--use-fused-rotary-pos-emb",+ "--use-fused-swiglu",+ "--use-fused-rmsnorm",+ "--no-masked-softmax-fusion",+ "--use-distributed-optimizer",+ "--reuse-fp32-param",+ "--overlap-grad-reduce",+ "--overlap-param-gather",+ # Each DP group contains replicas of the same pipeline stage. Start+ # reductions as buckets become ready in the final microbatch, including+ # on the second stage, instead of delaying them until its backward ends.+ "--no-align-grad-reduce",+ "--use-ascend-coc",+ "--log-interval", str(work["log_interval"]),+ "--eval-iters", "0",+ "--eval-interval", str(work["optimizer_updates"]),+ ]+ if resume:+ args.extend(("--load", str(checkpoint_dir)))+ elif save_at is not None:+ args.extend((+ "--save", str(checkpoint_dir),+ "--save-interval", str(save_at),+ "--exit-interval", str(save_at),+ ))+ return args+++def main(argv=None):+ parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)+ parser.add_argument("--run-spec", type=Path, required=True)+ parser.add_argument("--device-ids", type=_device_ids, required=True)+ parser.add_argument("--master-addr", default="127.0.0.1")+ parser.add_argument("--master-port", type=_positive_int, required=True)+ parser.add_argument("--runtime-dir", type=Path, required=True)+ parser.add_argument("--output-dir", type=Path, required=True)+ parser.add_argument("--checkpoint-dir", type=Path)+ checkpoint_action = parser.add_mutually_exclusive_group()+ checkpoint_action.add_argument("--save-at", type=_positive_int)+ checkpoint_action.add_argument("--resume", action="store_true")+ args = parser.parse_args(argv)+ if args.master_port > 65535:+ parser.error("master-port must be at most 65535")++ with args.run_spec.open(encoding="utf-8") as stream:+ spec = json.load(stream)+ train_args = training_arguments(+ spec, checkpoint_dir=args.checkpoint_dir, save_at=args.save_at, resume=args.resume+ )+ args.runtime_dir.mkdir(parents=True, exist_ok=True)+ args.output_dir.mkdir(parents=True, exist_ok=True)+ os.environ["ASCEND_RT_VISIBLE_DEVICES"] = ",".join(map(str, args.device_ids))++ # Use the same foreground supervisor as torchrun. In particular, keep its+ # signal forwarding, worker reaping, exit status and rendezvous cleanup.+ from torch.distributed.run import main as torchrun++ torchrun([+ "--nproc-per-node=4",+ "--nnodes=1",+ "--node-rank=0",+ f"--master-addr={args.master_addr}",+ f"--master-port={args.master_port}",+ "--max-restarts=0",+ str(Path(__file__).resolve().parents[2] / "pretrain_gpt.py"),+ *train_args,+ ])+++if __name__ == "__main__":+ main()