Skip to content

Latest commit

 

History

History
117 lines (87 loc) · 17.6 KB

Distillation.md

File metadata and controls

117 lines (87 loc) · 17.6 KB

Distillation Accelerated Training

What Is Distillation Accelerated Training?

The inference process of Diffusion models typically requires multi-step iterations, which improves generation quality but also makes the generation process slow. Through distillation accelerated training, the number of steps required to generate clear content can be reduced. The essence of distillation accelerated training technology is to align the generation effects of a small number of steps with those of a large number of steps.

In the design of the training framework, we need to evaluate the feasibility of a distillation accelerated training scheme from the following aspects:

  • Generality: The training scheme applies to most Diffusion models supported within the framework, rather than only working for a specific model, which is a basic requirement for code framework construction.
  • Stability: The training scheme must ensure stable training effects without requiring manual fine-tuning of parameters.
  • Simplicity: The training scheme does not introduce additional complex modules. According to Occam's Razor principle, complex solutions may introduce potential risks.
  • Generation Quality: The model obtained from training produces generation results at a small number of steps similar to those of the original model at a large number of steps.

We have tried several distillation accelerated training schemes, and the empirical results are shown in the following table:

Training Scheme Generality Stability Simplicity Generation Quality
Direct Distill ★★★ ★★★ ★★★ ★
DMD2 ★ ★ ★ ★★★
OPD (Recommended) ★★★ ★★ ★★★ ★★★

At this stage, we strongly recommend that developers use OPD for distillation accelerated training.

Direct Distill

Direct Distill is an end-to-end direct distillation training scheme that we designed. It uses the original model to generate sampling trajectories, and then trains the model to approximate the sampling trajectory with a small number of steps. For details, see End-to-End Direct Distillation Acceleration.

DMD2

DMD2 (Distribution Matching Distillation) is a model distillation training scheme that combines distribution matching with GAN training. A frozen teacher predicts the target distribution, while a fake-score model estimates the student's generated distribution. Together, their predictions provide the student's distribution-matching gradient. The GAN loss supplies an additional training signal from real images to improve detail in images generated by the distilled model.

Training involves three model roles:

  • Student: Generates samples along an ordinary Euler trajectory, retaining gradients only for a randomly selected sampling step, and optimizes distribution-matching and GAN losses.
  • Teacher: Has frozen parameters, predicts the target distribution, and uses --dmd2_teacher_cfg to control CFG.
  • Fake-score model: Learns to denoise student-generated samples and tracks the student's generated distribution. A GAN classifier head uses intermediate fake-score features to distinguish real images from student-generated images.

Real images are used only for GAN training to provide a signal for recovering image details; they do not contribute to the distribution-matching loss. With GAN disabled, dataset images serve only as placeholders for height and width to determine the generated image size. They are not encoded, and their pixel content is not used in training.

We provide the following training and validation examples for FLUX.2, Qwen-Image-2.1, MOSS-Image, and FLUX.3:

Base Model Trainable Parameters Training Code Post-Training Validation Steps Before Distillation Steps After Distillation
black-forest-labs/FLUX.2-klein-base-4B LoRA code code 50 8
black-forest-labs/FLUX.2-klein-base-4B Full code code 50 8
black-forest-labs/flux-3-image-klein-base LoRA code code 50 8
black-forest-labs/flux-3-image-klein-base Full code code 50 8
Qwen/Qwen-Image-2.1 LoRA code code 50 8
Qwen/Qwen-Image-2.1 Full code code 50 8
Qwen/Qwen-Image-2.1-Turbo LoRA code code 8 3
Qwen/Qwen-Image-2.1-Turbo Full code code 8 3
openmoss/MOSS-Image-SFT LoRA code code 50 8
openmoss/MOSS-Image-SFT Full code code 50 8

When using these examples, note the following:

  • --dmd2_student_sigmas and --dmd2_student_timesteps specify the student schedule and must correspond to each other. Use examples/dev_tools/compute_dmd2_sigmas.py to calculate them. Validation should use the same schedule as training, with student sampling at CFG=1.
  • --dmd2_teacher_cfg controls the CFG strength of teacher predictions and determines the guided target the student learns. A value of 1 applies no additional CFG guidance. This parameter affects only the teacher; student and fake-score predictions use CFG=1, and validation does not need to reuse the teacher's CFG.
  • --dmd2_fake_warmup_steps controls the initial number of critic-only updates; set it to 0 to disable warmup. --dmd2_fake_updates_per_generator controls the update ratio after warmup. Steps here count optimization windows after gradient accumulation.
  • --learning_rate controls the student learning rate. --dmd2_fake_learning_rate controls the fake-score and classifier learning rate and defaults to the student learning rate when omitted.
  • GAN training is enabled by default and requires real images. --dmd2_disable_gan disables it, in which case real images are not encoded. For GAN training, --dmd2_feature_module_of_dit_for_gan selects the backbone layer for feature extraction, and --dmd2_classifier_channels controls the classifier head width. Each model's training module handles its feature layout.
  • --dmd2_noise_sampling supports uniform and beta. The latter uses Beta(2.5, 1), favoring larger sigma values in the high-noise region, with bounds controlled by --dmd2_min_timestep and --dmd2_max_timestep. This option affects DM and fake denoising; GAN noise sampling always remains uniform.
  • Checkpoints export only student parameters. Use --lora_checkpoint to warm-start LoRA or --resume_from_checkpoint to load full student weights. These do not restore the fake-score model, classifier, optimizer, or random state and are not a full training resume. Replace the checkpoint paths in validation scripts with the actual training outputs.
  • DMD2 training currently does not support DeepSpeed or --enable_model_cpu_offload.

