xuan-luo's picture
download
raw
24.3 kB
diff --git a/megatron/core/models/gpt/experimental_attention_variant_module_specs.py b/megatron/core/models/gpt/experimental_attention_variant_module_specs.py
index 87c63a126..37c636703 100644
--- a/megatron/core/models/gpt/experimental_attention_variant_module_specs.py
+++ b/megatron/core/models/gpt/experimental_attention_variant_module_specs.py
@@ -146,6 +146,90 @@ def get_dsa_module_spec_for_backend(
return attention
+def get_depth_delta_module_spec_for_backend(
+ config: TransformerConfig, backend: BackendSpecProvider = None
+) -> ModuleSpec:
+ """Delegate to DeltaKV's project-local DepthDelta implementation."""
+ if backend is None:
+ backend = _get_backend_spec_provider(config=config)
+
+ from training.depth_delta.depth_delta.module_specs import (
+ get_depth_delta_module_spec_for_backend as build_depth_delta_spec,
+ )
+
+ return build_depth_delta_spec(config=config, backend=backend)
+
+
+def get_depth_delta_down_module_spec_for_backend(
+ config: TransformerConfig, backend: BackendSpecProvider = None
+) -> ModuleSpec:
+ """Delegate to DeltaKV's project-local rank-global implementation."""
+ if backend is None:
+ backend = _get_backend_spec_provider(config=config)
+
+ from training.depth_delta_down.depth_delta_down.module_specs import (
+ get_depth_delta_down_module_spec_for_backend as build_depth_delta_down_spec,
+ )
+
+ return build_depth_delta_down_spec(config=config, backend=backend)
+
+
+def get_independent_kv_module_spec_for_backend(
+ config: TransformerConfig, backend: BackendSpecProvider = None
+) -> ModuleSpec:
+ """Delegate to DeltaKV's project-local independent (non-shared) reduced-KV implementation."""
+ if backend is None:
+ backend = _get_backend_spec_provider(config=config)
+
+ from training.independent_kv.independent_kv.module_specs import (
+ get_independent_kv_module_spec_for_backend as build_independent_kv_spec,
+ )
+
+ return build_independent_kv_spec(config=config, backend=backend)
+
+
+def get_kv_share_module_spec_for_backend(
+ config: TransformerConfig, backend: BackendSpecProvider = None
+) -> ModuleSpec:
+ """Delegate to DeltaKV's project-local cross-layer KV-sharing implementation."""
+ if backend is None:
+ backend = _get_backend_spec_provider(config=config)
+
+ from training.kv_share.kv_share.module_specs import (
+ get_kv_share_module_spec_for_backend as build_kv_share_spec,
+ )
+
+ return build_kv_share_spec(config=config, backend=backend)
+
+
+def get_kvpath_module_spec_for_backend(
+ config: TransformerConfig, backend: BackendSpecProvider = None
+) -> ModuleSpec:
+ """Delegate to DeltaKV's project-local KVPath implementation."""
+ if backend is None:
+ backend = _get_backend_spec_provider(config=config)
+
+ from training.kvpath.kvpath.module_specs import (
+ get_kvpath_module_spec_for_backend as build_kvpath_spec,
+ )
+
+ return build_kvpath_spec(config=config, backend=backend)
+
+
+def get_kvpath_delta_module_spec_for_backend(
+ config: TransformerConfig, backend: BackendSpecProvider = None
+) -> ModuleSpec:
+ """Build the project-local cumulative K/V delta attention spec."""
+ if backend is None:
+ backend = _get_backend_spec_provider(config=config)
+
+ from training.kvpath_delta.kvpath_delta.module_specs import (
+ get_kvpath_delta_module_spec_for_backend as build_kvpath_delta_spec,
+ )
+
+ return build_kvpath_delta_spec(config=config, backend=backend)
+
+
def get_experimental_attention_variant_module_spec(
config: TransformerConfig, backend: BackendSpecProvider = None
) -> ModuleSpec:
@@ -158,6 +242,26 @@ def get_experimental_attention_variant_module_spec(
return get_gated_delta_net_module_spec(config=config, backend=backend)
elif config.experimental_attention_variant == "dsa":
return get_dsa_module_spec_for_backend(config=config, backend=backend)
+ elif config.experimental_attention_variant == "depth_delta":
+ return get_depth_delta_module_spec_for_backend(config=config, backend=backend)
+ elif config.experimental_attention_variant == "depth_delta_down":
+ return get_depth_delta_down_module_spec_for_backend(
+ config=config, backend=backend
+ )
+ elif config.experimental_attention_variant == "independent_kv":
+ return get_independent_kv_module_spec_for_backend(config=config, backend=backend)
+ elif config.experimental_attention_variant == "kv_share":
+ return get_kv_share_module_spec_for_backend(config=config, backend=backend)
+ elif config.experimental_attention_variant == "kvpath":
+ return get_kvpath_module_spec_for_backend(config=config, backend=backend)
+ elif config.experimental_attention_variant == "kvpath_branching":
+ from training.kvpath_branching.kvpath_branching.module_specs import (
+ get_kvpath_branching_module_spec_for_backend,
+ )
+
+ return get_kvpath_branching_module_spec_for_backend(config=config, backend=backend)
+ elif config.experimental_attention_variant == "kvpath_delta":
+ return get_kvpath_delta_module_spec_for_backend(config=config, backend=backend)
else:
raise ValueError(
f"Invalid experimental attention variant: {config.experimental_attention_variant}"
diff --git a/megatron/core/transformer/transformer_config.py b/megatron/core/transformer/transformer_config.py
index 245a164fb..423a26f85 100644
--- a/megatron/core/transformer/transformer_config.py
+++ b/megatron/core/transformer/transformer_config.py
@@ -299,10 +299,23 @@ class TransformerConfig(ModelParallelConfig):
####################
# attention variant
####################
- experimental_attention_variant: Optional[Literal['gdn', 'gdn2', 'dsa', 'gated_delta_net']] = (
- None
- )
- """Type of attention variant to use. Currently support gdn, gdn2 and dsa.
+ experimental_attention_variant: Optional[
+ Literal[
+ 'gdn',
+ 'gdn2',
+ 'dsa',
+ 'depth_delta',
+ 'depth_delta_down',
+ 'independent_kv',
+ 'kv_share',
+ 'kvpath',
+ 'kvpath_delta',
+ 'kvpath_branching',
+ 'gated_delta_net',
+ ]
+ ] = None
+ """Type of attention variant to use. Supports gdn, gdn2, dsa, depth_delta,
+ depth_delta_down, independent_kv, kv_share, kvpath, and kvpath_delta.
gdn2 selects the GDN2 (Gated DeltaNet-2) variant of the gated delta net layer, with
channel-wise decay, erase and write gates; it requires flash-linear-attention >= 0.5.1.
Both gdn and gdn2 also select the layer built for the hybrid layer pattern symbol 'G'.
@@ -312,6 +325,75 @@ class TransformerConfig(ModelParallelConfig):
experimental_attention_variant_loss_scale_func: Optional[Callable[[torch.Tensor], None]] = None
"""Optional hook for experimental attention variants to receive the main loss scale."""
+ ####################
+ # DepthDelta
+ ####################
+ depth_delta_window_size: int = 128
+ """Number of exact recent KV positions retained by follower layers."""
+
+ depth_delta_group_size: int = 4
+ """Number of consecutive layers sharing one full-dimensional anchor KV."""
+
+ depth_delta_rank: int = 64
+ """Per-KV-head channel dimension of follower global K/V innovations."""
+
+ depth_delta_init_scale: float = 0.1
+ """Initialization scale applied to both DepthDelta low-rank factors."""
+
+ ####################
+ # IndependentKV
+ ####################
+ independent_kv_group_size: int = 4
+ """Number of consecutive layers per independent-KV cycle. The first layer of each
+ cycle ('full' layer) keeps the baseline num_query_groups; the remaining layers
+ ('half' layers) are ordinary, fully independent GQA layers that simply use fewer
+ KV groups. There is no cross-layer KV sharing or low-rank projection, unlike
+ depth_delta/depth_delta_down."""
+
+ independent_kv_follower_query_groups: Optional[int] = None
+ """num_query_groups used by the non-first ('half') layers in each independent_kv
+ cycle. Defaults to max(1, num_query_groups // 2), i.e. half the baseline KV cache,
+ when left unset."""
+
+ ####################
+ # KVShare
+ ####################
+ kv_share_group_size: int = 4
+ """Number of consecutive layers per KV-share cycle. The first layer of each
+ cycle ('anchor') is an ordinary full GQA layer using the baseline
+ num_query_groups. The remaining layers ('follower') own only a Q projection:
+ they directly reuse the anchor layer's exact (pre-RoPE, post-qk-layernorm)
+ K/V for the same positions -- no per-layer K/V projection, no low-rank
+ delta, unlike depth_delta/depth_delta_down."""
+
+ ####################
+ # KVPath
+ ####################
+ kvpath_group_size: int = 4
+ """Number of layers per KVPath group. In kvpath, the anchor produces a
+ kvpath_base_head_dim-wide shared K/V and every layer adds a rank-wide K/V
+ branch by concatenation. In kvpath_delta, the anchor projects full-width
+ K/V and each follower up-projects a rank-wide K/V delta to kv_channels,
+ adds it to the previous layer's unrotated K/V, then applies full-width
+ RoPE to K."""
+
+ kvpath_rank: int = 32
+ """Per-KV-head K/V delta width (all layers for kvpath; followers only for
+ kvpath_delta)."""
+
+ kvpath_branch_head_dim: int = 64
+ """Per-layer transformed base width for kvpath_branching; cache keeps base_head_dim."""
+
+ kvpath_base_rmsnorm: bool = False
+ """Normalize each anchor K/V head before sharing it. False preserves older checkpoints."""
+
+ kvpath_base_head_dim: int = 128
+ """Per-KV-head channel width of the anchor-only, RoPE-free base K/V. The
+ effective per-head K/V width is kvpath_base_head_dim + kvpath_rank, which must
+ equal kv_channels; kv_channels also determines the per-head Q width
+ (kv_channels = kvpath_base_head_dim + kvpath_rank, split into a NoPE prefix that
+ scores against base K and a RoPE suffix that scores against delta K)."""
+
####################
# DSA
####################
@@ -1528,6 +1610,153 @@ class TransformerConfig(ModelParallelConfig):
f"tensor_model_parallel_size ({self.tensor_model_parallel_size})."
)
+ if self.experimental_attention_variant in {"depth_delta", "depth_delta_down"}:
+ # Anchor and follower layers intentionally have different parameter
+ # structures, so distributed checkpoints must preserve per-layer keys.
+ self.hetereogenous_dist_checkpoint = True
+ if self.depth_delta_window_size < 1:
+ raise ValueError("depth_delta_window_size must be positive.")
+ if self.depth_delta_group_size < 2:
+ raise ValueError("depth_delta_group_size must be at least 2.")
+ if self.num_layers % self.depth_delta_group_size != 0:
+ raise ValueError(
+ "num_layers must be divisible by depth_delta_group_size; "
+ f"got {self.num_layers} and {self.depth_delta_group_size}."
+ )
+ if not 0 < self.depth_delta_rank <= self.kv_channels:
+ raise ValueError(
+ "depth_delta_rank must be in (0, kv_channels]; "
+ f"got {self.depth_delta_rank} and {self.kv_channels}."
+ )
+ if self.depth_delta_init_scale <= 0:
+ raise ValueError("depth_delta_init_scale must be positive.")
+ if (
+ self.tensor_model_parallel_size != 1
+ or self.pipeline_model_parallel_size != 1
+ or self.context_parallel_size != 1
+ or self.sequence_parallel
+ ):
+ raise ValueError(
+ "DepthDelta MVP requires TP=PP=CP=1 and sequence_parallel=False."
+ )
+ if self.attention_dropout != 0.0:
+ raise ValueError("DepthDelta MVP requires attention_dropout=0.")
+ if self.recompute_granularity is not None:
+ raise ValueError(
+ "DepthDelta MVP does not support activation recomputation because "
+ "anchor KV is shared across layers."
+ )
+ if self.cuda_graph_impl != "none":
+ raise ValueError(
+ "DepthDelta MVP does not support CUDA graphs because anchor KV uses "
+ "per-forward cross-layer state."
+ )
+
+ if self.experimental_attention_variant == "independent_kv":
+ # Full and half layers have different linear_qkv shapes, so distributed
+ # checkpoints must preserve per-layer keys.
+ self.hetereogenous_dist_checkpoint = True
+ if self.independent_kv_group_size < 2:
+ raise ValueError("independent_kv_group_size must be at least 2.")
+ if self.num_layers % self.independent_kv_group_size != 0:
+ raise ValueError(
+ "num_layers must be divisible by independent_kv_group_size; "
+ f"got {self.num_layers} and {self.independent_kv_group_size}."
+ )
+ follower_groups = self.independent_kv_follower_query_groups
+ if follower_groups is None:
+ follower_groups = max(1, self.num_query_groups // 2)
+ if not 0 < follower_groups <= self.num_query_groups:
+ raise ValueError(
+ "independent_kv_follower_query_groups must be in (0, num_query_groups]; "
+ f"got {follower_groups} and {self.num_query_groups}."
+ )
+ if self.num_attention_heads % follower_groups != 0:
+ raise ValueError(
+ "num_attention_heads must be divisible by "
+ f"independent_kv_follower_query_groups; got {self.num_attention_heads} "
+ f"and {follower_groups}."
+ )
+
+ if self.experimental_attention_variant == "kv_share":
+ # Anchor layers own a full linear_qkv; follower layers own only a
+ # linear_q, so distributed checkpoints must preserve per-layer keys.
+ self.hetereogenous_dist_checkpoint = True
+ if self.kv_share_group_size < 2:
+ raise ValueError("kv_share_group_size must be at least 2.")
+ if self.num_layers % self.kv_share_group_size != 0:
+ raise ValueError(
+ "num_layers must be divisible by kv_share_group_size; "
+ f"got {self.num_layers} and {self.kv_share_group_size}."
+ )
+ if (
+ self.tensor_model_parallel_size != 1
+ or self.pipeline_model_parallel_size != 1
+ or self.context_parallel_size != 1
+ or self.sequence_parallel
+ ):
+ raise ValueError(
+ "kv_share MVP requires TP=PP=CP=1 and sequence_parallel=False."
+ )
+
+ if self.experimental_attention_variant == "kvpath_delta":
+ self.hetereogenous_dist_checkpoint = True
+ if self.kvpath_group_size < 2 or self.num_layers % self.kvpath_group_size:
+ raise ValueError("KVPath-delta requires num_layers divisible by group_size >= 2")
+ if self.kvpath_rank < 1 or self.kv_channels < 1:
+ raise ValueError("KVPath-delta requires positive rank and kv_channels")
+ if (
+ self.tensor_model_parallel_size != 1
+ or self.pipeline_model_parallel_size != 1
+ or self.context_parallel_size != 1
+ or self.sequence_parallel
+ or self.attention_dropout != 0.0
+ ):
+ raise ValueError("KVPath-delta requires TP=PP=CP=1 and zero attention dropout")
+
+ if self.experimental_attention_variant in {"kvpath", "kvpath_branching"}:
+ # Anchor layers own linear_q_delta_base; followers own only
+ # linear_q_delta (no QK-Norm on either), so distributed checkpoints
+ # must preserve per-layer keys.
+ self.hetereogenous_dist_checkpoint = True
+ if self.kvpath_group_size < 2:
+ raise ValueError("kvpath_group_size must be at least 2.")
+ if self.num_layers % self.kvpath_group_size != 0:
+ raise ValueError(
+ "num_layers must be divisible by kvpath_group_size; "
+ f"got {self.num_layers} and {self.kvpath_group_size}."
+ )
+ if self.kvpath_rank < 1:
+ raise ValueError("kvpath_rank must be positive.")
+ if self.kvpath_base_head_dim < 1:
+ raise ValueError("kvpath_base_head_dim must be positive.")
+ base_width = self.kvpath_base_head_dim
+ if self.experimental_attention_variant == "kvpath_branching":
+ base_width = self.kvpath_branch_head_dim
+ if base_width < 1 or self.kvpath_rank % 2:
+ raise ValueError("Branch width must be positive and kvpath_rank must be even")
+ if self.recompute_granularity == "full":
+ raise ValueError("kvpath_branching does not support full-layer recomputation")
+ expected_kv_channels = base_width + self.kvpath_rank
+ if self.kv_channels != expected_kv_channels:
+ raise ValueError(
+ "kv_channels must equal the effective base/branch width + kvpath_rank; "
+ f"got kv_channels={self.kv_channels}, "
+ f"kvpath_base_head_dim={self.kvpath_base_head_dim}, "
+ f"kvpath_rank={self.kvpath_rank}."
+ )
+ if (
+ self.tensor_model_parallel_size != 1
+ or self.pipeline_model_parallel_size != 1
+ or self.context_parallel_size != 1
+ or self.sequence_parallel
+ ):
+ raise ValueError(
+ "KVPath MVP requires TP=PP=CP=1 and sequence_parallel=False."
+ )
+ if self.attention_dropout != 0.0:
+ raise ValueError("KVPath MVP requires attention_dropout=0.")
+
if is_gated_delta_net_variant(self.experimental_attention_variant):
# gdn2 may also be enabled for GDN layers built via the hybrid layer pattern
# symbol 'G', where linear_attention_freq is unused; the GPT experimental
diff --git a/megatron/training/initialize.py b/megatron/training/initialize.py
index c0f28ce7a..ee9bbc8d0 100644
--- a/megatron/training/initialize.py
+++ b/megatron/training/initialize.py
@@ -586,11 +586,16 @@ def _warmup_jit_function(tp_size=None):
# Warmup JIT fusions with the input grad_enable state of both forward
# prop and recomputation. The three branches are mutually exclusive.
if warmup_bias_swiglu:
+ # SwiGLU consumes [gate; up], i.e. 2 * ffn_hidden_size channels.
+ # Like GEGLU below, duplicate the existing draws without advancing
+ # the RNG. This also supports odd FFN widths (e.g. KVPath branching).
+ swiglu_bias = torch.cat([bias, bias], dim=-1)
+ swiglu_input = torch.cat([input, input], dim=-1)
for bias_grad, input_grad in zip([True, True], [False, True]):
- bias.requires_grad, input.requires_grad = bias_grad, input_grad
+ swiglu_bias.requires_grad, swiglu_input.requires_grad = bias_grad, input_grad
for _ in range(5):
- output = bias_swiglu(input, bias)
- del output
+ output = bias_swiglu(swiglu_input, swiglu_bias)
+ del output, swiglu_bias, swiglu_input
elif warmup_bias_gelu:
for bias_grad, input_grad in zip([True, True], [False, True]):
bias.requires_grad, input.requires_grad = bias_grad, input_grad
diff --git a/megatron/training/models/gpt.py b/megatron/training/models/gpt.py
index 46dcc9b28..2dc8f53cf 100644
--- a/megatron/training/models/gpt.py
+++ b/megatron/training/models/gpt.py
@@ -2,6 +2,7 @@
import inspect
import logging
+import os
from typing import Any, Callable, ClassVar, Literal, override
from megatron.core.models.gpt.heterogeneous.heterogeneous_layer_specs import get_gpt_heterogeneous_layer_spec
@@ -106,7 +107,7 @@ def _te_or_local_layer_spec(config: "GPTModelConfig", vp_stage: int) -> ModuleSp
kwargs = {"use_te_op_fuser": config.use_transformer_engine_op_fuser}
else:
kwargs = {}
- return get_gpt_layer_with_transformer_engine_spec(
+ layer_spec = get_gpt_layer_with_transformer_engine_spec(
config.transformer.num_moe_experts,
config.transformer.moe_grouped_gemm,
config.transformer.qk_layernorm,
@@ -121,6 +122,16 @@ def _te_or_local_layer_spec(config: "GPTModelConfig", vp_stage: int) -> ModuleSp
use_grouped_gemm_for_dense_mlp=config.transformer.use_grouped_gemm_for_dense_mlp,
**kwargs,
)
+ if os.environ.get("GQA_TORCH_FLASH_SDPA") == "1":
+ if transformer_cfg.multi_latent_attention or transformer_cfg.qk_layernorm:
+ raise ValueError("GQA Torch Flash SDPA requires standard GQA without QK norm")
+ from training.gqa_sdpa_kernel.sdpa_attention import FlashSDPACoreAttention
+
+ layer_spec.submodules.self_attention.submodules.core_attention = (
+ FlashSDPACoreAttention
+ )
+ logger.warning("GQA core attention: PyTorch Flash SDPA")
+ return layer_spec
else:
return get_gpt_layer_local_spec(
transformer_cfg.num_moe_experts,
diff --git a/megatron/training/training.py b/megatron/training/training.py
index e4b0afb56..3f92f2a80 100644
--- a/megatron/training/training.py
+++ b/megatron/training/training.py
@@ -3629,6 +3629,7 @@ def training_log(
)
_otel_skipped_iters_snapshot = int(total_loss_dict.get(skipped_iters_key, 0))
+ wandb_metrics = {}
for key in total_loss_dict:
if key not in [advanced_iters_key, skipped_iters_key, nan_iters_key]:
avg = total_loss_dict[key].item() / float(
@@ -3636,8 +3637,19 @@ def training_log(
)
if avg >= 0.0:
log_string += ' {}: {:.6E} |'.format(key, avg)
+ wandb_metrics[key] = avg
+ # Train PPL is free: exp(loss). Cap like validation logging.
+ if 'loss' in key.lower():
+ wandb_metrics[f'{key} ppl'] = math.exp(min(20, avg))
if should_reset:
total_loss_dict[key] = torch.tensor([0.0], dtype=torch.float, device='cuda')
+ if wandb_writer and not is_first_iteration:
+ if learning_rate is not None:
+ wandb_metrics['learning-rate'] = learning_rate
+ if grad_norm is not None:
+ wandb_metrics['grad-norm'] = grad_norm
+ wandb_metrics['batch-size'] = batch_size
+ wandb_writer.log(wandb_metrics, iteration)
if args.num_experts is not None and moe_log_string:
log_string += moe_log_string
log_string += f' loss scale: {loss_scale:.1f} |'
@@ -5398,7 +5410,11 @@ def evaluate_and_print_results(
)
if wandb_writer and is_last_rank():
wandb_writer.log(
- {'{} validation{}'.format(key, suffix): total_loss_dict[key].item()}, iteration
+ {
+ '{} validation{}'.format(key, suffix): total_loss_dict[key].item(),
+ '{} validation{} ppl'.format(key, suffix): ppl,
+ },
+ iteration,
)
if process_non_loss_data_func is not None and writer and is_last_rank():

Xet Storage Details

Size:
24.3 kB
·
Xet hash:
5aa1d824052ec952a111941f980bafde233e86da093fa727fbea5d5493d85f3b

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.