|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +"""LongCat model plugin (per-role instance).""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +from typing import Any, Literal, TYPE_CHECKING |
| 7 | + |
| 8 | +import torch |
| 9 | + |
| 10 | +from fastvideo.pipelines import TrainingBatch |
| 11 | +from fastvideo.train.models.wan.wan import WanModel |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + from fastvideo.train.utils.training_config import TrainingConfig |
| 15 | + |
| 16 | + |
| 17 | +class LongCatModel(WanModel): |
| 18 | + """LongCat per-role model for training and distillation.""" |
| 19 | + |
| 20 | + _transformer_cls_name: str = "LongCatTransformer3DModel" |
| 21 | + |
| 22 | + @staticmethod |
| 23 | + def _validate_flow_shift(flow_shift: float | None) -> float: |
| 24 | + if flow_shift is None: |
| 25 | + return 12.0 |
| 26 | + |
| 27 | + validated = float(flow_shift) |
| 28 | + if validated == 0.0: |
| 29 | + raise ValueError("LongCat training does not support flow_shift=0.0 because " |
| 30 | + "it collapses FlowMatch training timesteps. Use 12.0 to " |
| 31 | + "match the released LongCat scheduler config.") |
| 32 | + return validated |
| 33 | + |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + *, |
| 37 | + init_from: str, |
| 38 | + training_config: TrainingConfig, |
| 39 | + trainable: bool = True, |
| 40 | + disable_custom_init_weights: bool = False, |
| 41 | + flow_shift: float = 12.0, |
| 42 | + enable_gradient_checkpointing_type: str | None = None, |
| 43 | + transformer_override_safetensor: str | None = None, |
| 44 | + ) -> None: |
| 45 | + super().__init__( |
| 46 | + init_from=init_from, |
| 47 | + training_config=training_config, |
| 48 | + trainable=trainable, |
| 49 | + disable_custom_init_weights=disable_custom_init_weights, |
| 50 | + flow_shift=self._validate_flow_shift(flow_shift), |
| 51 | + enable_gradient_checkpointing_type=enable_gradient_checkpointing_type, |
| 52 | + transformer_override_safetensor=transformer_override_safetensor, |
| 53 | + ) |
| 54 | + |
| 55 | + def _init_timestep_mechanics(self) -> None: |
| 56 | + assert self.training_config is not None |
| 57 | + tc = self.training_config |
| 58 | + flow_shift = getattr(tc.pipeline_config, "flow_shift", None) # type: ignore[union-attr] |
| 59 | + self.timestep_shift = self._validate_flow_shift(flow_shift) |
| 60 | + self.num_train_timestep = int(self.noise_scheduler.num_train_timesteps) |
| 61 | + self.min_timestep = 0 |
| 62 | + self.max_timestep = self.num_train_timestep |
| 63 | + |
| 64 | + def _build_attention_metadata(self, training_batch: TrainingBatch) -> TrainingBatch: |
| 65 | + training_batch.attn_metadata = None |
| 66 | + return training_batch |
| 67 | + |
| 68 | + def _build_distill_input_kwargs( |
| 69 | + self, |
| 70 | + noise_input: torch.Tensor, |
| 71 | + timestep: torch.Tensor, |
| 72 | + text_dict: dict[str, torch.Tensor] | None, |
| 73 | + ) -> dict[str, Any]: |
| 74 | + if text_dict is None: |
| 75 | + raise ValueError("text_dict cannot be None for LongCat distillation") |
| 76 | + |
| 77 | + batch_size = int(noise_input.shape[0]) |
| 78 | + if timestep.ndim == 0: |
| 79 | + timestep = timestep.view(1).expand(batch_size) |
| 80 | + elif timestep.ndim == 1 and int(timestep.shape[0]) == 1 and batch_size > 1: |
| 81 | + timestep = timestep.expand(batch_size) |
| 82 | + |
| 83 | + return { |
| 84 | + "hidden_states": noise_input.permute(0, 2, 1, 3, 4), |
| 85 | + "encoder_hidden_states": text_dict["encoder_hidden_states"], |
| 86 | + "encoder_attention_mask": text_dict["encoder_attention_mask"], |
| 87 | + "timestep": timestep, |
| 88 | + } |
| 89 | + |
| 90 | + def predict_noise( |
| 91 | + self, |
| 92 | + noisy_latents: torch.Tensor, |
| 93 | + timestep: torch.Tensor, |
| 94 | + batch: TrainingBatch, |
| 95 | + *, |
| 96 | + conditional: bool, |
| 97 | + cfg_uncond: dict[str, Any] | None = None, |
| 98 | + attn_kind: Literal["dense", "vsa"] = "dense", |
| 99 | + ) -> torch.Tensor: |
| 100 | + """Adapt LongCat's sign convention to FineTuneMethod's target. |
| 101 | +
|
| 102 | + ``LongCatTransformer3DModel`` is pretrained to output the |
| 103 | + ``clean - noise`` direction; ``LongCatDenoisingStage`` (the |
| 104 | + bidirectional inference pipeline) explicitly negates the |
| 105 | + transformer output before handing it to |
| 106 | + ``FlowMatchEulerDiscreteScheduler.step``. Training methods on |
| 107 | + the other hand (``FineTuneMethod``, |
| 108 | + ``DiffusionForcingSFTMethod``) target ``noise - clean`` |
| 109 | + directly (the standard rectified-flow velocity Wan uses). |
| 110 | +
|
| 111 | + Without the negation here, the loss MSE pushes the transformer |
| 112 | + toward ``noise - clean``, flipping its native output sign over |
| 113 | + training. Inference then applies its own negation on top, so |
| 114 | + the scheduler receives the wrong direction and produces noise |
| 115 | + even while the training loss is dropping. Verified empirically |
| 116 | + on a 100-step LongCat overfit run: step 0 generated meaningful |
| 117 | + video, step 100 was pure noise despite low loss. |
| 118 | +
|
| 119 | + Negating in ``predict_noise`` keeps the transformer's |
| 120 | + pretrained sign convention intact while presenting the |
| 121 | + training methods with a Wan-compatible |
| 122 | + ``pred ≈ noise - clean`` for MSE. |
| 123 | + """ |
| 124 | + pred = super().predict_noise( |
| 125 | + noisy_latents, |
| 126 | + timestep, |
| 127 | + batch, |
| 128 | + conditional=conditional, |
| 129 | + cfg_uncond=cfg_uncond, |
| 130 | + attn_kind=attn_kind, |
| 131 | + ) |
| 132 | + return -pred |
0 commit comments