From 6658b14a30fc3ed47c709e5e2fdf8a6237854439 Mon Sep 17 00:00:00 2001 From: Zijun Li <3335126979@qq.com> Date: Fri, 4 Dec 2026 11:20:05 +0800 Subject: [PATCH 1/5] feat(dspine): wire training, Plan, checkpoint and window replay Register DSpine in AutoDraftModelConfig / AutoEagle3DraftModel and the DRAFT_ALGORITHMS dispatch, add the dspine Plan family with fail-closed scope, and wire the trainer and checkpoint topology. DSpineTrainer replays each accumulation window: a no-grad prepass pools one detached alignment_ce from backbone CE, the CPU/CUDA RNG state is restored, and the same microbatches are replayed with gradients so every microbatch shares the coefficient. Refinement stays microbatch-finalized and the replay sums numerators over the total sequence count, matching SpecForge #965/#1038. Add the Qwen3-8B example config, CPU integration tests and docs. --- aspec/config/draft_algorithm.py | 3 +- .../config/dspine_qwen3_8b_draft_config.json | 42 +++ aspec/models/draft/__init__.py | 3 + aspec/models/draft/auto.py | 3 + aspec/models/dspine.py | 6 + aspec/planning.py | 68 +++- aspec/training/checkpoint.py | 44 ++- aspec/training/dflash_trainer.py | 7 + aspec/training/dspine_trainer.py | 158 ++++++++++ aspec/training/trainer.py | 9 +- aspec/training/trainer_actor.py | 6 +- configs/examples/dspine_qwen3_8b_4k_tcp.yaml | 92 ++++++ docs/support.md | 2 +- docs/user-guide/algorithms.md | 17 +- docs/user-guide/dspine.md | 65 ++-- tests/cpu/test_dspine_integration.py | 296 ++++++++++++++++++ 16 files changed, 785 insertions(+), 36 deletions(-) create mode 100644 aspec/config/dspine_qwen3_8b_draft_config.json create mode 100644 aspec/training/dspine_trainer.py create mode 100644 configs/examples/dspine_qwen3_8b_4k_tcp.yaml create mode 100644 tests/cpu/test_dspine_integration.py diff --git a/aspec/config/draft_algorithm.py b/aspec/config/draft_algorithm.py index bbceb49..650beca 100644 --- a/aspec/config/draft_algorithm.py +++ b/aspec/config/draft_algorithm.py @@ -20,6 +20,7 @@ "NativeMTPDraftModel": "mtp", "MedusaDraftModel": "medusa", "DominoDraftModel": "domino", + "DSpineDraftModel": "dspine", "JetSpecDraftModel": "jetspec", "DFlashDraftModel": "dflash", "DFlash2DraftModel": "dflash2", @@ -69,7 +70,7 @@ def draft_model_semantics(config) -> dict: "max_position_embeddings", "rope_theta", "rope_scaling", "rope_parameters", "target_layer_ids", "num_target_layers", "target_num_hidden_layers", "num_aux_hidden_states", "medusa_num_heads", "medusa_num_layers", - "projector_type", "emb_dim", "gru_hidden_dim", + "projector_type", "emb_dim", "gru_hidden_dim", "dspine_config", "shift_label", "pure_draft_prefix_len", "fc_norm", "norm_output", "mask_token_id", "lm_head_rank_divisor", "attention_mode", "q_lora_rank", "kv_lora_rank", "qk_nope_head_dim", "qk_rope_head_dim", "v_head_dim", "block_size", diff --git a/aspec/config/dspine_qwen3_8b_draft_config.json b/aspec/config/dspine_qwen3_8b_draft_config.json new file mode 100644 index 0000000..efbb73d --- /dev/null +++ b/aspec/config/dspine_qwen3_8b_draft_config.json @@ -0,0 +1,42 @@ +{ + "architectures": [ + "DSpineDraftModel" + ], + "model_type": "dspine", + "hidden_size": 4096, + "intermediate_size": 12288, + "num_hidden_layers": 5, + "num_attention_heads": 32, + "num_key_value_heads": 8, + "vocab_size": 151936, + "rms_norm_eps": 1e-06, + "max_position_embeddings": 40960, + "rope_theta": 1000000.0, + "num_target_layers": 5, + "target_hidden_size": 4096, + "target_num_hidden_layers": 36, + "target_layer_ids": [ + 1, + 9, + 17, + 25, + 33 + ], + "mask_token_id": 151669, + "block_size": 16, + "is_causal": true, + "tie_word_embeddings": false, + "dspine_config": { + "transfer_rank": 1024, + "message_size": 512, + "top_k": 16, + "ce_weight": 0.1, + "alignment_weight": 0.5, + "alignment_warmup_steps": 146, + "replacement_layers": 3, + "replacement_probability": 0.5, + "replacement_hold_ratio": 0.16666666666666666, + "replacement_end_ratio": 0.3333333333333333, + "candidate_mass_threshold": 0.0001 + } +} diff --git a/aspec/models/draft/__init__.py b/aspec/models/draft/__init__.py index 773fc05..74b331d 100644 --- a/aspec/models/draft/__init__.py +++ b/aspec/models/draft/__init__.py @@ -28,6 +28,7 @@ K3DSparkConfig, K3DSparkModel, ) +from aspec.models.draft.dspine import DSpineConfig, DSpineDraftModel from aspec.models.draft.jetspec import JetSpecConfig, JetSpecDraftModel __all__ = [ @@ -39,6 +40,8 @@ "DFlash2DraftModel", "DominoConfig", "DominoDraftModel", + "DSpineConfig", + "DSpineDraftModel", "JetSpecConfig", "JetSpecDraftModel", "DSparkConfig", diff --git a/aspec/models/draft/auto.py b/aspec/models/draft/auto.py index f798694..7cd3bcd 100644 --- a/aspec/models/draft/auto.py +++ b/aspec/models/draft/auto.py @@ -35,6 +35,7 @@ K3DSparkConfig, K3DSparkModel, ) +from aspec.models.draft.dspine import DSpineConfig, DSpineDraftModel from aspec.models.draft.eagle4 import Eagle4DraftModel from aspec.models.draft.jetspec import JetSpecConfig, JetSpecDraftModel from aspec.models.draft.llama3_eagle import LlamaForCausalLMEagle3 @@ -69,6 +70,7 @@ class AutoEagle3DraftModel(AutoModelForCausalLMBase): NativeMTPConfig: NativeMTPDraftModel, MedusaConfig: MedusaDraftModel, DominoConfig: DominoDraftModel, + DSpineConfig: DSpineDraftModel, JetSpecConfig: JetSpecDraftModel, DFlashConfig: DFlashDraftModel, DFlash2Config: DFlash2DraftModel, @@ -94,6 +96,7 @@ class AutoDraftModelConfig: "NativeMTPDraftModel": NativeMTPConfig, "MedusaDraftModel": MedusaConfig, "DominoDraftModel": DominoConfig, + "DSpineDraftModel": DSpineConfig, "JetSpecDraftModel": JetSpecConfig, "DFlashDraftModel": DFlashConfig, "DFlash2DraftModel": DFlash2Config, diff --git a/aspec/models/dspine.py b/aspec/models/dspine.py index 796104c..992dbaa 100644 --- a/aspec/models/dspine.py +++ b/aspec/models/dspine.py @@ -67,6 +67,12 @@ class DSpineModel(DFlashModel): _materialize_cpu_block_mask = True + @property + def uses_target_hidden_states(self) -> bool: + # DSpine always needs the Target post-norm state for its teacher + # distribution, even though it replaces the DFlash L1 term. + return True + def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) config = getattr(self.draft_model, "config", None) diff --git a/aspec/planning.py b/aspec/planning.py index 22be5c3..a5f49c1 100644 --- a/aspec/planning.py +++ b/aspec/planning.py @@ -525,6 +525,53 @@ def _load_draft_descriptor(config: DictConfig) -> dict[str, Any]: "JetSpec forward KL requires inference.store_last_hidden_states=true" ) + if family == "dspine": + from aspec.models.draft.dspine import DSpineConfig + + try: + raw = DSpineConfig.from_dict(raw).to_dict() + except (ValueError, TypeError) as exc: + raise PlanCompileError(str(exc)) from exc + if raw["block_size"] != _select(config, "training.dflash_block_size"): + raise PlanCompileError( + "DSpine block_size must match training.dflash_block_size" + ) + if raw.get("cudnn_gqa_mode", "auto") != "auto": + raise PlanCompileError( + "DSpine requires cudnn_gqa_mode=auto; the FlexAttention mask " + "controls block visibility" + ) + backend = _select(config, "training.attention_backend") + if backend != "flex_attention": + raise PlanCompileError( + "DSpine requires training.attention_backend=flex_attention; " + "that is the masked block-attention path the CUDA dispatcher uses" + ) + if _select(config, "training.draft_context_parallel_size", 1) != 1: + raise PlanCompileError( + "DSpine currently supports draft_context_parallel_size=1" + ) + if _select(config, "training.dflash_packing", False): + raise PlanCompileError( + "DSpine does not support sequence packing; set " + "training.dflash_packing=false" + ) + if _select(config, "training.compile_model", False): + raise PlanCompileError("DSpine whole-model compile has not been enabled") + if _select(config, "training.dflash_loss_objective") != "decay": + raise PlanCompileError("DSpine supports the decay loss objective only") + if (_select(config, "training.dflash_ce_loss_alpha") != 1.0 + or _select(config, "training.dflash_l1_loss_alpha") != 0.0): + raise PlanCompileError( + "DSpine replaces the CE/L1 mix; set dflash_ce_loss_alpha=1.0 " + "and dflash_l1_loss_alpha=0.0" + ) + if not _select(config, "inference.store_last_hidden_states", False): + raise PlanCompileError( + "DSpine requires inference.store_last_hidden_states=true for " + "the teacher distribution" + ) + target_layer_ids = raw.get("target_layer_ids") if not isinstance(target_layer_ids, list) or not target_layer_ids: raise PlanCompileError( @@ -824,6 +871,7 @@ def _load_draft_descriptor(config: DictConfig) -> dict[str, Any]: "domino_pure_draft_prefix_len": raw.get("pure_draft_prefix_len"), "domino_emb_dim": raw.get("emb_dim"), "domino_gru_hidden_dim": raw.get("gru_hidden_dim"), + "dspine_config": raw.get("dspine_config"), } @@ -1595,6 +1643,22 @@ def _workload( "teacher_feature": "last_hidden_states", "frozen_parts": ["target_lm_head"], } + elif family == "dspine": + objective = { + "family": "dspine", + "loss": "dspine_backbone_refinement_alignment", + "block_size": _select(config, "training.dflash_block_size"), + "num_anchors": _select(config, "training.dflash_num_anchors"), + "num_target_layers": _select(config, "training.dflash_num_target_layers"), + "loss_objective": _select(config, "training.dflash_loss_objective"), + "loss_decay_gamma": _select(config, "training.dflash_loss_decay_gamma"), + "ce_loss_alpha": 1.0, + "l1_loss_alpha": 0.0, + "prediction_start": 1, + "teacher_feature": "last_hidden_states", + "frozen_parts": ["target_lm_head"], + "dspine": dict(draft.get("dspine_config") or {}), + } elif family == "dspark": objective = { "family": family, @@ -1645,7 +1709,7 @@ def _workload( objective["frozen_parts"] = (["draft_body", "embedding", "lm_head"] if draft["eagle4"]["stage"] == "candidate_head" else ["embedding", "candidate_head"] + (["lm_head"] if _select(config, "model.freeze_lm_head", False) else [])) - if family in {"dspark", "dflash", "dflash2", "domino", "jetspec"}: + if family in {"dspark", "dflash", "dflash2", "domino", "dspine", "jetspec"}: objective["anchor_sampling_scope"] = anchor_scope if draft.get("mtp_conditioning"): from aspec.config.mtp_conditioning import mtp_conditioning_semantics @@ -2294,7 +2358,7 @@ def compile_execution_plan( or draft["attention"]["csa"] is not None or draft["attention"]["qsa"] is not None or draft["attention"].get("dsa") is not None - or draft["family"] in {"domino", "jetspec"} + or draft["family"] in {"domino", "dspine", "jetspec"} ) direct_target_output = bool( _select(config, "inference.target_prefill_memory_optimized", False) diff --git a/aspec/training/checkpoint.py b/aspec/training/checkpoint.py index e3e7605..b972fb9 100644 --- a/aspec/training/checkpoint.py +++ b/aspec/training/checkpoint.py @@ -90,7 +90,7 @@ def _logical_training_topology(args: Any, world_size: int) -> dict[str, Any]: key: getattr(args, key, None) for key in ("ttt_length", "loss_type", "lk_eta", "ploss_weights") } - elif getattr(args, "draft_algorithm", None) in {"dflash", "dflash2", "dspark", "domino", "jetspec"}: + elif getattr(args, "draft_algorithm", None) in {"dflash", "dflash2", "dspark", "domino", "dspine", "jetspec"}: topology["training_objective"] = { "block_size": int(args.dflash_block_size), "anchor_sampling_scope": getattr(args, "anchor_sampling_scope", "row"), @@ -105,7 +105,7 @@ def _logical_training_topology(args: Any, world_size: int) -> dict[str, Any]: for name, default in (("temperature", 1.0), ("top_p", 1.0), ("top_k", -1)): key = f"l1_{side}_{name}" topology["training_objective"][key] = getattr(args, f"dspark_{key}", default) - elif args.draft_algorithm in {"domino", "jetspec"}: + elif args.draft_algorithm in {"domino", "dspine", "jetspec"}: fields += ("loss_objective",) else: fields += ("loss_objective", "dpace_alpha") @@ -146,6 +146,14 @@ def _logical_training_topology(args: Any, world_size: int) -> dict[str, Any]: topology["training_objective"]["loss_decay_gamma"] = getattr( args, "jetspec_loss_decay_gamma", 0.0 ) + if args.draft_algorithm == "dspine": + topology["training_objective"]["loss"] = ( + "dspine_backbone_refinement_alignment" + ) + config = getattr(args, "draft_model_config_obj", None) + options = dict(getattr(config, "dspine_config", {}) or {}) + topology["training_objective"]["dspine"] = options + topology["training_objective"]["alignment_ce"] = "window_backbone_ce" if "training_objective" in topology: fields = ("max_seq_length", "micro_batch_size", "draft_accumulation_steps", "max_grad_norm", "seed") @@ -217,7 +225,7 @@ def _validate_exact_resume_topology(args: Any, metadata: dict[str, Any], *, chec raise RuntimeError(f"Exact resume cannot change dspark_{key}; use weights-only initialization") # Checkpoints predating this option always sampled per physical row. # Missing semantic identity must not authorize a switch to per-sample training. - if (getattr(args, "draft_algorithm", None) in {"dspark", "dflash", "dflash2", "domino", "jetspec"} + if (getattr(args, "draft_algorithm", None) in {"dspark", "dflash", "dflash2", "domino", "dspine", "jetspec"} and ((saved_topology or {}).get("training_objective") or {}).get( "anchor_sampling_scope", "row" ) != getattr(args, "anchor_sampling_scope", "row")): @@ -249,8 +257,12 @@ def _validate_exact_resume_topology(args: Any, metadata: dict[str, Any], *, chec ): raise RuntimeError("Exact resume cannot change a legacy full-attention checkpoint to SWA") if saved_topology is None: - if getattr(args, "draft_algorithm", None) in {"domino", "jetspec"}: - name = "Domino" if args.draft_algorithm == "domino" else "JetSpec" + if getattr(args, "draft_algorithm", None) in {"domino", "dspine", "jetspec"}: + name = { + "domino": "Domino", + "dspine": "DSpine", + "jetspec": "JetSpec", + }[args.draft_algorithm] raise RuntimeError( f"Exact resume requires training_topology for {name} checkpoints; " "use continual_training=true for a weights-only new stage." @@ -309,6 +321,28 @@ def _validate_exact_resume_topology(args: Any, metadata: dict[str, Any], *, chec f"missing {missing}. Use continual_training=true for a " "weights-only new stage." ) + if getattr(args, "draft_algorithm", None) == "dspine": + objective = saved_topology.get("training_objective") or {} + semantics = saved_topology.get("draft_model_semantics") or {} + missing = [ + key for key in ( + "dspine", "block_size", "loss", "loss_decay_gamma", + "ce_loss_alpha", "l1_loss_alpha", + ) + if key not in objective + ] + missing += [ + key for key in ( + "architectures", "block_size", "is_causal", "dspine_config", + ) + if key not in semantics + ] + if missing: + raise RuntimeError( + "Exact resume requires complete DSpine training_topology; " + f"missing {missing}. Use continual_training=true for a " + "weights-only new stage." + ) if current_policy.get("dsa") is not None: # Chunk workspace is an execution bound, not the DSA objective. Preserve # every recorded semantic field while allowing a different memory budget. diff --git a/aspec/training/dflash_trainer.py b/aspec/training/dflash_trainer.py index a944f8e..af24e39 100644 --- a/aspec/training/dflash_trainer.py +++ b/aspec/training/dflash_trainer.py @@ -468,6 +468,8 @@ def _forward( raise ValueError("Target-side MTP conditioning requires aligned mtp_hidden_states") prefix_kwargs["draft_prefix"] = MTPPrefix(mtp[:, 1:].to(device, non_blocking=True).detach()) + model_kwargs = self._model_forward_kwargs() + ( loss, accuracy, @@ -489,6 +491,7 @@ def _forward( packed_document_lengths=batch.get("packed_document_lengths"), attention_mask=attention_mask, **prefix_kwargs, + **model_kwargs, ) return ( @@ -501,6 +504,10 @@ def _forward( loss_terms, ) + def _model_forward_kwargs(self) -> dict: + """Extra kwargs for the training wrapper (subclass hook).""" + return {} + def _backward(self, loss: torch.Tensor, accumulation_steps: int = 1) -> torch.Tensor: scaled_loss = loss / accumulation_steps scaled_loss.backward() diff --git a/aspec/training/dspine_trainer.py b/aspec/training/dspine_trainer.py new file mode 100644 index 0000000..f715a7e --- /dev/null +++ b/aspec/training/dspine_trainer.py @@ -0,0 +1,158 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""DSpine trainer — DFlash backbone with adjacent injection and refinement. + +The objective follows SpecForge DSpine: the backbone/refinement terms are +finalized per microbatch, while one detached backbone-CE coefficient +(``alignment_ce``) is shared across every microbatch in an optimizer window. +The trainer therefore replays the accumulation window once without gradients +to pool that coefficient, restores the RNG state, then runs the real +forward/backward pass over the same microbatches. +""" + +import torch + +from aspec.models.draft.dspine import DSpineConfig, DSpineDraftModel +from aspec.models.dspine import DSpineModel +from aspec.models.ops.anchors import anchor_sampling_seed +from aspec.training.dflash_trainer import DFlashTrainer + + +class DSpineTrainer(DFlashTrainer): + """DSpine-specific trainer; reuses the DFlash optimizer/checkpoint path.""" + + _draft_config_class = DSpineConfig + _anchor_slot_offset = 1 + + def __init__(self, args): + super().__init__(args) + self._dspine_step = 0 + self._dspine_total_steps = int( + getattr(args, "lr_total_steps", None) + or getattr(args, "num_train_steps", None) + or 0 + ) + self._window_alignment_ce = None + if self.ce_loss_alpha != 1.0 or self.l1_loss_alpha != 0.0: + raise ValueError( + "DSpine replaces the CE/L1 mix with its own objective; set " + "dflash_ce_loss_alpha=1.0 and dflash_l1_loss_alpha=0.0" + ) + if self.loss_objective != "decay": + raise ValueError("DSpine supports the decay weighting objective only") + + def _build_draft_model(self, config): + if config.block_size != self.block_size: + raise ValueError( + "training.dflash_block_size must match dspine_config.block_size " + f"({self.block_size} != {config.block_size})" + ) + if config.num_target_layers != self.num_target_layers: + raise ValueError( + "training.dflash_num_target_layers must match the number of " + f"dspine_config.target_layer_ids ({self.num_target_layers} != " + f"{config.num_target_layers})" + ) + return DSpineDraftModel(config) + + def _build_training_wrapper(self, draft_model): + wrapper = DSpineModel( + draft_model=draft_model, + block_size=self.block_size, + num_anchors=self.num_anchors, + loss_objective=self.loss_objective, + dpace_alpha=self.dpace_alpha, + loss_decay_gamma=self.loss_decay_gamma, + ce_loss_alpha=self.ce_loss_alpha, + l1_loss_alpha=self.l1_loss_alpha, + deterministic_anchor_sampling=getattr( + self.args, "deterministic_anchor_sampling", False + ), + anchor_seed=getattr(self.args, "seed", 0), + anchor_sampling_scope=getattr(self.args, "anchor_sampling_scope", "row"), + attention_backend=getattr(self.args, "attention_backend", "flex_attention"), + draft_context_parallel_size=getattr( + self.args, "draft_context_parallel_size", 1 + ), + ) + self._anchor_slot_offset = wrapper.prediction_start + return wrapper + + def _model_forward_kwargs(self) -> dict: + return { + "global_step": self._dspine_step, + "total_steps": self._dspine_total_steps, + "alignment_ce": self._window_alignment_ce, + } + + def _alignment_weight(self) -> float: + config = getattr(getattr(self, "draft_model", None), "config", None) + options = getattr(config, "dspine_config", None) or {} + return float(options.get("alignment_weight", 0.0)) + + def _prepass_anchor_seed(self, step, batch_idx): + if not getattr(self.args, "deterministic_anchor_sampling", False): + return None + return anchor_sampling_seed( + getattr(self.args, "seed", 0), step, batch_idx, self.dp_rank + ) + + def _prepare_train_window(self, batches, step: int, num_batches: int): + batches = list(batches) + if len(batches) != num_batches: + raise RuntimeError( + f"training step {step} prepared {len(batches)} microbatches; " + f"expected {num_batches}" + ) + self._dspine_step = int(step) + self._window_alignment_ce = None + if self._alignment_weight() <= 0: + return batches + + cpu_rng = torch.get_rng_state() + cuda_rng = ( + torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None + ) + ce_sum = None + denominator_sum = None + try: + with torch.no_grad(): + for batch_idx, batch in enumerate(batches): + result = self._forward( + batch, anchor_seed=self._prepass_anchor_seed(step, batch_idx) + ) + ce, denominator = result[5]["dspine/backbone_ce"] + ce = ce.detach() + denominator = denominator.detach() + ce_sum = ce if ce_sum is None else ce_sum + ce + denominator_sum = ( + denominator + if denominator_sum is None + else denominator_sum + denominator + ) + finally: + torch.set_rng_state(cpu_rng) + if cuda_rng is not None: + torch.cuda.set_rng_state_all(cuda_rng) + + if ce_sum is None or denominator_sum is None: + raise RuntimeError("DSpine alignment prepass produced no microbatches") + safe_denominator = denominator_sum.where( + denominator_sum > 0, torch.ones_like(denominator_sum) + ) + self._window_alignment_ce = (ce_sum / safe_denominator).detach() + return batches + + def _train_step(self, batch, accumulation_steps, step, batch_idx, num_batches): + self._dspine_step = int(step) + result = super()._train_step( + batch=batch, + accumulation_steps=accumulation_steps, + step=step, + batch_idx=batch_idx, + num_batches=num_batches, + ) + if batch_idx == num_batches - 1: + self._window_alignment_ce = None + return result diff --git a/aspec/training/trainer.py b/aspec/training/trainer.py index f4eb9d9..dd6e7cc 100644 --- a/aspec/training/trainer.py +++ b/aspec/training/trainer.py @@ -681,7 +681,10 @@ def _train_core_from_queue(self, step: int, num_batches: int) -> dict: _set_grad_sync = getattr(_model, "set_requires_gradient_sync", None) _no_sync = getattr(_model, "no_sync", None) if _set_grad_sync is None else None - batches = self.prof.iterate_train_actor(self._iter_batches_from_queue(num_batches)) + batches = self._prepare_train_window( + self._iter_batches_from_queue(num_batches), step, num_batches + ) + batches = self.prof.iterate_train_actor(batches) for batch_idx, batch in enumerate(batches): is_last = batch_idx == num_batches - 1 work_items = batch.pop("_aspec_work", None) @@ -777,6 +780,10 @@ def _train_core_from_queue(self, step: int, num_batches: int) -> dict: def _iter_batches_from_queue(self, num_batches: int): yield from itertools.islice(self.data_fetcher, num_batches) + def _prepare_train_window(self, batches, step: int, num_batches: int): + """Hook for trainers that need to inspect an accumulation window first.""" + return batches + # ------------------------------------------------------------------ # Checkpointing & persistence # ------------------------------------------------------------------ diff --git a/aspec/training/trainer_actor.py b/aspec/training/trainer_actor.py index 4f7df89..1d9b41d 100644 --- a/aspec/training/trainer_actor.py +++ b/aspec/training/trainer_actor.py @@ -56,6 +56,10 @@ def _trainer_class_for_config(draft_model_config): from aspec.training.domino_trainer import DominoTrainer return DominoTrainer + if getattr(draft_model_config, "architectures", None) == ["DSpineDraftModel"]: + from aspec.training.dspine_trainer import DSpineTrainer + + return DSpineTrainer if getattr(draft_model_config, "architectures", None) == ["JetSpecDraftModel"]: from aspec.training.jetspec_trainer import JetSpecTrainer @@ -79,7 +83,7 @@ def _trainer_class_for_config(draft_model_config): return Eagle3Trainer raise ValueError( - "ASpec supports DSpark, DFlash, Domino, JetSpec, EAGLE3, native MTP and Medusa draft model configs; " + "ASpec supports DSpark, DFlash, Domino, DSpine, JetSpec, EAGLE3, native MTP and Medusa draft model configs; " f"got {type(draft_model_config).__name__}" ) diff --git a/configs/examples/dspine_qwen3_8b_4k_tcp.yaml b/configs/examples/dspine_qwen3_8b_4k_tcp.yaml new file mode 100644 index 0000000..edfc136 --- /dev/null +++ b/configs/examples/dspine_qwen3_8b_4k_tcp.yaml @@ -0,0 +1,92 @@ +# Supplementary configuration example; see the support matrix for supported workflows. +# Single-node DSpine on a frozen Qwen3-8B Target: one Target GPU plus two Draft GPUs, +# 4K, CP1, no packing, FlexAttention, Store/TCP transport (no NVLink). This is a +# functional smoke test, not evidence of convergence, acceptance or decoding quality. + +model: + target_model_path: ${oc.env:ASPEC_TARGET_MODEL} + native_context_length: 32768 + trust_remote_code: false + draft_model_config: aspec/config/dspine_qwen3_8b_draft_config.json + +dataset: + train_data_path: ../../examples/data/sample_conversations.jsonl + eval_data_path: null + chat_template: qwen3-instruct + min_loss_tokens: 32 + shuffle_dataset: false + +training: + attention_backend: flex_attention + draft_context_parallel_size: 1 + micro_batch_size: 1 + draft_accumulation_steps: 4 + learning_rate: 6e-4 + min_lr: 6e-5 + weight_decay: 0.0 + max_concurrent_batches: 1 + streaming_dispatch_with_training: true + pipeline_dispatch_with_training: true + max_grad_norm: 1.0 + max_seq_length: 4096 + num_epochs: 100 + num_train_steps: 8 + lr_total_steps: 8 + seed: 42 + training_num_gpus_per_node: 2 + training_num_nodes: 1 + placement_strategy: inference_first + fsdp_strategy: REPLICATE + fsdp_reduce_dtype: bfloat16 + prefetch_depth: 1 + save_interval: 0 + save_per_epoch: false + save_final_checkpoint: true + warmup_ratio: 0.04 + dflash_packing: false + dflash_block_size: 16 + dflash_num_target_layers: 5 + dflash_num_anchors: 128 + dflash_loss_objective: decay + dflash_ce_loss_alpha: 1.0 + dflash_l1_loss_alpha: 0.0 + gradient_checkpointing: true + +inference: + inference_engine_type: sgl + store_last_hidden_states: true + target_prefill_memory_optimized: false + inference_num_gpus: 1 + inference_num_gpus_per_engine: 1 + inference_num_gpus_per_node: 2 + inference_fetch_batch: 8 + inference_buffer_threshold: 2 + max_sample_pool_size: 12 + inference_batch_size: 2 + sglang: + tp_size: 1 + mem_fraction_static: 0.5 + +mooncake: + master_server_address: null + metadata_server: null + data_plane: store + protocol: tcp + enable_gpu_direct: false + allow_host_fallback: false + global_segment_size: 32GB + local_buffer_size: 8GB + host_buffer_size: 1GB + async_put_pool_size: 1 + enable_hard_pin: true + max_seq_len: 4096 + hidden_dim: 4096 + +logging: + report_to: none + +debug: + enable_perf_metrics: true + +output_dir: outputs/dspine_qwen3_8b_4k_tcp +cache_dir: cache/dspine_qwen3_8b_4k_tcp diff --git a/docs/support.md b/docs/support.md index 23a3fc7..3f6a538 100644 --- a/docs/support.md +++ b/docs/support.md @@ -13,7 +13,7 @@ and tests do not imply CPU training support. | EAGLE3 | Recurrent TTT, full/pruned vocabulary, GQA/MHA or materialized MLA; FA4 packing/CP | No EAGLE3 MoE, anchored mode or whole-model compile | | P-EAGLE core | Qwen3 full-vocabulary parallel model/loss, deterministic dense slots, eager/SDPA | Model/loss prerequisite only; no public trainer, COD sampler, resume, export or consumer validation; see [scope](user-guide/peagle.md) | | Domino | DFlash block backbone plus GRU causal correction head, mixed backbone/corrected CE, both documented label layouts; training, `lambda_base` curriculum, held-out corrected/backbone observations and exact recovery with FlexAttention, CP1, padded/non-packing | No packed/CP>1, MoE, sparse attention or MTP conditioning; SGLang/native export, strict reload, proposal consumer, a bounded SpecForge comparison and bounded SGLang decode acceptance are validated; harder data, longer convergence and a formal anchor-replay training mode remain pending; see [scope](user-guide/domino.md) | -| DSpine | DFlash block backbone plus adjacent-token injection, persistent transfer codes, last-write refinement and alignment/refinement objectives; dense full attention, padded, CP1, non-packing | Model/loss prerequisite only; no public trainer, exact-resume, recipe, export or consumer/acceptance validation; see [scope](user-guide/dspine.md) | +| DSpine | DFlash block backbone plus adjacent-token injection, persistent transfer codes, last-write refinement and alignment/refinement objectives; training, Plan, accumulation-window replay and exact recovery with FlexAttention, CP1, padded/non-packing | No recipe, export, consumer/acceptance or bounded SpecForge comparison yet; see [scope](user-guide/dspine.md) | | Medusa heads-only | Parallel full-vocabulary future-token heads on the frozen Target post-norm state; training, exact recovery and native export; greedy and typical/nucleus sampling candidate-tree acceptance via a standalone Hugging Face evaluator; SDPA CP1, MBS1, non-packing, REPLICATE, one node | No packing/CP or warmstart; no SGLang Medusa integration or production-serving claim; see [scope](user-guide/medusa.md) | | EAGLE4 | Dense and selected upstream MoE; Draft/candidate stages; packing/CP and native assets | Candidate Top-K forward-KL is explicitly implemented from public semantics, not an unpublished official recipe; no serving integration | | DFlash2 | Experimental full/causal/SWA training with Flex, cuDNN THD or FA4 packing/CP | Experimental objective; no claim to reproduce an official training recipe | diff --git a/docs/user-guide/algorithms.md b/docs/user-guide/algorithms.md index 1e35841..24275a0 100644 --- a/docs/user-guide/algorithms.md +++ b/docs/user-guide/algorithms.md @@ -76,13 +76,16 @@ promotion, Target bindings and consumer/acceptance validation remain pending. ## DSpine -The [DSpine model/loss API](dspine.md) adds adjacent-token injection, persistent -transfer codes and last-write candidate refinement on the retained DFlash block -backbone. The objective combines backbone CE/L1, refinement CE/L1 and a -transfer-code alignment term with an explicit warmup/replacement schedule. This -increment is model/loss only: dense full attention, padded inputs, CP1 and -non-packing. Trainer, recipe, exact resume, export and consumer/acceptance -validation remain pending. +The [DSpine API](dspine.md) adds adjacent-token injection, persistent transfer +codes and last-write candidate refinement on the retained DFlash block backbone. +The objective combines backbone CE/L1, microbatch-finalized refinement CE/L1 and +a transfer-code alignment term with an explicit warmup/replacement schedule. +Training replays each accumulation window without gradients to pool one detached +`alignment_ce`, restores the RNG state, then runs the real forward/backward over +the same microbatches. Scope is dense full attention, FlexAttention, padded +inputs, CP1 and non-packing; Plan and exact resume pin the DSpine objective and +config. A runnable recipe, export, consumer/acceptance validation and a bounded +SpecForge comparison remain pending. ## EAGLE4: two stages diff --git a/docs/user-guide/dspine.md b/docs/user-guide/dspine.md index 2ce10f4..a34837d 100644 --- a/docs/user-guide/dspine.md +++ b/docs/user-guide/dspine.md @@ -1,10 +1,9 @@ -# DSpine Draft model and objective +# DSpine Draft training -This is the model/loss prerequisite for [ASpec #37](https://github.com/inclusionAI/ASpec/issues/37). -It adds DSpine adjacent-token injection, persistent transfer codes and candidate -refinement on the retained DFlash block backbone. Trainer, recipe, exact resume, -export and serving are follow-ups; this page describes the tested model/loss scope -only. +DSpine adds adjacent-token injection, persistent transfer codes and candidate +refinement on the retained DFlash block backbone. ASpec now supports the +model/objective, Plan compilation, the trainer and exact resume. Recipes, +native export, proposal consumers and serving acceptance remain follow-ups. ## References @@ -22,9 +21,10 @@ only. ## Selected scope -The first implementation targets one dense full-attention DFlash backbone such as -Qwen3-8B with padded inputs, `draft_context_parallel_size=1` and no packing. Native -MTP conditioning, MoE FFNs, sparse attention, packed documents and CP>1 fail closed. +Training targets one dense full-attention DFlash backbone such as Qwen3-8B with +padded inputs, `draft_context_parallel_size=1`, FlexAttention and no packing. +Native MTP conditioning, MoE FFNs, sparse attention, packed documents, CP>1, +SDPA/FA4/cuDNN training and whole-model compile fail closed at Plan time. ## Components @@ -40,19 +40,48 @@ MTP conditioning, MoE FFNs, sparse attention, packed documents and CP>1 fail clo rescoring. - `DSpineModel` reuses ASpec anchor sampling, block masks, Target features and DFlash reductions. It adds backbone CE/L1, candidate refinement CE/L1, transfer-code - alignment, the alignment warmup and the predecessor-replacement schedule. + alignment, the alignment warmup and the predecessor-replacement schedule. It + always consumes the Target post-norm state for the teacher distribution. +- `DSpineTrainer` reuses the DFlash optimizer/checkpoint path and adds the + accumulation-window replay described below. -The current objective is dense full attention, padded, CP1, non-packing. The -trainer-side accumulation replay and exact-resume contract are not part of this -increment. +## Training and exact resume + +The example config is `configs/examples/dspine_qwen3_8b_4k_tcp.yaml` with +`aspec/config/dspine_qwen3_8b_draft_config.json`. Plan records the DSpine +objective, the full `dspine_config` block and the Target feature contract before +backend startup. + +The objective follows SpecForge #1038: + +- backbone and refinement terms are finalized per microbatch; refinement CE/L1 + use microbatch-wide eligible means and are not pooled across microbatches; +- one detached backbone-CE coefficient (`alignment_ce`) is shared by every + microbatch in an optimizer window. The trainer runs a no-grad prepass over the + window, pools `sum(backbone_ce) / sum(token_weight)`, restores the CPU/CUDA RNG + state, then replays the same microbatches with gradients; +- the replay sums microbatch numerators and divides by the total sequence count, + matching the DFlash accumulation contract. + +Checkpoint topology pins the algorithm (`dspine`), `block_size`, loss/weighting +parameters and the whole `dspine_config` block, including the transfer rank, +top-k width, warmup and replacement schedule. Exact resume requires that complete +topology and the RNG state; changing any of those fields requires +`continual_training=true` for a weights-only new stage. ## Validation and limits -`tests/cpu/test_dspine.py` covers configuration fail-closed cases, transfer-space -initialization, finite forward/backward, adjacent-injection causality and packed-input -rejection. CPU numerical contracts do not establish Qwen3-8B convergence, GPU -throughput or decoding acceptance. +`tests/cpu/test_dspine.py` covers the model/loss contracts and +`tests/cpu/test_dspine_integration.py` covers registration, Plan fail-closed, +trainer dispatch, the window replay (shared coefficient and RNG restoration) and +exact-resume topology. + +A tiny two-layer CUDA bf16 FlexAttention smoke exercises the trainer replay path: +the prepass pools a finite alignment coefficient, the replay produces finite +gradients on all trainable parameters, and the RNG state is unchanged across the +prepass/replay boundary. This is a functional smoke, not convergence, throughput, +SpecForge parity or decoding acceptance. The published DSpine checkpoint layout uses a `dflash_config` code bridge and a -serving-specific candidate sampler. Mapping those fields, trainer wiring, export, +serving-specific candidate sampler. A runnable recipe, native export, proposal consumer/acceptance and a bounded SpecForge comparison are follow-up work. diff --git a/tests/cpu/test_dspine_integration.py b/tests/cpu/test_dspine_integration.py new file mode 100644 index 0000000..716e049 --- /dev/null +++ b/tests/cpu/test_dspine_integration.py @@ -0,0 +1,296 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""DSpine integration contracts: registration, Plan, dispatch, replay and resume.""" + +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch + +from aspec.config.draft_algorithm import draft_model_semantics, resolve_draft_algorithm +from aspec.config.train_config import load_config +from aspec.models.draft.auto import AutoDraftModelConfig, AutoEagle3DraftModel +from aspec.models.draft.dspine import DSpineConfig, DSpineDraftModel +from aspec.models.dspine import DSpineModel +from aspec.planning import ( + PlanCompileError, + _load_draft_descriptor, + _runtime_values, + compile_execution_plan, +) +from aspec.training.checkpoint import ( + _logical_training_topology, + _validate_exact_resume_topology, +) +from aspec.training.dflash_trainer import DFlashTrainer +from aspec.training.dspine_trainer import DSpineTrainer +from aspec.training.trainer_actor import _trainer_class_for_config + +_REPO_ROOT = Path(__file__).parents[2] +_EXAMPLE = _REPO_ROOT / "configs" / "examples" / "dspine_qwen3_8b_4k_tcp.yaml" +_DRAFT_JSON = _REPO_ROOT / "aspec" / "config" / "dspine_qwen3_8b_draft_config.json" + +_ILLEGAL_OVERRIDES = [ + ("training.dflash_packing=true", PlanCompileError), + ("training.draft_context_parallel_size=2", NotImplementedError), + ("training.attention_backend=sdpa", PlanCompileError), + ("training.attention_backend=fa4", PlanCompileError), + ("training.attention_backend=cudnn_flex_attention", PlanCompileError), + ("training.compile_model=true", PlanCompileError), + ("training.dflash_loss_objective=dpace", PlanCompileError), + ("training.dflash_ce_loss_alpha=0.5", PlanCompileError), + ("training.dflash_l1_loss_alpha=0.1", PlanCompileError), + ("training.dflash_block_size=8", PlanCompileError), + ("inference.store_last_hidden_states=false", PlanCompileError), +] + + +def _tiny_config(**overrides): + raw = dict( + architectures=["DSpineDraftModel"], model_type="dspine", + hidden_size=16, intermediate_size=32, num_hidden_layers=1, + num_attention_heads=2, num_key_value_heads=1, head_dim=8, vocab_size=32, + target_hidden_size=16, target_num_hidden_layers=4, target_layer_ids=[1], + num_target_layers=1, mask_token_id=31, max_position_embeddings=128, + block_size=5, is_causal=True, + dspine_config={ + "transfer_rank": 8, + "message_size": 8, + "top_k": 4, + "alignment_warmup_steps": 0, + "replacement_layers": 1, + "replacement_probability": 0.0, + }, + ) + raw.update(overrides) + return AutoDraftModelConfig.from_dict(raw) + + +def _fake_qwen_target(tmp_path): + target = tmp_path / "Qwen3-8B-test" + target.mkdir() + (target / "config.json").write_text(json.dumps({ + "model_type": "qwen3", + "architectures": ["Qwen3ForCausalLM"], + "hidden_size": 4096, + "vocab_size": 151936, + "num_hidden_layers": 36, + "max_position_embeddings": 40960, + }), encoding="utf-8") + return target + + +def _config(tmp_path, *overrides): + args = [f"model.target_model_path={_fake_qwen_target(tmp_path)}", *overrides] + return load_config(config_path=str(_EXAMPLE), cli_args=args), args + + +def test_registration_resolves_dspine(): + assert resolve_draft_algorithm({"architectures": ["DSpineDraftModel"]}) == "dspine" + shipped = AutoDraftModelConfig.from_file(str(_DRAFT_JSON)) + assert isinstance(shipped, DSpineConfig) + assert shipped.block_size == 16 + assert shipped.is_causal is True + assert shipped.target_layer_ids == [1, 9, 17, 25, 33] + assert shipped.dspine_config["top_k"] == 16 + + tiny = _tiny_config() + model = AutoEagle3DraftModel.from_config(tiny) + assert isinstance(model, DSpineDraftModel) + assert _trainer_class_for_config(tiny) is DSpineTrainer + semantics = draft_model_semantics(tiny) + assert semantics["architectures"] == ["DSpineDraftModel"] + assert semantics["is_causal"] is True + assert semantics["block_size"] == 5 + assert semantics["dspine_config"]["transfer_rank"] == 8 + + +def test_plan_compiles_with_dspine_objective(tmp_path): + config, args = _config(tmp_path) + plan = compile_execution_plan(config, config_path=str(_EXAMPLE), cli_args=args).to_dict() + draft = plan["workload"]["models"]["draft"] + assert draft["family"] == "dspine" + objective = plan["workload"]["objective"] + assert objective["loss"] == "dspine_backbone_refinement_alignment" + assert objective["block_size"] == 16 + assert objective["prediction_start"] == 1 + assert objective["teacher_feature"] == "last_hidden_states" + assert objective["ce_loss_alpha"] == 1.0 + assert objective["l1_loss_alpha"] == 0.0 + assert objective["frozen_parts"] == ["target_lm_head"] + assert objective["dspine"]["transfer_rank"] == 1024 + features = plan["workload"]["features"] + assert features["aux_hidden_state_layers"] == [1, 9, 17, 25, 33] + assert "last_hidden_states" in features["tensors"] + attention = next( + item for item in plan["capabilities"] if item["name"] == "draft_attention_execution" + ) + assert attention["requirement"] == "required" + + runtime = _runtime_values(config, _load_draft_descriptor(config)) + assert runtime["draft_algorithm"] == "dspine" + assert runtime["dflash_ce_loss_alpha"] == 1.0 + assert runtime["dflash_l1_loss_alpha"] == 0.0 + + +@pytest.mark.parametrize("override, error", _ILLEGAL_OVERRIDES) +def test_plan_rejects_unsupported_dspine_combinations(tmp_path, override, error): + target = f"model.target_model_path={_fake_qwen_target(tmp_path)}" + args = [target, override] + with pytest.raises(error): + config = load_config(config_path=str(_EXAMPLE), cli_args=args) + compile_execution_plan(config, config_path=str(_EXAMPLE), cli_args=args) + + +def _trainer_args(): + return SimpleNamespace( + draft_algorithm="dspine", draft_model_config_obj=_tiny_config(), world_size=2, + dflash_block_size=5, dflash_num_anchors=2, dflash_num_target_layers=1, + dflash_loss_objective="decay", dflash_dpace_alpha=0.5, + dflash_loss_decay_gamma=7.0, dflash_ce_loss_alpha=1.0, dflash_l1_loss_alpha=0.0, + anchor_sampling_scope="row", deterministic_anchor_sampling=False, + max_seq_length=128, micro_batch_size=1, draft_accumulation_steps=1, + max_grad_norm=1.0, seed=42, draft_context_parallel_size=1, + training_num_nodes=1, training_num_gpus_per_node=2, + attention_backend="flex_attention", fsdp_strategy="REPLICATE", + sp_ulysses_size=1, sp_ring_size=1, lr_total_steps=100, num_train_steps=8, + ) + + +def _mount_trainer(monkeypatch, args): + def base_init(self, args): + self.args = args + self.block_size = args.dflash_block_size + self.num_anchors = args.dflash_num_anchors + self.num_target_layers = args.dflash_num_target_layers + self.loss_objective = args.dflash_loss_objective + self.dpace_alpha = args.dflash_dpace_alpha + self.loss_decay_gamma = args.dflash_loss_decay_gamma + self.ce_loss_alpha = args.dflash_ce_loss_alpha + self.l1_loss_alpha = args.dflash_l1_loss_alpha + self.dp_rank = 0 + self._anchor_slot_offset = 1 + + monkeypatch.setattr(DFlashTrainer, "__init__", base_init) + return DSpineTrainer(args) + + +def test_trainer_constructor_propagates_dspine_objective(monkeypatch): + args = _trainer_args() + trainer = _mount_trainer(monkeypatch, args) + wrapper = trainer._build_training_wrapper(DSpineDraftModel(_tiny_config())) + assert isinstance(wrapper, DSpineModel) + assert wrapper.block_size == 5 + assert wrapper.loss_decay_gamma == 7.0 + assert wrapper.uses_target_hidden_states is True + assert trainer._anchor_slot_offset == wrapper.prediction_start + + objective = _logical_training_topology(args, 2)["training_objective"] + assert objective["loss"] == "dspine_backbone_refinement_alignment" + assert objective["dspine"]["transfer_rank"] == 8 + + trainer.block_size = 4 + with pytest.raises(ValueError, match="block_size"): + trainer._build_draft_model(_tiny_config()) + trainer.block_size = 5 + trainer.num_target_layers = 2 + with pytest.raises(ValueError, match="num_target_layers"): + trainer._build_draft_model(_tiny_config()) + + +def test_alignment_prepass_pools_window_and_restores_rng(monkeypatch): + trainer = _mount_trainer(monkeypatch, _trainer_args()) + trainer.draft_model = SimpleNamespace( + config=SimpleNamespace(dspine_config={"alignment_weight": 0.5}) + ) + ce_values = iter([2.0, 3.0]) + denominators = iter([4.0, 6.0]) + calls = [] + + def fake_forward(batch, *, anchor_seed=None): + calls.append((torch.is_grad_enabled(), anchor_seed)) + torch.rand(1) + return ( + None, None, None, None, None, + {"dspine/backbone_ce": ( + torch.tensor(next(ce_values)), + torch.tensor(next(denominators)), + )}, + None, + ) + + trainer._forward = fake_forward + batches = [{"row": 0}, {"row": 1}] + torch.manual_seed(7) + before = torch.get_rng_state().clone() + prepared = trainer._prepare_train_window(iter(batches), step=5, num_batches=2) + assert prepared == batches + torch.testing.assert_close(torch.get_rng_state(), before) + assert all(not grad for grad, _ in calls) + torch.testing.assert_close( + trainer._window_alignment_ce, torch.tensor((2.0 + 3.0) / (4.0 + 6.0)) + ) + kwargs = trainer._model_forward_kwargs() + assert kwargs["global_step"] == 5 + assert kwargs["total_steps"] == 100 + torch.testing.assert_close(kwargs["alignment_ce"], trainer._window_alignment_ce) + + +def test_alignment_prepass_is_skipped_without_alignment_weight(monkeypatch): + trainer = _mount_trainer(monkeypatch, _trainer_args()) + trainer.draft_model = SimpleNamespace( + config=SimpleNamespace(dspine_config={"alignment_weight": 0.0}) + ) + calls = [] + trainer._forward = lambda *args, **kwargs: calls.append(args) + batches = [{"row": 0}] + assert trainer._prepare_train_window(iter(batches), step=0, num_batches=1) == batches + assert not calls + assert trainer._window_alignment_ce is None + + +@pytest.mark.parametrize( + "missing", + ["empty", "dspine", "loss", "is_causal", "dspine_config"], +) +def test_exact_resume_rejects_incomplete_dspine_topology(missing): + args = _trainer_args() + topology = json.loads(json.dumps(_logical_training_topology(args, 2))) + if missing == "empty": + topology = {} + elif missing in {"dspine", "loss"}: + del topology["training_objective"][missing] + else: + del topology["draft_model_semantics"][missing] + with pytest.raises(RuntimeError, match="complete DSpine training_topology"): + _validate_exact_resume_topology( + args, {"world_size": 2, "training_topology": topology} + ) + + +def test_exact_resume_requires_topology_for_dspine(): + args = _trainer_args() + with pytest.raises(RuntimeError, match="training_topology for DSpine"): + _validate_exact_resume_topology(args, {"world_size": 2}) + + +def test_checkpoint_topology_pins_dspine_objective(): + args = _trainer_args() + current = _logical_training_topology(args, 2) + objective = current["training_objective"] + assert objective["loss"] == "dspine_backbone_refinement_alignment" + assert objective["dspine"]["alignment_weight"] == 0.5 + assert objective["block_size"] == 5 + assert objective["loss_decay_gamma"] == 7.0 + assert current["draft_model_semantics"]["is_causal"] is True + assert current["draft_model_semantics"]["dspine_config"]["transfer_rank"] == 8 + + metadata = {"world_size": 2, "training_topology": json.loads(json.dumps(current))} + _validate_exact_resume_topology(args, metadata) + changed = json.loads(json.dumps(metadata)) + changed["training_topology"]["training_objective"]["dspine"]["transfer_rank"] = 4 + with pytest.raises(RuntimeError): + _validate_exact_resume_topology(args, changed) From 548cc6344144ed6a543a2ade28e48e3560681c3b Mon Sep 17 00:00:00 2001 From: Zijun Li <3335126979@qq.com> Date: Fri, 4 Dec 2026 11:52:15 +0800 Subject: [PATCH 2/5] fix(dspine): harden transfer init, resume horizon and window leases - sync lazily initialized transfer readouts into the BF16 fp32 masters after the first forward so the first optimizer step cannot overwrite them - record the effective DSpine schedule horizon in checkpoint topology and require it on exact resume - copy leased microbatches out of the destination ring and release the leases while materializing the accumulation window, avoiding a deadlock when the window exceeds the ring depth - reject Plan configs whose draft hidden width differs from the Target hidden width before backend startup - count the alignment prepass in forward/compute timing and keep queue-fetch time separate --- aspec/planning.py | 5 ++ aspec/training/checkpoint.py | 9 ++- aspec/training/dspine_trainer.py | 84 +++++++++++++++++++++++++++- aspec/training/trainer.py | 17 +++++- tests/cpu/test_dspine_integration.py | 63 ++++++++++++++++++++- 5 files changed, 172 insertions(+), 6 deletions(-) diff --git a/aspec/planning.py b/aspec/planning.py index a5f49c1..8261ce5 100644 --- a/aspec/planning.py +++ b/aspec/planning.py @@ -536,6 +536,11 @@ def _load_draft_descriptor(config: DictConfig) -> dict[str, Any]: raise PlanCompileError( "DSpine block_size must match training.dflash_block_size" ) + if raw["hidden_size"] != raw.get("target_hidden_size"): + raise PlanCompileError( + "DSpine requires hidden_size == target_hidden_size so the " + "Target output head can initialize the transfer space" + ) if raw.get("cudnn_gqa_mode", "auto") != "auto": raise PlanCompileError( "DSpine requires cudnn_gqa_mode=auto; the FlexAttention mask " diff --git a/aspec/training/checkpoint.py b/aspec/training/checkpoint.py index b972fb9..3e28552 100644 --- a/aspec/training/checkpoint.py +++ b/aspec/training/checkpoint.py @@ -154,6 +154,11 @@ def _logical_training_topology(args: Any, world_size: int) -> dict[str, Any]: options = dict(getattr(config, "dspine_config", {}) or {}) topology["training_objective"]["dspine"] = options topology["training_objective"]["alignment_ce"] = "window_backbone_ce" + topology["training_objective"]["dspine_total_steps"] = int( + getattr(args, "lr_total_steps", None) + or getattr(args, "num_train_steps", None) + or 0 + ) if "training_objective" in topology: fields = ("max_seq_length", "micro_batch_size", "draft_accumulation_steps", "max_grad_norm", "seed") @@ -326,8 +331,8 @@ def _validate_exact_resume_topology(args: Any, metadata: dict[str, Any], *, chec semantics = saved_topology.get("draft_model_semantics") or {} missing = [ key for key in ( - "dspine", "block_size", "loss", "loss_decay_gamma", - "ce_loss_alpha", "l1_loss_alpha", + "dspine", "dspine_total_steps", "block_size", "loss", + "loss_decay_gamma", "ce_loss_alpha", "l1_loss_alpha", ) if key not in objective ] diff --git a/aspec/training/dspine_trainer.py b/aspec/training/dspine_trainer.py index f715a7e..db1e417 100644 --- a/aspec/training/dspine_trainer.py +++ b/aspec/training/dspine_trainer.py @@ -16,6 +16,7 @@ from aspec.models.draft.dspine import DSpineConfig, DSpineDraftModel from aspec.models.dspine import DSpineModel from aspec.models.ops.anchors import anchor_sampling_seed +from aspec.training.data_fetcher import _take_p2p_receive_leases from aspec.training.dflash_trainer import DFlashTrainer @@ -34,6 +35,7 @@ def __init__(self, args): or 0 ) self._window_alignment_ce = None + self._transfer_masters_synced = None if self.ce_loss_alpha != 1.0 or self.l1_loss_alpha != 0.0: raise ValueError( "DSpine replaces the CE/L1 mix with its own objective; set " @@ -42,6 +44,67 @@ def __init__(self, args): if self.loss_objective != "decay": raise ValueError("DSpine supports the decay weighting objective only") + def _sync_transfer_masters(self) -> None: + """Mirror the lazily initialized readouts into the BF16 fp32 masters. + + ``BF16Optimizer`` clones the trainable parameters when it is built and + copies the fp32 masters back into the model on every step. Because the + transfer space is initialized by the first forward, the first step + would otherwise overwrite the new readout directions. + """ + draft = getattr(self, "draft_model", None) + optimizer = getattr(self, "optimizer", None) + params = getattr(optimizer, "model_params", None) + masters = getattr(optimizer, "fp32_params", None) + if draft is None or not params or not masters: + return + mapping = {id(parameter): master for parameter, master in zip(params, masters)} + with torch.no_grad(): + for readout in draft.injection.readouts: + master = mapping.get(id(readout.weight)) + if master is not None: + master.copy_(readout.weight.detach().float()) + + def _forward(self, batch, *, anchor_seed=None): + if self._transfer_masters_synced is None: + # A resumed checkpoint already carries initialized readouts and + # optimizer masters; never copy model values over loaded state. + self._transfer_masters_synced = bool(self.draft_model.transfer_ready) + result = super()._forward(batch, anchor_seed=anchor_seed) + if not self._transfer_masters_synced and bool(self.draft_model.transfer_ready): + self._sync_transfer_masters() + self._transfer_masters_synced = True + return result + + @staticmethod + def _clone_window_value(value): + if torch.is_tensor(value): + return value.clone() + if isinstance(value, dict): + return { + key: DSpineTrainer._clone_window_value(item) + for key, item in value.items() + } + if isinstance(value, list): + return [DSpineTrainer._clone_window_value(item) for item in value] + if isinstance(value, tuple): + return tuple(DSpineTrainer._clone_window_value(item) for item in value) + return value + + def _materialize_train_window(self, batches): + """Copy leased microbatches and release their ring slots immediately.""" + materialized = [] + for batch in batches: + leases = _take_p2p_receive_leases(batch) + if leases: + try: + batch = self._clone_window_value(batch) + finally: + for lease in leases: + lease.release() + materialized.append(batch) + return materialized + def _build_draft_model(self, config): if config.block_size != self.block_size: raise ValueError( @@ -99,7 +162,7 @@ def _prepass_anchor_seed(self, step, batch_idx): ) def _prepare_train_window(self, batches, step: int, num_batches: int): - batches = list(batches) + batches = self._materialize_train_window(batches) if len(batches) != num_batches: raise RuntimeError( f"training step {step} prepared {len(batches)} microbatches; " @@ -107,9 +170,14 @@ def _prepare_train_window(self, batches, step: int, num_batches: int): ) self._dspine_step = int(step) self._window_alignment_ce = None + self._prepass_events = None if self._alignment_weight() <= 0: return batches + use_cuda = torch.cuda.is_available() + prepass_start = torch.cuda.Event(enable_timing=True) if use_cuda else None + if prepass_start is not None: + prepass_start.record() cpu_rng = torch.get_rng_state() cuda_rng = ( torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None @@ -142,8 +210,22 @@ def _prepare_train_window(self, batches, step: int, num_batches: int): denominator_sum > 0, torch.ones_like(denominator_sum) ) self._window_alignment_ce = (ce_sum / safe_denominator).detach() + if prepass_start is not None: + prepass_end = torch.cuda.Event(enable_timing=True) + prepass_end.record() + self._prepass_events = (prepass_start, prepass_end) return batches + def _aggregate_metrics(self, all_step_metrics, step, *, grad_norm=None): + metrics = super()._aggregate_metrics( + all_step_metrics, step, grad_norm=grad_norm + ) + prepass_seconds = float(getattr(self, "_window_prepass_seconds", 0.0) or 0.0) + if prepass_seconds > 0 and "perf/forward_time" in metrics: + metrics["perf/forward_time"] += prepass_seconds + metrics["perf/prepass_time"] = prepass_seconds + return metrics + def _train_step(self, batch, accumulation_steps, step, batch_idx, num_batches): self._dspine_step = int(step) result = super()._train_step( diff --git a/aspec/training/trainer.py b/aspec/training/trainer.py index dd6e7cc..56a6e5a 100644 --- a/aspec/training/trainer.py +++ b/aspec/training/trainer.py @@ -684,6 +684,16 @@ def _train_core_from_queue(self, step: int, num_batches: int) -> dict: batches = self._prepare_train_window( self._iter_batches_from_queue(num_batches), step, num_batches ) + prepass_events = getattr(self, "_prepass_events", None) + self._prepass_events = None + prepass_seconds = 0.0 + if prepass_events is not None: + prepass_seconds = ( + prepass_events[0].elapsed_time(prepass_events[1]) / 1000.0 + ) + self._window_prepass_seconds = prepass_seconds + if perf and prepass_events is not None: + compute_events.append(prepass_events) batches = self.prof.iterate_train_actor(batches) for batch_idx, batch in enumerate(batches): is_last = batch_idx == num_batches - 1 @@ -696,7 +706,12 @@ def _train_core_from_queue(self, step: int, num_batches: int) -> dict: step_execution_ids.extend(item["execution_id"] for item in work_items) if perf: - data_time += time.time() - t_data_start + elapsed = time.time() - t_data_start + if batch_idx == 0: + # Preparation (including any DSpine alignment prepass) is + # measured separately; keep queue-fetch time here. + elapsed = max(0.0, elapsed - prepass_seconds) + data_time += elapsed evt_start = torch.cuda.Event(enable_timing=True) evt_end = torch.cuda.Event(enable_timing=True) evt_start.record() diff --git a/tests/cpu/test_dspine_integration.py b/tests/cpu/test_dspine_integration.py index 716e049..8a5de24 100644 --- a/tests/cpu/test_dspine_integration.py +++ b/tests/cpu/test_dspine_integration.py @@ -136,6 +136,20 @@ def test_plan_compiles_with_dspine_objective(tmp_path): assert runtime["dflash_l1_loss_alpha"] == 0.0 +def test_plan_rejects_dspine_hidden_width_mismatch(tmp_path): + raw = json.loads(_DRAFT_JSON.read_text()) + raw["target_hidden_size"] = 2048 + config_path = tmp_path / "dspine_bad_hidden.json" + config_path.write_text(json.dumps(raw)) + args = [ + f"model.target_model_path={_fake_qwen_target(tmp_path)}", + f"model.draft_model_config={config_path}", + ] + with pytest.raises(PlanCompileError, match="hidden_size"): + config = load_config(config_path=str(_EXAMPLE), cli_args=args) + compile_execution_plan(config, config_path=str(_EXAMPLE), cli_args=args) + + @pytest.mark.parametrize("override, error", _ILLEGAL_OVERRIDES) def test_plan_rejects_unsupported_dspine_combinations(tmp_path, override, error): target = f"model.target_model_path={_fake_qwen_target(tmp_path)}" @@ -252,16 +266,56 @@ def test_alignment_prepass_is_skipped_without_alignment_weight(monkeypatch): assert trainer._window_alignment_ce is None +def test_transfer_space_syncs_optimizer_masters(monkeypatch): + trainer = _mount_trainer(monkeypatch, _trainer_args()) + weight = torch.nn.Parameter(torch.ones(2, 2)) + readout = SimpleNamespace(weight=weight) + master = torch.zeros(2, 2) + trainer.draft_model = SimpleNamespace( + transfer_ready=torch.ones(1, dtype=torch.bool), + injection=SimpleNamespace(readouts=[readout]), + ) + trainer.optimizer = SimpleNamespace( + model_params=[weight], fp32_params=[master] + ) + trainer._sync_transfer_masters() + torch.testing.assert_close(master, torch.ones(2, 2)) + + +def test_prepare_window_copies_leased_batches_and_releases(monkeypatch): + trainer = _mount_trainer(monkeypatch, _trainer_args()) + trainer.draft_model = SimpleNamespace( + config=SimpleNamespace(dspine_config={"alignment_weight": 0.0}) + ) + + class Lease: + def __init__(self): + self.released = False + + def release(self): + self.released = True + + lease = Lease() + tensor = torch.arange(4) + batch = {"tensor": tensor, "_mooncake_p2p_receive_lease": lease} + prepared = trainer._prepare_train_window(iter([batch]), step=0, num_batches=1) + assert lease.released is True + assert "_mooncake_p2p_receive_lease" not in batch + assert "_mooncake_p2p_receive_lease" not in prepared[0] + assert prepared[0]["tensor"].data_ptr() != tensor.data_ptr() + torch.testing.assert_close(prepared[0]["tensor"], tensor) + + @pytest.mark.parametrize( "missing", - ["empty", "dspine", "loss", "is_causal", "dspine_config"], + ["empty", "dspine", "dspine_total_steps", "loss", "is_causal", "dspine_config"], ) def test_exact_resume_rejects_incomplete_dspine_topology(missing): args = _trainer_args() topology = json.loads(json.dumps(_logical_training_topology(args, 2))) if missing == "empty": topology = {} - elif missing in {"dspine", "loss"}: + elif missing in {"dspine", "dspine_total_steps", "loss"}: del topology["training_objective"][missing] else: del topology["draft_model_semantics"][missing] @@ -283,6 +337,7 @@ def test_checkpoint_topology_pins_dspine_objective(): objective = current["training_objective"] assert objective["loss"] == "dspine_backbone_refinement_alignment" assert objective["dspine"]["alignment_weight"] == 0.5 + assert objective["dspine_total_steps"] == 100 assert objective["block_size"] == 5 assert objective["loss_decay_gamma"] == 7.0 assert current["draft_model_semantics"]["is_causal"] is True @@ -294,3 +349,7 @@ def test_checkpoint_topology_pins_dspine_objective(): changed["training_topology"]["training_objective"]["dspine"]["transfer_rank"] = 4 with pytest.raises(RuntimeError): _validate_exact_resume_topology(args, changed) + changed = json.loads(json.dumps(metadata)) + changed["training_topology"]["training_objective"]["dspine_total_steps"] = 50 + with pytest.raises(RuntimeError): + _validate_exact_resume_topology(args, changed) From fb86a8f8422021f6c3343a5808492e4b3de560b9 Mon Sep 17 00:00:00 2001 From: Zijun Li <3335126979@qq.com> Date: Fri, 4 Dec 2026 20:57:34 +0800 Subject: [PATCH 3/5] fix(dspine): address maintainer review on DP, metrics and FSDP - reduce the alignment window statistic across the DP group before dividing, so every rank replays with the same coefficient - log the optimized objective numerator/sequence count, register the dspine component keys and use the objective for train/eval avg_loss - treat DSpine as causal in the shared attention policy resolver - defer prepass event timing to the existing synchronized point so incomplete events cannot stop the first window - synchronize the clone stream before releasing ring leases - initialize the transfer space before the first forward and make the readout/code copies DTensor-aware for FSDP FULL_SHARD --- aspec/config/draft_attention.py | 1 + aspec/models/draft/dspine.py | 20 +++- aspec/models/dspine.py | 1 + aspec/training/dspine_trainer.py | 101 +++++++++++++++-- aspec/training/trainer.py | 35 +++--- tests/cpu/test_dspine.py | 1 + tests/cpu/test_dspine_integration.py | 155 +++++++++++++++++++++++++++ 7 files changed, 289 insertions(+), 25 deletions(-) diff --git a/aspec/config/draft_attention.py b/aspec/config/draft_attention.py index 52f3b04..0ad9434 100644 --- a/aspec/config/draft_attention.py +++ b/aspec/config/draft_attention.py @@ -421,6 +421,7 @@ def dsa_positive_integer(name: str, default: int) -> int: else kind == "sliding_attention") else "bidirectional" for kind in schedule ] if raw.get("architectures") == ["DFlash2DraftModel"] + else "causal" if raw.get("architectures") == ["DSpineDraftModel"] else "bidirectional" ), } diff --git a/aspec/models/draft/dspine.py b/aspec/models/draft/dspine.py index 113a761..fe3d2fd 100644 --- a/aspec/models/draft/dspine.py +++ b/aspec/models/draft/dspine.py @@ -81,6 +81,17 @@ def schedule(self, step: int, total_steps: int | None) -> tuple[float, float]: return beta, self.replacement_probability * min(max(fraction, 0), 1) +def _copy_into_tensor(target: torch.Tensor, value: torch.Tensor) -> None: + """Copy a replicated tensor into a possibly sharded DTensor target.""" + try: + from torch.distributed.tensor import DTensor, distribute_tensor + except ImportError: # pragma: no cover - older torch without DTensor + DTensor = None + if DTensor is not None and isinstance(target, DTensor): + value = distribute_tensor(value, target.device_mesh, target.placements) + target.copy_(value) + + class DSpineConfig(DFlashConfig): """DFlash backbone plus DSpine injection/refinement options.""" @@ -255,9 +266,14 @@ def initialize_transfer_space( / values.sqrt(), dim=-1, ) - self.transfer_codes[start : start + len(rows)].copy_(codes.to(self.transfer_codes.dtype)) + _copy_into_tensor( + self.transfer_codes[start : start + len(rows)], + codes.to(self.transfer_codes.dtype), + ) for readout in self.injection.readouts: - readout.weight.copy_(directions.T.to(readout.weight.dtype)) + _copy_into_tensor( + readout.weight, directions.T.to(readout.weight.dtype) + ) self.transfer_ready.fill_(True) def _require_transfer_ready(self) -> None: diff --git a/aspec/models/dspine.py b/aspec/models/dspine.py index 992dbaa..58efcf5 100644 --- a/aspec/models/dspine.py +++ b/aspec/models/dspine.py @@ -348,6 +348,7 @@ def forward( (proposal_weights.new_zeros(1), count_pp) ) components = { + "dspine/loss": (numerator.detach(), sequence_denominator), "dspine/backbone_ce": (ce.detach(), token_denominator.detach()), "dspine/backbone_l1": (l1.detach(), token_denominator.detach()), "dspine/refinement_ce": (ref_ce_sum.detach(), ref_ce_mass), diff --git a/aspec/training/dspine_trainer.py b/aspec/training/dspine_trainer.py index db1e417..3d2a628 100644 --- a/aspec/training/dspine_trainer.py +++ b/aspec/training/dspine_trainer.py @@ -12,11 +12,15 @@ """ import torch +import torch.distributed as dist from aspec.models.draft.dspine import DSpineConfig, DSpineDraftModel from aspec.models.dspine import DSpineModel from aspec.models.ops.anchors import anchor_sampling_seed -from aspec.training.data_fetcher import _take_p2p_receive_leases +from aspec.training.data_fetcher import ( + _synchronize_cuda_tensor_devices, + _take_p2p_receive_leases, +) from aspec.training.dflash_trainer import DFlashTrainer @@ -25,6 +29,19 @@ class DSpineTrainer(DFlashTrainer): _draft_config_class = DSpineConfig _anchor_slot_offset = 1 + _extra_loss_component_keys = [ + "dspine/loss", + "dspine/backbone_ce", + "dspine/backbone_l1", + "dspine/refinement_ce", + "dspine/refinement_l1", + "dspine/refinement_loss", + "dspine/refinement_ce_mean", + "dspine/refinement_l1_mean", + "dspine/alignment_loss", + "dspine/alignment_ce", + "dspine/replacement_probability", + ] def __init__(self, args): super().__init__(args) @@ -44,14 +61,41 @@ def __init__(self, args): if self.loss_objective != "decay": raise ValueError("DSpine supports the decay weighting objective only") - def _sync_transfer_masters(self) -> None: - """Mirror the lazily initialized readouts into the BF16 fp32 masters. + def init_model(self, draft_model_config, target_model_path, mooncake_config=None): + result = super().init_model( + draft_model_config, target_model_path, mooncake_config + ) + self._initialize_transfer_space_before_training() + return result + + def _initialize_transfer_space_before_training(self) -> None: + """Initialize the transfer space before any forward or optimizer step. ``BF16Optimizer`` clones the trainable parameters when it is built and - copies the fp32 masters back into the model on every step. Because the - transfer space is initialized by the first forward, the first step - would otherwise overwrite the new readout directions. + copies the fp32 masters back into the model on every step. FSDP2 also + swaps parameter objects around the first forward. Initializing here, + while the optimizer still owns these exact parameter objects, keeps + the readout directions in both the model and the fp32 masters. """ + draft = getattr(self, "draft_model", None) + if draft is None: + return + if bool(getattr(draft, "transfer_ready", False)): + # A resumed checkpoint already carries the initialized readouts + # and optimizer masters; never copy model values over loaded state. + self._transfer_masters_synced = True + return + head = getattr(self, "target_lm_head_weight", None) + if head is None: + raise ValueError( + "DSpine training requires the Target output head to initialize " + "the transfer space" + ) + draft.initialize_transfer_space(head) + self._sync_transfer_masters() + self._transfer_masters_synced = True + + def _sync_transfer_masters(self) -> None: draft = getattr(self, "draft_model", None) optimizer = getattr(self, "optimizer", None) params = getattr(optimizer, "model_params", None) @@ -67,11 +111,12 @@ def _sync_transfer_masters(self) -> None: def _forward(self, batch, *, anchor_seed=None): if self._transfer_masters_synced is None: - # A resumed checkpoint already carries initialized readouts and - # optimizer masters; never copy model values over loaded state. self._transfer_masters_synced = bool(self.draft_model.transfer_ready) result = super()._forward(batch, anchor_seed=anchor_seed) if not self._transfer_masters_synced and bool(self.draft_model.transfer_ready): + # Fallback for callers that construct the trainer without + # init_model(); normal training initializes before the first + # forward and never reaches this branch. self._sync_transfer_masters() self._transfer_masters_synced = True return result @@ -91,14 +136,30 @@ def _clone_window_value(value): return tuple(DSpineTrainer._clone_window_value(item) for item in value) return value + @classmethod + def _iter_window_tensors(cls, value): + if torch.is_tensor(value): + yield value + elif isinstance(value, dict): + for item in value.values(): + yield from cls._iter_window_tensors(item) + elif isinstance(value, (list, tuple)): + for item in value: + yield from cls._iter_window_tensors(item) + def _materialize_train_window(self, batches): - """Copy leased microbatches and release their ring slots immediately.""" + """Copy leased microbatches and release their ring slots safely.""" materialized = [] for batch in batches: leases = _take_p2p_receive_leases(batch) if leases: try: batch = self._clone_window_value(batch) + # CUDA clones are asynchronous; wait before Mooncake can + # reuse the ring slot for the next GET. + _synchronize_cuda_tensor_devices( + list(self._iter_window_tensors(batch)) + ) finally: for lease in leases: lease.release() @@ -161,6 +222,15 @@ def _prepass_anchor_seed(self, step, batch_idx): getattr(self.args, "seed", 0), step, batch_idx, self.dp_rank ) + def _reduce_window_statistic(self, ce_sum, denominator_sum): + group = getattr(self, "dp_group", None) + if dist.is_available() and dist.is_initialized(): + if dist.get_world_size(group=group) > 1: + packed = torch.stack((ce_sum, denominator_sum)) + dist.all_reduce(packed, op=dist.ReduceOp.SUM, group=group) + return packed[0], packed[1] + return ce_sum, denominator_sum + def _prepare_train_window(self, batches, step: int, num_batches: int): batches = self._materialize_train_window(batches) if len(batches) != num_batches: @@ -206,6 +276,9 @@ def _prepare_train_window(self, batches, step: int, num_batches: int): if ce_sum is None or denominator_sum is None: raise RuntimeError("DSpine alignment prepass produced no microbatches") + ce_sum, denominator_sum = self._reduce_window_statistic( + ce_sum, denominator_sum + ) safe_denominator = denominator_sum.where( denominator_sum > 0, torch.ones_like(denominator_sum) ) @@ -220,12 +293,22 @@ def _aggregate_metrics(self, all_step_metrics, step, *, grad_norm=None): metrics = super()._aggregate_metrics( all_step_metrics, step, grad_norm=grad_norm ) + objective = metrics.get("train/dspine/loss") + if objective is not None: + metrics["train/avg_loss"] = objective prepass_seconds = float(getattr(self, "_window_prepass_seconds", 0.0) or 0.0) if prepass_seconds > 0 and "perf/forward_time" in metrics: metrics["perf/forward_time"] += prepass_seconds metrics["perf/prepass_time"] = prepass_seconds return metrics + def _aggregate_eval_metrics(self, all_step_metrics): + metrics = super()._aggregate_eval_metrics(all_step_metrics) + objective = metrics.get("eval/dspine/loss") + if objective is not None: + metrics["eval/avg_loss"] = objective + return metrics + def _train_step(self, batch, accumulation_steps, step, batch_idx, num_batches): self._dspine_step = int(step) result = super()._train_step( diff --git a/aspec/training/trainer.py b/aspec/training/trainer.py index 56a6e5a..7e168ce 100644 --- a/aspec/training/trainer.py +++ b/aspec/training/trainer.py @@ -686,14 +686,12 @@ def _train_core_from_queue(self, step: int, num_batches: int) -> dict: ) prepass_events = getattr(self, "_prepass_events", None) self._prepass_events = None - prepass_seconds = 0.0 - if prepass_events is not None: - prepass_seconds = ( - prepass_events[0].elapsed_time(prepass_events[1]) / 1000.0 - ) - self._window_prepass_seconds = prepass_seconds - if perf and prepass_events is not None: - compute_events.append(prepass_events) + self._window_prepass_seconds = 0.0 + self._pending_prepass_events = ( + prepass_events if perf and prepass_events is not None else None + ) + if self._pending_prepass_events is not None: + compute_events.append(self._pending_prepass_events) batches = self.prof.iterate_train_actor(batches) for batch_idx, batch in enumerate(batches): is_last = batch_idx == num_batches - 1 @@ -706,12 +704,7 @@ def _train_core_from_queue(self, step: int, num_batches: int) -> dict: step_execution_ids.extend(item["execution_id"] for item in work_items) if perf: - elapsed = time.time() - t_data_start - if batch_idx == 0: - # Preparation (including any DSpine alignment prepass) is - # measured separately; keep queue-fetch time here. - elapsed = max(0.0, elapsed - prepass_seconds) - data_time += elapsed + data_time += time.time() - t_data_start evt_start = torch.cuda.Event(enable_timing=True) evt_end = torch.cuda.Event(enable_timing=True) evt_start.record() @@ -763,6 +756,7 @@ def _train_core_from_queue(self, step: int, num_batches: int) -> dict: f"Training step {step} received {len(all_step_metrics)} batches; " f"expected {num_batches}" ) + data_time = self._finalize_prepass_timing(perf, data_time) self.global_step += 1 if self._work_lifecycle_enabled: if self.global_step in self._committed_work_by_step: @@ -799,6 +793,19 @@ def _prepare_train_window(self, batches, step: int, num_batches: int): """Hook for trainers that need to inspect an accumulation window first.""" return batches + def _finalize_prepass_timing(self, perf: bool, data_time: float) -> float: + """Read deferred prepass events after the window has synchronized.""" + events = getattr(self, "_pending_prepass_events", None) + self._pending_prepass_events = None + if not perf or events is None: + return data_time + # The end event may still be queued right after preparation. Read it + # only here, where the existing compute events are already read, and + # move its time out of queue-fetch accounting. + prepass_start, prepass_end = events + self._window_prepass_seconds = prepass_start.elapsed_time(prepass_end) / 1000.0 + return max(0.0, data_time - self._window_prepass_seconds) + # ------------------------------------------------------------------ # Checkpointing & persistence # ------------------------------------------------------------------ diff --git a/tests/cpu/test_dspine.py b/tests/cpu/test_dspine.py index 6270d5e..07fc97d 100644 --- a/tests/cpu/test_dspine.py +++ b/tests/cpu/test_dspine.py @@ -91,6 +91,7 @@ def test_forward_initializes_transfer_space_and_backpropagates(): assert bool(model.draft_model.transfer_ready) assert model.draft_model.transfer_codes.shape == (32, 8) assert "dspine/backbone_ce" in components + assert "dspine/loss" in components assert terms[1] > 0 loss.backward() diff --git a/tests/cpu/test_dspine_integration.py b/tests/cpu/test_dspine_integration.py index 8a5de24..313f31a 100644 --- a/tests/cpu/test_dspine_integration.py +++ b/tests/cpu/test_dspine_integration.py @@ -21,12 +21,14 @@ _runtime_values, compile_execution_plan, ) +from aspec.training import dspine_trainer as dspine_trainer_module from aspec.training.checkpoint import ( _logical_training_topology, _validate_exact_resume_topology, ) from aspec.training.dflash_trainer import DFlashTrainer from aspec.training.dspine_trainer import DSpineTrainer +from aspec.training.trainer import Trainer from aspec.training.trainer_actor import _trainer_class_for_config _REPO_ROOT = Path(__file__).parents[2] @@ -113,6 +115,7 @@ def test_plan_compiles_with_dspine_objective(tmp_path): plan = compile_execution_plan(config, config_path=str(_EXAMPLE), cli_args=args).to_dict() draft = plan["workload"]["models"]["draft"] assert draft["family"] == "dspine" + assert draft["attention"]["draft_block_attention"] == "causal" objective = plan["workload"]["objective"] assert objective["loss"] == "dspine_backbone_refinement_alignment" assert objective["block_size"] == 16 @@ -288,24 +291,175 @@ def test_prepare_window_copies_leased_batches_and_releases(monkeypatch): config=SimpleNamespace(dspine_config={"alignment_weight": 0.0}) ) + order = [] + monkeypatch.setattr( + dspine_trainer_module, + "_synchronize_cuda_tensor_devices", + lambda values: order.append(("sync", list(values))), + ) + class Lease: def __init__(self): self.released = False def release(self): self.released = True + order.append(("release", None)) lease = Lease() tensor = torch.arange(4) batch = {"tensor": tensor, "_mooncake_p2p_receive_lease": lease} prepared = trainer._prepare_train_window(iter([batch]), step=0, num_batches=1) assert lease.released is True + assert [entry[0] for entry in order] == ["sync", "release"] assert "_mooncake_p2p_receive_lease" not in batch assert "_mooncake_p2p_receive_lease" not in prepared[0] assert prepared[0]["tensor"].data_ptr() != tensor.data_ptr() torch.testing.assert_close(prepared[0]["tensor"], tensor) +def test_alignment_window_statistic_reduces_across_dp(monkeypatch): + trainer = _mount_trainer(monkeypatch, _trainer_args()) + monkeypatch.setattr(dspine_trainer_module.dist, "is_available", lambda: True) + monkeypatch.setattr(dspine_trainer_module.dist, "is_initialized", lambda: True) + monkeypatch.setattr( + dspine_trainer_module.dist, "get_world_size", lambda group=None: 2 + ) + calls = [] + + def fake_all_reduce(packed, op=None, group=None): + calls.append((op, group)) + packed.add_(torch.tensor([12.0, 4.0])) + + monkeypatch.setattr(dspine_trainer_module.dist, "all_reduce", fake_all_reduce) + ce_sum, denominator_sum = trainer._reduce_window_statistic( + torch.tensor(2.0), torch.tensor(2.0) + ) + torch.testing.assert_close(ce_sum, torch.tensor(14.0)) + torch.testing.assert_close(denominator_sum, torch.tensor(6.0)) + torch.testing.assert_close(ce_sum / denominator_sum, torch.tensor(14.0 / 6.0)) + assert calls == [(dspine_trainer_module.dist.ReduceOp.SUM, None)] + + +def test_prepass_timing_is_deferred_and_skipped_without_perf(): + class Event: + def __init__(self, milliseconds): + self.milliseconds = milliseconds + self.calls = 0 + + def elapsed_time(self, other): + self.calls += 1 + return self.milliseconds + + start = Event(200.0) + fake = SimpleNamespace( + _pending_prepass_events=(start, Event(0.0)), + _window_prepass_seconds=0.0, + ) + assert Trainer._finalize_prepass_timing(fake, True, 5.0) == pytest.approx(4.8) + assert fake._window_prepass_seconds == pytest.approx(0.2) + assert start.calls == 1 + assert Trainer._finalize_prepass_timing(fake, True, 5.0) == 5.0 + + class IncompleteEvent: + def elapsed_time(self, other): + raise AssertionError("event timing must not be read without perf") + + fake = SimpleNamespace( + _pending_prepass_events=(IncompleteEvent(), IncompleteEvent()), + _window_prepass_seconds=0.0, + ) + assert Trainer._finalize_prepass_timing(fake, False, 3.0) == 3.0 + + +def test_train_core_defers_prepass_timing_until_sync(monkeypatch): + class FakeEvent: + def __init__(self, enable_timing=False): + pass + + def record(self): + pass + + def elapsed_time(self, other): + return 100.0 + + monkeypatch.setattr(torch.cuda, "Event", FakeEvent) + trainer = SimpleNamespace() + trainer.model = SimpleNamespace(train=lambda: None) + trainer.prof = SimpleNamespace(iterate_train_actor=lambda iterator: iterator) + trainer.data_fetcher = iter([{"batch": 0}, {"batch": 1}]) + trainer._iter_batches_from_queue = lambda num_batches: iter( + [{"batch": 0}, {"batch": 1}] + ) + trainer._enable_perf_metrics = True + trainer._work_lifecycle_enabled = False + trainer._committed_work_by_step = {} + trainer.global_step = 0 + + def prepare(batches, step, num_batches): + trainer._prepass_events = (FakeEvent(), FakeEvent()) + return list(batches) + + trainer._prepare_train_window = prepare + trainer._train_step = lambda **kwargs: { + "_fwd_events": (FakeEvent(), FakeEvent()), + "_bwd_events": (FakeEvent(), FakeEvent()), + } + trainer._maybe_dump = lambda *args, **kwargs: None + trainer.optimizer = SimpleNamespace(step=lambda: torch.tensor(0.0)) + trainer._after_optimizer_step = lambda *args, **kwargs: None + trainer._aggregate_metrics = lambda *args, **kwargs: {} + trainer._finalize_prepass_timing = ( + lambda perf, data_time: Trainer._finalize_prepass_timing( + trainer, perf, data_time + ) + ) + + Trainer._train_core_from_queue(trainer, step=0, num_batches=2) + assert trainer._window_prepass_seconds == pytest.approx(0.1) + assert trainer._pending_prepass_events is None + + +def test_dspine_loss_components_pool_like_the_objective(monkeypatch): + trainer = _mount_trainer(monkeypatch, _trainer_args()) + steps = [ + { + "dspine/loss": (torch.tensor(4.0), torch.tensor(2.0)), + "dspine/backbone_ce": (torch.tensor(6.0), torch.tensor(4.0)), + }, + { + "dspine/loss": (torch.tensor(8.0), torch.tensor(2.0)), + "dspine/backbone_ce": (torch.tensor(6.0), torch.tensor(4.0)), + }, + ] + reduced = trainer._reduce_loss_components(steps, "train/") + assert reduced["train/dspine/loss"] == pytest.approx(3.0) + assert reduced["train/dspine/backbone_ce"] == pytest.approx(1.5) + + +def test_dspine_metrics_use_the_optimized_objective(monkeypatch): + trainer = _mount_trainer(monkeypatch, _trainer_args()) + monkeypatch.setattr( + DFlashTrainer, + "_aggregate_metrics", + lambda self, all_step_metrics, step, *, grad_norm=None: { + "train/dspine/loss": 2.5, + "perf/forward_time": 1.0, + }, + ) + monkeypatch.setattr( + DFlashTrainer, + "_aggregate_eval_metrics", + lambda self, all_step_metrics: {"eval/dspine/loss": 1.5}, + ) + trainer._window_prepass_seconds = 0.25 + metrics = trainer._aggregate_metrics([], 0, grad_norm=None) + assert metrics["train/avg_loss"] == 2.5 + assert metrics["perf/forward_time"] == pytest.approx(1.25) + assert metrics["perf/prepass_time"] == pytest.approx(0.25) + assert trainer._aggregate_eval_metrics([])["eval/avg_loss"] == 1.5 + + @pytest.mark.parametrize( "missing", ["empty", "dspine", "dspine_total_steps", "loss", "is_causal", "dspine_config"], @@ -342,6 +496,7 @@ def test_checkpoint_topology_pins_dspine_objective(): assert objective["loss_decay_gamma"] == 7.0 assert current["draft_model_semantics"]["is_causal"] is True assert current["draft_model_semantics"]["dspine_config"]["transfer_rank"] == 8 + assert current["draft_attention_policy"]["draft_block_attention"] == "causal" metadata = {"world_size": 2, "training_topology": json.loads(json.dumps(current))} _validate_exact_resume_topology(args, metadata) From 7eb8de1e02005884f8df4c961755b7fa259d3746 Mon Sep 17 00:00:00 2001 From: Zijun Li <3335126979@qq.com> Date: Fri, 4 Dec 2026 21:23:21 +0800 Subject: [PATCH 4/5] fix(trainer): define data_time when perf metrics are disabled The deferred prepass timing helper was called unconditionally while data_time was only initialized inside the perf-enabled branch, causing an UnboundLocalError after the optimizer step when perf logging is off. Initialize data_time before the branch and cover both perf settings in the step test. --- aspec/training/trainer.py | 2 +- tests/cpu/test_dspine_integration.py | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/aspec/training/trainer.py b/aspec/training/trainer.py index 7e168ce..b310170 100644 --- a/aspec/training/trainer.py +++ b/aspec/training/trainer.py @@ -668,8 +668,8 @@ def _train_core_from_queue(self, step: int, num_batches: int) -> dict: grad_norm = None perf = self._enable_perf_metrics + data_time = 0.0 if perf: - data_time = 0.0 compute_events: list[tuple[torch.cuda.Event, torch.cuda.Event]] = [] t_data_start = time.time() diff --git a/tests/cpu/test_dspine_integration.py b/tests/cpu/test_dspine_integration.py index 313f31a..515f53b 100644 --- a/tests/cpu/test_dspine_integration.py +++ b/tests/cpu/test_dspine_integration.py @@ -372,7 +372,8 @@ def elapsed_time(self, other): assert Trainer._finalize_prepass_timing(fake, False, 3.0) == 3.0 -def test_train_core_defers_prepass_timing_until_sync(monkeypatch): +@pytest.mark.parametrize("perf", [True, False]) +def test_train_core_defers_prepass_timing_until_sync(monkeypatch, perf): class FakeEvent: def __init__(self, enable_timing=False): pass @@ -391,7 +392,7 @@ def elapsed_time(self, other): trainer._iter_batches_from_queue = lambda num_batches: iter( [{"batch": 0}, {"batch": 1}] ) - trainer._enable_perf_metrics = True + trainer._enable_perf_metrics = perf trainer._work_lifecycle_enabled = False trainer._committed_work_by_step = {} trainer.global_step = 0 @@ -416,7 +417,8 @@ def prepare(batches, step, num_batches): ) Trainer._train_core_from_queue(trainer, step=0, num_batches=2) - assert trainer._window_prepass_seconds == pytest.approx(0.1) + expected_seconds = 0.1 if perf else 0.0 + assert trainer._window_prepass_seconds == pytest.approx(expected_seconds) assert trainer._pending_prepass_events is None From e709f453fcd3b87b1e1b460440d9fd26bf2b76b4 Mon Sep 17 00:00:00 2001 From: Zijun Li <3335126979@qq.com> Date: Sat, 5 Dec 2026 00:13:41 +0800 Subject: [PATCH 5/5] fix(metrics): keep tiny eligible weights and align eval logging - shared loss-component reducer now keeps positive denominators as-is and only falls back to 1 for zero, so tiny eligible weights do not deflate logged refinement CE/L1 - eval console logging now happens after the final eval/avg_loss is selected by any subclass override, matching the tracker value --- aspec/training/dflash_trainer.py | 24 +++++++++++++-------- tests/cpu/test_dspine_integration.py | 32 ++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/aspec/training/dflash_trainer.py b/aspec/training/dflash_trainer.py index af24e39..647f6d0 100644 --- a/aspec/training/dflash_trainer.py +++ b/aspec/training/dflash_trainer.py @@ -672,7 +672,11 @@ def _reduce_loss_components(self, all_step_metrics: list[dict], prefix: str) -> packed = torch.stack(totals) if dist.is_initialized() and dist.get_world_size() > 1: dist.all_reduce(packed, op=dist.ReduceOp.SUM) - pooled = (packed[:, 0] / packed[:, 1].clamp(min=1e-6)).tolist() + denominator = packed[:, 1] + pooled = ( + packed[:, 0] + / denominator.where(denominator > 0, torch.ones_like(denominator)) + ).tolist() return {f"{prefix}{key}": value for key, value in zip(keys, pooled, strict=True)} def eval_from_cache(self) -> dict: @@ -699,7 +703,16 @@ def eval_from_cache(self) -> dict: self.model.train() - return self._aggregate_eval_metrics(all_metrics) + metrics = self._aggregate_eval_metrics(all_metrics) + if dist.get_rank() == 0: + prefix = self._prediction_metric_prefix() + logger.info( + f"eval: loss={metrics.get('eval/avg_loss', 0.0):.4f}, " + f"acc={metrics.get('eval/avg_acc', 0.0):.4f}, " + f"{prefix}sim_acc_len=" + f"{metrics.get(f'eval/{prefix}sim_acc_len', 0.0):.2f}" + ) + return metrics def _prediction_metric_prefix(self) -> str: """MTP observations cover the unknown suffix conditional on visible T1.""" @@ -757,13 +770,6 @@ def _aggregate_eval_metrics(self, all_step_metrics: list[dict]) -> dict: metrics[f"eval/{prefix}acc_{i}"] = pred_acc_pp[i].item() metrics.update(loss_components) - - if dist.get_rank() == 0: - logger.info( - f"eval: loss={weighted_avg_loss:.4f}, acc={avg_acc:.4f}, " - f"{prefix}sim_acc_len={simulated_acc_len:.2f}" - ) - return metrics # ------------------------------------------------------------------ diff --git a/tests/cpu/test_dspine_integration.py b/tests/cpu/test_dspine_integration.py index 515f53b..2cde3b6 100644 --- a/tests/cpu/test_dspine_integration.py +++ b/tests/cpu/test_dspine_integration.py @@ -21,6 +21,7 @@ _runtime_values, compile_execution_plan, ) +from aspec.training import dflash_trainer as dflash_trainer_module from aspec.training import dspine_trainer as dspine_trainer_module from aspec.training.checkpoint import ( _logical_training_topology, @@ -422,6 +423,37 @@ def prepare(batches, step, num_batches): assert trainer._pending_prepass_events is None +def test_loss_component_reducer_keeps_tiny_positive_weight(monkeypatch): + trainer = _mount_trainer(monkeypatch, _trainer_args()) + weight = torch.exp(torch.tensor(-16.0)) + steps = [ + {"dspine/refinement_ce": (torch.tensor(2.0) * weight, weight.clone())} + ] + reduced = trainer._reduce_loss_components(steps, "train/") + assert reduced["train/dspine/refinement_ce"] == pytest.approx(2.0, rel=1e-5) + + +def test_eval_log_uses_final_objective(monkeypatch): + logs = [] + monkeypatch.setattr(dflash_trainer_module.dist, "get_rank", lambda: 0) + monkeypatch.setattr(dflash_trainer_module.logger, "info", logs.append) + fake = SimpleNamespace() + fake._eval_cache = [{"x": 1}] + fake.args = SimpleNamespace(micro_batch_size=1) + fake.model = SimpleNamespace(eval=lambda: None, train=lambda: None) + fake._eval_collator = lambda chunk: {"x": 1} + fake.eval_forward = lambda batch: {} + fake._aggregate_eval_metrics = lambda all_metrics: { + "eval/avg_loss": 1.75, + "eval/avg_acc": 0.5, + "eval/sim_acc_len": 2.0, + } + fake._prediction_metric_prefix = lambda: "" + DFlashTrainer.eval_from_cache(fake) + assert any("loss=1.7500" in message for message in logs) + assert not any("loss=0.0000" in message for message in logs) + + def test_dspine_loss_components_pool_like_the_objective(monkeypatch): trainer = _mount_trainer(monkeypatch, _trainer_args()) steps = [