OPD

OPD (On-Policy Distillation) is an online distillation training scheme, including DiffusionOPD, DanceOPD, etc. Its algorithm pseudocode is as follows:

with torch.no_grad():
    trajectory = sample_trajectory(student_model)
input = trajectory[randint]
student_output = student_model(input)
with torch.no_grad():
    teacher_output = teacher_model(output) # Multi-step inference
loss = torch.nn.functional.mse(student_output, teacher_output)

In the DiffusionOPD variant, input = trajectory[randint] is replaced with a for loop, using every point in the trajectory for training. In the DanceOPD variant, input is sampled only in the low-noise-content stage, avoiding a large divergence in the model's output after training. In our example code, these two variants can be implemented respectively via the parameters --opd_num_distill_steps and --opd_min_distill_idx.

How do we combine the teacher model's multi-step outputs into a single target?

Suppose the student model's current sigma interval is [sigma_start, sigma_end], and the teacher performs multiple inference steps within it. The flag --opd_align_at_sigma_zero controls which endpoint the teacher's supervision target aligns to:

  • By default, the target aligns to the right endpoint, sigma_end. This forces the student's update in this step to exactly reach the end of the teacher's trajectory (where x_teacher(sigma_end) is obtained by extrapolating from the teacher's final step).
  • With --opd_align_at_sigma_zero enabled, the target instead aligns to sigma=0, using the average velocity from the current noisy sample to the clean sample as the supervision signal.

This flag only changes the teacher's supervision target, not the student's forward pass. Since sigma_end is already 0 for the last interval, both settings are equivalent there.

Compared with Direct Distill, OPD samples and updates starting from the student model rather than pre-generating trajectories with the teacher model, which makes the trained model perform better. Compared with DMD2, OPD does not require designing a discriminator model based on the model structure, so it is highly general and does not require careful tuning of various hyperparameters. Using FLUX.2, Qwen-Image-2.1, and MOSS-Image as examples, we provide example code for OPD training:

Base Model Trainable Parameters Training Code Post-Training Validation Steps Before Distillation Steps After Distillation
black-forest-labs/FLUX.2-klein-base-4B LoRA code code 50 8
black-forest-labs/FLUX.2-klein-base-4B Full code code 50 8
Qwen/Qwen-Image-2.1 LoRA code code 50 8
Qwen/Qwen-Image-2.1 Full code code 50 8
Qwen/Qwen-Image-2.1-Turbo LoRA code code 8 3
openmoss/MOSS-Image-SFT LoRA code code 50 8
openmoss/MOSS-Image-SFT Full code code 50 8

If needed, you can easily replicate the example code to implement OPD training for other models. Thanks to the general design of the framework, you can even train with datasets in arbitrary input formats (for example, mixing text-to-image and image-editing datasets), and you can even design new Adapter architecture models specifically for step distillation.

Qwen-Image-2.1-TurTurbo is a distillation accelerated model trained by us, used to verify the effectiveness of the training schemes in the framework. The following practical experiences we obtained from our experiments are for reference:

  • OPD converges very quickly during training, and usually produces results within 2 GPU*h.
  • In LoRA training, the LoRA should cover the input layer, the output layer, and the layers that process the timestep, because distillation accelerated training greatly changes the output form of the model.
  • For LoRA models obtained from OPD training, in a few cases, appropriately increasing the LoRA weight (multiplying the weights by a coefficient greater than 1) can better stimulate the model's capabilities.
  • The OPD training process is not absolutely stable; errors generated during sampling may accumulate inside the model. Therefore, longer training is not always better. When necessary, you can train multiple times and average the weights to increase stability.
  • When the difference in the number of steps between the teacher model and the student model is very large (for example, 50 and 4), the training results are not good. In this case, you can consider progressive distillation (for example, first distill from 50 to 8, then use the 8-step model as the teacher model to distill to 4).
  • The sigmas distribution of the student model is related to the generated image style. When sigmas stay longer in the high-noise stage, the image content tends to become simpler; when sigmas stay longer in the low-noise stage, the image details tend to become richer.
  • Enabling CFG can reduce the diversity of generated content, thereby reducing the difficulty of training.

Future Work

Distillation accelerated training still has great room for improvement in stability and model quality. We will continue to optimize the training effectiveness of the algorithms in the framework.