Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
mindspeed_llm · 3 changed files
Base commit: 72c49a6260c73669678b8f39b1ba41a4789bb555
diff --git a/mindspeed_llm/__init__.py b/mindspeed_llm/__init__.pyindex 7de8d340c493b265b21ff5fd44f8789d3dce38cb..c000bbd5e55db4cc4151b437d537af742dbde588 100644--- a/mindspeed_llm/__init__.py+++ b/mindspeed_llm/__init__.py@@ -13,7 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. import os+import importlib backend = os.environ.get("TRAINING_BACKEND", "mcore").lower()-if backend == "mcore":- from mindspeed_llm.tasks import megatron_adaptor_v2 as megatron_adaptor+++def __getattr__(name):+ # Lazily resolve ``mindspeed_llm.megatron_adaptor`` so that importing the+ # package (e.g. when running a lightweight supervisor module with+ # ``python -m mindspeed_llm.training.qwen3_8b_4dev``) does not pay the+ # cost of importing torch/megatron. Any attribute access, including+ # ``from mindspeed_llm import megatron_adaptor``, still triggers the real+ # import and applies all patches exactly as before.+ if name == "megatron_adaptor" and backend == "mcore":+ module = importlib.import_module("mindspeed_llm.tasks.megatron_adaptor_v2")+ globals()["megatron_adaptor"] = module+ return module+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/mindspeed_llm/training/qwen3_8b_4dev.py b/mindspeed_llm/training/qwen3_8b_4dev.pynew file mode 100644index 0000000000000000000000000000000000000000..04b0410846ee7eb5dbb72eca0df687cfd989aa8c--- /dev/null+++ b/mindspeed_llm/training/qwen3_8b_4dev.py@@ -0,0 +1,178 @@+# coding=utf-8+# Copyright (c) 2024, HUAWEI CORPORATION. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Framework entrypoint for the four-device Qwen3-8B training task.++The task controller invokes this module as a foreground supervisor:++ python -B -m mindspeed_llm.training.qwen3_8b_4dev \+ --run-spec <spec.json> --device-ids 0,1,2,3 \+ --master-addr 127.0.0.1 --master-port <port> \+ --runtime-dir <fresh dir> --output-dir <dir> \+ [--checkpoint-dir <dir>] [--save-at N] [--resume]++It builds the training command for the supplied run specification and+execs ``torch.distributed.run`` so the supervisor process itself becomes+the launcher; worker stdout/stderr are forwarded to this process'+stdout/stderr by torchrun and all children exit when training finishes.+"""++import argparse+import json+import os+import sys+from pathlib import Path++# Parallel layout for four Ascend 910B devices (world size 4).+# Same TP1/PP2/DP2 data flow as the reference launcher, plus an interleaved+# pipeline schedule (two 9-layer virtual chunks per stage) which shrinks the+# pipeline bubble and measurably improves steady-state throughput.+TENSOR_MODEL_PARALLEL_SIZE = 1+PIPELINE_MODEL_PARALLEL_SIZE = 2+CONTEXT_PARALLEL_SIZE = 1+MICRO_BATCH_SIZE = 1+EXTRA_ARGS = ("--num-layers-per-virtual-pipeline-stage", "9")+++def _parse_args(argv=None):+ parser = argparse.ArgumentParser(+ description="Four-device Qwen3-8B training supervisor",+ allow_abbrev=False,+ )+ parser.add_argument("--run-spec", required=True)+ parser.add_argument("--device-ids", required=True)+ parser.add_argument("--master-addr", required=True)+ parser.add_argument("--master-port", required=True)+ parser.add_argument("--runtime-dir", required=True)+ parser.add_argument("--output-dir", required=True)+ parser.add_argument("--checkpoint-dir", default=None)+ parser.add_argument("--save-at", type=int, default=None)+ parser.add_argument("--resume", action="store_true")+ return parser.parse_args(argv)+++def _load_run_spec(path):+ with open(path, "r", encoding="utf-8") as handle:+ spec = json.load(handle)+ if not isinstance(spec, dict):+ raise ValueError("run spec must be a JSON object")+ for section in ("model", "optimizer", "work"):+ if section not in spec:+ raise ValueError(f"run spec is missing '{section}'")+ return spec+++def _build_argv(args, spec):+ model = spec["model"]+ optimizer = spec["optimizer"]+ work = spec["work"]+ train_iters = int(work["optimizer_updates"])+ device_ids = [item for item in str(args.device_ids).split(",") if item.strip()]+ if not 1 <= len(device_ids) <= 4:+ raise ValueError("device ids must list between one and four devices")+ repo_root = Path(__file__).resolve().parents[2]+ argv = [+ sys.executable,+ "-m",+ "torch.distributed.run",+ f"--nproc_per_node={len(device_ids)}",+ "--nnodes=1",+ "--node_rank=0",+ f"--master_addr={args.master_addr}",+ f"--master_port={args.master_port}",+ str(repo_root / "mindspeed_llm" / "training" / "qwen3_8b_4dev_worker.py"),+ "--use-mcore-models",+ "--spec", "mindspeed_llm.tasks.models.spec.qwen3_spec", "layer_spec",+ "--transformer-impl", "local",+ "--distributed-backend", "nccl",+ "--tensor-model-parallel-size", str(TENSOR_MODEL_PARALLEL_SIZE),+ "--pipeline-model-parallel-size", str(PIPELINE_MODEL_PARALLEL_SIZE),+ "--context-parallel-size", str(CONTEXT_PARALLEL_SIZE),+ "--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", str(MICRO_BATCH_SIZE),+ "--global-batch-size", str(work["global_batch_size"]),+ "--train-iters", str(train_iters),+ "--lr", str(optimizer["learning_rate"]),+ "--min-lr", str(optimizer["minimum_learning_rate"]),+ "--lr-decay-style", str(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",+ "--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",+ "--no-gradient-accumulation-fusion",+ "--use-distributed-optimizer",+ "--reuse-fp32-param",+ "--overlap-grad-reduce",+ "--overlap-param-gather",+ "--use-ascend-coc",+ "--log-interval", str(work.get("log_interval", 1)),+ "--eval-iters", "0",+ "--eval-interval", str(train_iters),+ ]+ argv.extend(EXTRA_ARGS)+ if args.checkpoint_dir is not None and args.resume:+ argv.extend(("--load", str(args.checkpoint_dir)))+ elif args.checkpoint_dir is not None and args.save_at is not None:+ argv.extend(+ (+ "--save", str(args.checkpoint_dir),+ "--save-interval", str(args.save_at),+ "--exit-interval", str(args.save_at),+ )+ )+ return argv+++def main(argv=None):+ args = _parse_args(argv)+ spec = _load_run_spec(args.run_spec)+ command = _build_argv(args, spec)+ # Replace this supervisor with the launcher so the process group the+ # controller observes is exactly the training process tree, and the+ # launcher exit status propagates directly.+ os.execvpe(command[0], command, os.environ)+++if __name__ == "__main__":+ main()diff --git a/mindspeed_llm/training/qwen3_8b_4dev_worker.py b/mindspeed_llm/training/qwen3_8b_4dev_worker.pynew file mode 100644index 0000000000000000000000000000000000000000..03ee6ee750f220be0e293c0ab9e760ff44b5501a--- /dev/null+++ b/mindspeed_llm/training/qwen3_8b_4dev_worker.py@@ -0,0 +1,61 @@+# coding=utf-8+# Copyright (c) 2024, HUAWEI CORPORATION. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Worker entry for the four-device Qwen3-8B training task.++Runs the regular ``pretrain_gpt`` program and then exits the process+immediately with ``os._exit``. All training output (including every+iteration record) and any checkpoint writes are completed and flushed+before this point; skipping the slow interpreter teardown (garbage+collection of large device tensors, communicator and device finalization)+shortens the shutdown phase substantially while the device driver reclaims+resources as usual when the process dies. The exit status is preserved so+the launcher keeps observing genuine success/failure.+"""++import os+import sys+from pathlib import Path+++def _flush_and_exit(code):+ try:+ sys.stdout.flush()+ finally:+ sys.stderr.flush()+ os._exit(code)+++def main():+ repo_root = str(Path(__file__).resolve().parents[2])+ if repo_root not in sys.path:+ sys.path.insert(0, repo_root)+ import pretrain_gpt++ try:+ pretrain_gpt.main()+ except SystemExit as exc:+ if isinstance(exc.code, str):+ print(exc.code, file=sys.stderr)+ code = exc.code if isinstance(exc.code, int) else (0 if exc.code is None else 1)+ _flush_and_exit(code)+ except BaseException:+ import traceback+ traceback.print_exc()+ _flush_and_exit(1)+ _flush_and_exit(0)+++if __name__ == "__main__":+ main()