Buckets:
| """Build Megatron-Core pretraining commands from a model config.toml.""" | |
| from __future__ import annotations | |
| import tomllib | |
| from pathlib import Path | |
| from typing import Any | |
| from utils.paths import resolve | |
| def load_config(path: Path) -> dict[str, Any]: | |
| with path.open("rb") as handle: | |
| return tomllib.load(handle) | |
| def flag(enabled: bool, name: str) -> list[str]: | |
| return [name] if enabled else [] | |
| def checkpoint_ready(path: Path) -> bool: | |
| return (path / "latest_checkpointed_iteration.txt").exists() | |
| def resolve_load_dir(paths: dict[str, Any]) -> Path | None: | |
| output_dir = resolve(paths["output_dir"]) | |
| if checkpoint_ready(output_dir): | |
| return output_dir | |
| init_checkpoint = paths.get("init_checkpoint") | |
| if init_checkpoint: | |
| init_dir = resolve(str(init_checkpoint)) | |
| if checkpoint_ready(init_dir): | |
| return init_dir | |
| return None | |
| def validate_config(config: dict[str, Any], optimizer_override: str | None) -> str: | |
| model = config["model"] | |
| data = config["data"] | |
| training = config["training"] | |
| launcher = config["launcher"] | |
| optimizer = (optimizer_override or config["optimizer"]["name"]).lower() | |
| if optimizer != "adamw": | |
| raise ValueError(f"optimizer must be adamw, got {optimizer!r}") | |
| if model["hidden_size"] <= 0 or model["num_layers"] <= 0: | |
| raise ValueError("model dimensions must be positive") | |
| if model["num_attention_heads"] % model["num_query_groups"] != 0: | |
| raise ValueError("num_attention_heads must be divisible by num_query_groups") | |
| if model.get("attention_variant") in {"depth_delta", "depth_delta_down"}: | |
| if model["num_layers"] % int(model["depth_delta_group_size"]): | |
| raise ValueError("num_layers must be divisible by depth_delta_group_size") | |
| if not 0 < int(model["depth_delta_rank"]) <= int(model["kv_channels"]): | |
| raise ValueError("depth_delta_rank must be in (0, kv_channels]") | |
| if model.get("attention_variant") == "independent_kv": | |
| group_size = int(model["independent_kv_group_size"]) | |
| if model["num_layers"] % group_size: | |
| raise ValueError("num_layers must be divisible by independent_kv_group_size") | |
| follower_groups = model.get("independent_kv_follower_query_groups") | |
| if follower_groups is None: | |
| follower_groups = max(1, int(model["num_query_groups"]) // 2) | |
| follower_groups = int(follower_groups) | |
| if not 0 < follower_groups <= int(model["num_query_groups"]): | |
| raise ValueError( | |
| "independent_kv_follower_query_groups must be in (0, num_query_groups]" | |
| ) | |
| if model["num_attention_heads"] % follower_groups != 0: | |
| raise ValueError( | |
| "num_attention_heads must be divisible by independent_kv_follower_query_groups" | |
| ) | |
| if model.get("attention_variant") == "kv_share": | |
| if model["num_layers"] % int(model["kv_share_group_size"]): | |
| raise ValueError("num_layers must be divisible by kv_share_group_size") | |
| if model.get("attention_variant") == "kvpath": | |
| if model["num_layers"] % int(model["kvpath_group_size"]): | |
| raise ValueError("num_layers must be divisible by kvpath_group_size") | |
| expected_kv_channels = int(model["kvpath_base_head_dim"]) + int(model["kvpath_rank"]) | |
| if int(model["kv_channels"]) != expected_kv_channels: | |
| raise ValueError( | |
| "kv_channels must equal kvpath_base_head_dim + kvpath_rank" | |
| ) | |
| if model.get("attention_variant") == "kvpath_branching": | |
| group = int(model["kvpath_group_size"]) | |
| rank = int(model["kvpath_rank"]) | |
| branch = int(model["kvpath_branch_head_dim"]) | |
| if group < 2 or model["num_layers"] % group: | |
| raise ValueError("kvpath_branching requires complete groups of at least two layers") | |
| if min(rank, branch, int(model["kvpath_base_head_dim"])) < 1 or rank % 2: | |
| raise ValueError("KVPath widths must be positive and kvpath_rank must be even") | |
| if int(model["kv_channels"]) != branch + rank: | |
| raise ValueError("kv_channels must equal kvpath_branch_head_dim + kvpath_rank") | |
| if model.get("attention_variant") == "kvpath_delta": | |
| if model["num_layers"] % int(model["kvpath_group_size"]): | |
| raise ValueError("num_layers must be divisible by kvpath_group_size") | |
| if int(model["kvpath_rank"]) < 1 or int(model["kv_channels"]) < 1: | |
| raise ValueError("kvpath_rank and kv_channels must be positive") | |
| world_size = launcher["nnodes"] * launcher["nproc_per_node"] | |
| model_parallel = ( | |
| training["tensor_model_parallel_size"] | |
| * training["pipeline_model_parallel_size"] | |
| * training["context_parallel_size"] | |
| ) | |
| if world_size % model_parallel: | |
| raise ValueError( | |
| f"world size {world_size} must be divisible by model parallel size {model_parallel}" | |
| ) | |
| data_parallel = world_size // model_parallel | |
| update_batch = data["micro_batch_size"] * data_parallel | |
| if data["global_batch_size"] % update_batch: | |
| raise ValueError( | |
| "global_batch_size must be divisible by micro_batch_size * data_parallel_size; " | |
| f"got {data['global_batch_size']} vs {update_batch}" | |
| ) | |
| return optimizer | |
| def build_train_command( | |
| config: dict[str, Any], | |
| optimizer: str, | |
| extra_megatron_args: list[str] | None = None, | |
| *, | |
| python_executable: str, | |
| load_dir: Path | None = None, | |
| skip_load: bool = False, | |
| ) -> list[str]: | |
| paths = config["paths"] | |
| launcher = config["launcher"] | |
| model = config["model"] | |
| data = config["data"] | |
| training = config["training"] | |
| schedule = config["schedule"] | |
| ckpt = config.get("checkpoint", {}) | |
| megatron_repo = resolve(paths["megatron_repo"]) | |
| entrypoint = megatron_repo / "pretrain_gpt.py" | |
| tokenizer_dir = resolve(paths["tokenizer_dir"]) | |
| train_prefix = resolve(paths["train_data_prefix"]) | |
| valid_prefix = resolve(paths["valid_data_prefix"]) | |
| output_dir = resolve(paths["output_dir"]) | |
| data_cache_path = resolve(data["data_cache_path"]) | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| data_cache_path.mkdir(parents=True, exist_ok=True) | |
| optimizer_cfg = config["optimizer"][optimizer] | |
| lr = float(optimizer_cfg["lr"]) | |
| min_lr = lr * float(schedule["min_lr_ratio"]) | |
| command = [ | |
| python_executable, | |
| "-m", | |
| "torch.distributed.run", | |
| "--nnodes", | |
| str(launcher["nnodes"]), | |
| "--nproc-per-node", | |
| str(launcher["nproc_per_node"]), | |
| "--node-rank", | |
| str(launcher["node_rank"]), | |
| "--master-addr", | |
| str(launcher["master_addr"]), | |
| "--master-port", | |
| str(launcher["master_port"]), | |
| str(entrypoint), | |
| "--num-layers", | |
| str(model["num_layers"]), | |
| "--hidden-size", | |
| str(model["hidden_size"]), | |
| "--ffn-hidden-size", | |
| str(model["ffn_hidden_size"]), | |
| "--num-attention-heads", | |
| str(model["num_attention_heads"]), | |
| "--num-query-groups", | |
| str(model["num_query_groups"]), | |
| "--kv-channels", | |
| str(model["kv_channels"]), | |
| "--seq-length", | |
| str(data["seq_length"]), | |
| "--max-position-embeddings", | |
| str(model["max_position_embeddings"]), | |
| "--position-embedding-type", | |
| "rope", | |
| "--rotary-percent", | |
| "1.0", | |
| "--rotary-base", | |
| str(model["rope_theta"]), | |
| "--normalization", | |
| str(model["normalization"]), | |
| "--norm-epsilon", | |
| str(model["norm_epsilon"]), | |
| "--swiglu", | |
| "--disable-bias-linear", | |
| "--attention-dropout", | |
| str(model["attention_dropout"]), | |
| "--hidden-dropout", | |
| str(model["hidden_dropout"]), | |
| "--tokenizer-type", | |
| "GPT2BPETokenizer", | |
| "--vocab-file", | |
| str(tokenizer_dir / "vocab.json"), | |
| "--merge-file", | |
| str(tokenizer_dir / "merges.txt"), | |
| "--make-vocab-size-divisible-by", | |
| str(model["make_vocab_size_divisible_by"]), | |
| "--train-data-path", | |
| str(train_prefix), | |
| "--valid-data-path", | |
| str(valid_prefix), | |
| "--data-cache-path", | |
| str(data_cache_path), | |
| "--num-workers", | |
| str(data["num_workers"]), | |
| "--micro-batch-size", | |
| str(data["micro_batch_size"]), | |
| "--global-batch-size", | |
| str(data["global_batch_size"]), | |
| "--train-iters", | |
| str(training["train_iters"]), | |
| "--lr", | |
| str(lr), | |
| "--min-lr", | |
| str(min_lr), | |
| "--lr-decay-style", | |
| str(schedule["lr_decay_style"]), | |
| "--lr-decay-iters", | |
| str(training["train_iters"]), | |
| "--lr-warmup-iters", | |
| str(schedule["lr_warmup_iters"]), | |
| "--weight-decay", | |
| str(schedule["weight_decay"]), | |
| "--clip-grad", | |
| str(training["clip_grad"]), | |
| "--eval-interval", | |
| str(training["eval_interval"]), | |
| "--eval-iters", | |
| str(training["eval_iters"]), | |
| "--log-interval", | |
| str(training["log_interval"]), | |
| "--save-interval", | |
| str(training["save_interval"]), | |
| "--save", | |
| str(output_dir), | |
| "--seed", | |
| str(training["seed"]), | |
| "--tensor-model-parallel-size", | |
| str(training["tensor_model_parallel_size"]), | |
| "--pipeline-model-parallel-size", | |
| str(training["pipeline_model_parallel_size"]), | |
| "--context-parallel-size", | |
| str(training["context_parallel_size"]), | |
| "--transformer-impl", | |
| str(training["transformer_impl"]), | |
| "--distributed-backend", | |
| "nccl", | |
| ] | |
| if str(schedule["lr_decay_style"]).upper() == "WSD": | |
| wsd_decay_iters = schedule.get("lr_wsd_decay_iters") | |
| if wsd_decay_iters is None: | |
| raise ValueError("schedule.lr_wsd_decay_iters is required when lr_decay_style is WSD") | |
| command += [ | |
| "--lr-wsd-decay-iters", | |
| str(wsd_decay_iters), | |
| "--lr-wsd-decay-style", | |
| str(schedule.get("lr_wsd_decay_style", "linear")), | |
| ] | |
| # Megatron ignores --num-query-groups unless --group-query-attention is set. | |
| use_gqa = int(model["num_query_groups"]) != int(model["num_attention_heads"]) | |
| command += flag(use_gqa, "--group-query-attention") | |
| command += flag(model["untie_embeddings_and_output_weights"], "--untie-embeddings-and-output-weights") | |
| command += flag(model["qk_layernorm"], "--qk-layernorm") | |
| command += flag(training["bf16"], "--bf16") | |
| command += flag(training["use_flash_attn"], "--use-flash-attn") | |
| command += flag(training["sequence_parallel"], "--sequence-parallel") | |
| command += flag(training["distributed_optimizer"], "--use-distributed-optimizer") | |
| command += ["--no-gradient-accumulation-fusion"] | |
| wandb = config.get("wandb", {}) | |
| if wandb.get("enabled", False): | |
| project = str(wandb.get("project", "DepthDeltaKV")) | |
| exp_name = str(wandb.get("exp_name") or Path(str(paths.get("output_dir", "run"))).name) | |
| command += [ | |
| "--wandb-project", | |
| project, | |
| "--wandb-exp-name", | |
| exp_name, | |
| ] | |
| entity = wandb.get("entity") | |
| if entity: | |
| command += ["--wandb-entity", str(entity)] | |
| save_dir = wandb.get("save_dir") | |
| if save_dir: | |
| command += ["--wandb-save-dir", str(resolve(str(save_dir)))] | |
| attention_variant = model.get("attention_variant") | |
| if attention_variant is not None: | |
| command += ["--experimental-attention-variant", str(attention_variant)] | |
| if attention_variant in {"depth_delta", "depth_delta_down"}: | |
| command += [ | |
| "--depth-delta-window-size", | |
| str(model["depth_delta_window_size"]), | |
| "--depth-delta-group-size", | |
| str(model["depth_delta_group_size"]), | |
| "--depth-delta-rank", | |
| str(model["depth_delta_rank"]), | |
| "--depth-delta-init-scale", | |
| str(model["depth_delta_init_scale"]), | |
| ] | |
| if attention_variant == "independent_kv": | |
| command += [ | |
| "--independent-kv-group-size", | |
| str(model["independent_kv_group_size"]), | |
| ] | |
| follower_groups = model.get("independent_kv_follower_query_groups") | |
| if follower_groups is not None: | |
| command += [ | |
| "--independent-kv-follower-query-groups", | |
| str(follower_groups), | |
| ] | |
| if attention_variant == "kv_share": | |
| command += [ | |
| "--kv-share-group-size", | |
| str(model["kv_share_group_size"]), | |
| ] | |
| if attention_variant in {"kvpath", "kvpath_branching"}: | |
| command += [ | |
| "--kvpath-group-size", | |
| str(model["kvpath_group_size"]), | |
| "--kvpath-rank", | |
| str(model["kvpath_rank"]), | |
| "--kvpath-base-head-dim", | |
| str(model["kvpath_base_head_dim"]), | |
| ] | |
| if attention_variant == "kvpath_branching": | |
| command += ["--kvpath-branch-head-dim", str(model["kvpath_branch_head_dim"])] | |
| if model.get("kvpath_base_rmsnorm", False): | |
| command += ["--kvpath-base-rmsnorm"] | |
| if attention_variant == "kvpath_delta": | |
| command += [ | |
| "--kvpath-group-size", | |
| str(model["kvpath_group_size"]), | |
| "--kvpath-rank", | |
| str(model["kvpath_rank"]), | |
| ] | |
| retain_interval = ckpt.get("save_retain_interval") | |
| if retain_interval is not None: | |
| command += ["--save-retain-interval", str(retain_interval)] | |
| if not skip_load: | |
| resolved_load = load_dir if load_dir is not None else resolve_load_dir(paths) | |
| if resolved_load is not None: | |
| command += ["--load", str(resolved_load)] | |
| command += [ | |
| "--optimizer", | |
| "adam", | |
| "--adam-beta1", | |
| str(optimizer_cfg["beta1"]), | |
| "--adam-beta2", | |
| str(optimizer_cfg["beta2"]), | |
| "--adam-eps", | |
| str(optimizer_cfg["eps"]), | |
| ] | |
| return command + (extra_megatron_args or []) | |
| def required_train_files(config: dict[str, Any]) -> list[Path]: | |
| paths = config["paths"] | |
| data = config["data"] | |
| megatron_repo = resolve(paths["megatron_repo"]) | |
| tokenizer_dir = resolve(paths["tokenizer_dir"]) | |
| train_prefix = resolve(paths["train_data_prefix"]) | |
| valid_prefix = resolve(paths["valid_data_prefix"]) | |
| return [ | |
| megatron_repo / "pretrain_gpt.py", | |
| tokenizer_dir / "vocab.json", | |
| tokenizer_dir / "merges.txt", | |
| train_prefix.with_suffix(".bin"), | |
| train_prefix.with_suffix(".idx"), | |
| valid_prefix.with_suffix(".bin"), | |
| valid_prefix.with_suffix(".idx"), | |
| ] | |
Xet Storage Details
- Size:
- 14.8 kB
- Xet hash:
- ce0ed7243fc6f8331f832d487bb8dacda212be01cbbd23f0668917d43b60f594
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.