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..4ce2b2cb22c86b4fc516f0b467595cdd63c2032f 100644--- a/mindspeed_llm/__init__.py+++ b/mindspeed_llm/__init__.py@@ -13,7 +13,15 @@ # See the License for the specific language governing permissions and # limitations under the License. import os+import sys backend = os.environ.get("TRAINING_BACKEND", "mcore").lower()-if backend == "mcore":+# The four-device task launcher only validates its controller-owned arguments+# before replacing itself with torchrun. Avoid importing the full framework in+# that transient process; torchrun workers do not have these launcher options+# and therefore still install the normal adaptor before importing Megatron.+is_qwen3_task_launcher = all(+ option in sys.argv for option in ("--run-spec", "--device-ids", "--runtime-dir")+)+if backend == "mcore" and not is_qwen3_task_launcher: from mindspeed_llm.tasks import megatron_adaptor_v2 as megatron_adaptordiff --git a/mindspeed_llm/training/qwen3_8b_4dev.py b/mindspeed_llm/training/qwen3_8b_4dev.pynew file mode 100644index 0000000000000000000000000000000000000000..cfc74f2425c694aeb6c95b3cf9332cbd79fe4976--- /dev/null+++ b/mindspeed_llm/training/qwen3_8b_4dev.py@@ -0,0 +1,320 @@+"""Task entrypoint for deterministic Qwen3-8B training on four NPUs.++The task controller owns the public run specification and process group. This+module validates that interface, translates it to the existing Megatron/MindSpeed+training program, and then replaces itself with ``torchrun`` so signals and exit+status continue to belong to the controller's foreground process group.+"""++from __future__ import annotations++import argparse+import json+import os+from pathlib import Path+import sys+from typing import Any+++_MODEL_KEYS = {+ "num_layers",+ "model_width",+ "ffn_width",+ "num_attention_heads",+ "num_query_groups",+ "kv_channels",+ "vocab_size",+ "rotary_base",+}+_OPTIMIZER_KEYS = {+ "learning_rate",+ "minimum_learning_rate",+ "learning_rate_decay_style",+ "weight_decay",+ "adam_beta1",+ "adam_beta2",+ "clip_grad",+}+_WORK_KEYS = {+ "sequence_length",+ "global_batch_size",+ "optimizer_updates",+ "log_interval",+}+++def _parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description=__doc__)+ 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, type=int)+ parser.add_argument("--runtime-dir", required=True)+ parser.add_argument("--output-dir", required=True)+ parser.add_argument("--checkpoint-dir")+ parser.add_argument("--save-at", type=int)+ parser.add_argument("--resume", action="store_true")+ return parser+++def _regular_json_file(raw: str) -> tuple[Path, dict[str, Any]]:+ path = Path(raw)+ if not path.is_absolute() or not path.is_file() or path.is_symlink():+ raise ValueError("--run-spec must name an absolute regular file")+ value = json.loads(path.read_text(encoding="utf-8"))+ if not isinstance(value, dict):+ raise ValueError("run specification must contain a JSON object")+ return path, value+++def _existing_directory(raw: str, option: str) -> Path:+ path = Path(raw)+ if not path.is_absolute() or not path.is_dir() or path.is_symlink():+ raise ValueError(f"{option} must name an absolute directory")+ return path+++def _require_keys(value: object, keys: set[str], label: str) -> dict[str, Any]:+ if not isinstance(value, dict) or set(value) != keys:+ raise ValueError(f"invalid {label} section in run specification")+ return value+++def _positive_int(value: object, label: str) -> int:+ if type(value) is not int or value <= 0:+ raise ValueError(f"{label} must be a positive integer")+ return value+++def _finite_number(value: object, label: str) -> float:+ if type(value) not in (int, float):+ raise ValueError(f"{label} must be numeric")+ number = float(value)+ if not (number == number and abs(number) != float("inf")):+ raise ValueError(f"{label} must be finite")+ return number+++def _validated_spec(raw: dict[str, Any]) -> dict[str, Any]:+ if set(raw) != {"schema_version", "kind", "seed", "model", "optimizer", "work"}:+ raise ValueError("run specification has an invalid top-level shape")+ if raw["schema_version"] != 1 or raw["kind"] != "mindspeed_training_run_spec":+ raise ValueError("unsupported run specification")+ if type(raw["seed"]) is not int or raw["seed"] < 0:+ raise ValueError("seed must be a non-negative integer")++ model = _require_keys(raw["model"], _MODEL_KEYS, "model")+ optimizer = _require_keys(raw["optimizer"], _OPTIMIZER_KEYS, "optimizer")+ work = _require_keys(raw["work"], _WORK_KEYS, "work")+ for key in _MODEL_KEYS:+ _positive_int(model[key], f"model.{key}")+ for key in ("sequence_length", "global_batch_size", "optimizer_updates", "log_interval"):+ _positive_int(work[key], f"work.{key}")+ for key in _OPTIMIZER_KEYS - {"learning_rate_decay_style"}:+ _finite_number(optimizer[key], f"optimizer.{key}")+ if optimizer["learning_rate_decay_style"] != "cosine":+ raise ValueError("only the task's cosine learning-rate schedule is supported")+ return raw+++def _device_ids(raw: str) -> tuple[int, ...]:+ parts = raw.split(",")+ if len(parts) != 4 or any(not item.isdigit() for item in parts):+ raise ValueError("--device-ids must contain four comma-separated device ids")+ values = tuple(int(item) for item in parts)+ if len(set(values)) != len(values):+ raise ValueError("--device-ids contains duplicates")+ return values+++def _training_argv(+ *,+ spec: dict[str, Any],+ devices: tuple[int, ...],+ master_addr: str,+ master_port: int,+ checkpoint: Path | None,+ save_at: int | None,+ resume: bool,+) -> list[str]:+ model = spec["model"]+ optimizer = spec["optimizer"]+ work = spec["work"]+ updates = int(work["optimizer_updates"])+ source_root = Path(__file__).resolve().parents[2]+ training_program = source_root / "pretrain_gpt.py"+ if not training_program.is_file():+ raise ValueError("pretrain_gpt.py is unavailable")++ argv = [+ sys.executable,+ "-B",+ "-m",+ "torch.distributed.run",+ f"--nproc_per_node={len(devices)}",+ "--nnodes=1",+ "--node_rank=0",+ f"--master_addr={master_addr}",+ f"--master_port={master_port}",+ str(training_program),+ "--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",+ "--num-layers-per-virtual-pipeline-stage",+ "3",+ "--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(updates),+ "--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",+ "--use-distributed-optimizer",+ "--reuse-fp32-param",+ "--overlap-grad-reduce",+ "--overlap-param-gather",+ "--use-ascend-coc",+ "--num-workers",+ "0",+ "--log-interval",+ str(work["log_interval"]),+ "--eval-iters",+ "0",+ "--eval-interval",+ str(updates),+ ]+ if resume:+ assert checkpoint is not None+ argv.extend(("--load", str(checkpoint)))+ elif save_at is not None:+ assert checkpoint is not None+ argv.extend(+ (+ "--save",+ str(checkpoint),+ "--save-interval",+ str(save_at),+ "--exit-interval",+ str(save_at),+ )+ )+ return argv+++def main(argv: list[str] | None = None) -> int:+ args = _parser().parse_args(argv)+ _, raw_spec = _regular_json_file(args.run_spec)+ spec = _validated_spec(raw_spec)+ devices = _device_ids(args.device_ids)+ _existing_directory(args.runtime_dir, "--runtime-dir")+ _existing_directory(args.output_dir, "--output-dir")+ if args.master_addr not in {"127.0.0.1", "localhost"}:+ raise ValueError("--master-addr must be loopback")+ if not 1 <= args.master_port <= 65535:+ raise ValueError("--master-port is outside the TCP port range")+ if args.resume and args.save_at is not None:+ raise ValueError("--resume and --save-at are mutually exclusive")++ checkpoint: Path | None = None+ if args.checkpoint_dir is not None:+ checkpoint = Path(args.checkpoint_dir)+ if not checkpoint.is_absolute() or checkpoint.is_symlink():+ raise ValueError("--checkpoint-dir must be an absolute non-symlink path")+ if args.resume:+ if checkpoint is None or not checkpoint.is_dir():+ raise ValueError("--resume requires an existing checkpoint directory")+ if args.save_at is not None:+ updates = int(spec["work"]["optimizer_updates"])+ if checkpoint is None or not 1 <= args.save_at <= updates:+ raise ValueError("--save-at requires a checkpoint path and a valid update")++ command = _training_argv(+ spec=spec,+ devices=devices,+ master_addr=args.master_addr,+ master_port=args.master_port,+ checkpoint=checkpoint,+ save_at=args.save_at,+ resume=args.resume,+ )+ environment = os.environ.copy()+ environment["MINDSPEED_QWEN3_BENCHMARK_FAST_EXIT"] = "1"+ os.execve(sys.executable, command, environment)+ return 127+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/pretrain_gpt.py b/pretrain_gpt.pyindex 5a8506bb3f73e23ca5e1c1e2562d0a861c433cfb..0e1bf42e16d70bd8a0365a02c14a35c8f42e29a8 100644--- a/pretrain_gpt.py+++ b/pretrain_gpt.py@@ -3,6 +3,7 @@ """Pretrain GPT.""" import os+import sys from functools import partial from typing import Union @@ -305,5 +306,27 @@ def main(): forward_step) +def _fast_benchmark_worker_exit():+ """Exit without Python's expensive NPU-context finalizers.++ The benchmark launcher enables this only for its short-lived workers. At+ this point ``pretrain`` has returned, so the optimizer update and normal+ training observations are complete. Synchronizing the device and all+ ranks before flushing output preserves that completion boundary, while+ ``os._exit`` avoids spending several seconds finalizing already-disposable+ process-local NPU and data-loader state.+ """+ if os.environ.get("MINDSPEED_QWEN3_BENCHMARK_FAST_EXIT") != "1":+ return++ torch.npu.synchronize()+ if torch.distributed.is_available() and torch.distributed.is_initialized():+ torch.distributed.barrier()+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)++ if __name__ == "__main__": main()+ _fast_benchmark_worker_exit()