training_utils
¶
Classes¶
fastvideo.training.training_utils.EMA_FSDP
¶
FSDP2-friendly EMA with two modes
- mode="local_shard" (default): maintain float32 CPU EMA of local parameter shards on every rank. Provides a context manager to temporarily swap EMA weights into the live model for teacher forward.
- mode="rank0_full": maintain a consolidated float32 CPU EMA of full parameters on rank 0 only using gather_state_dict_on_cpu_rank0(). Useful for checkpoint export; not for teacher forward.
Usage (local_shard for CM teacher): ema = EMA_FSDP(model, decay=0.999, mode="local_shard") for step in ...: ema.update(model) with ema.apply_to_model(model): with torch.no_grad(): y_teacher = model(...)
Usage (rank0_full for export): ema = EMA_FSDP(model, decay=0.999, mode="rank0_full") ema.update(model) ema.state_dict() # on rank 0
Source code in fastvideo/training/training_utils.py
Functions¶
fastvideo.training.training_utils.EMA_FSDP.copy_to_unwrapped
¶
Copy EMA weights into a non-sharded (unwrapped) module. Intended for export/eval. For mode="rank0_full", only rank 0 has the full EMA state.
Source code in fastvideo/training/training_utils.py
Functions¶
fastvideo.training.training_utils.clip_grad_norm_
¶
clip_grad_norm_(parameters: Tensor | list[Tensor], max_norm: float, norm_type: float = 2.0, error_if_nonfinite: bool = False, foreach: bool | None = None, pp_mesh: DeviceMesh | None = None) -> Tensor
Clip the gradient norm of parameters.
Gradient norm clipping requires computing the gradient norm over the entire model.
torch.nn.utils.clip_grad_norm_ only computes gradient norm along DP/FSDP/TP dimensions.
We need to manually reduce the gradient norm across PP stages.
See https://github.com/pytorch/torchtitan/issues/596 for details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
`torch.Tensor` or `List[torch.Tensor]`
|
Tensors that will have gradients normalized. |
required |
max_norm
|
`float`
|
Maximum norm of the gradients after clipping. |
required |
norm_type
|
`float`, defaults to `2.0`
|
Type of p-norm to use. Can be |
2.0
|
error_if_nonfinite
|
`bool`, defaults to `False`
|
If |
False
|
foreach
|
`bool`, defaults to `None`
|
Use the faster foreach-based implementation. If |
None
|
pp_mesh
|
`torch.distributed.device_mesh.DeviceMesh`, defaults to `None`
|
Pipeline parallel device mesh. If not |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Source code in fastvideo/training/training_utils.py
fastvideo.training.training_utils.compute_density_for_timestep_sampling
¶
compute_density_for_timestep_sampling(weighting_scheme: str, batch_size: int, generator, logit_mean: float | None = None, logit_std: float | None = None, mode_scale: float | None = None)
Compute the density for sampling the timesteps when doing SD3 training.
Courtesy: This was contributed by Rafie Walker in https://github.com/huggingface/diffusers/pull/8528.
SD3 paper reference: https://arxiv.org/abs/2403.03206v1.
Source code in fastvideo/training/training_utils.py
fastvideo.training.training_utils.custom_to_hf_state_dict
¶
custom_to_hf_state_dict(state_dict: dict[str, Any] | Iterator[tuple[str, Tensor]], reverse_param_names_mapping: dict[str, tuple[str, int, int]]) -> dict[str, Any]
Convert fastvideo's custom model format to diffusers format using reverse_param_names_mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
dict[str, Any] | Iterator[tuple[str, Tensor]]
|
State dict in fastvideo's custom format |
required |
reverse_param_names_mapping
|
dict[str, tuple[str, int, int]]
|
Reverse mapping from fastvideo's custom format to diffusers format |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
State dict in diffusers format |
Source code in fastvideo/training/training_utils.py
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 | |
fastvideo.training.training_utils.get_constant_schedule
¶
get_constant_schedule(optimizer: Optimizer, last_epoch: int = -1) -> LambdaLR
Create a schedule with a constant learning rate, using the learning rate set in optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
[`~torch.optim.Optimizer`]
|
The optimizer for which to schedule the learning rate. |
required |
last_epoch
|
`int`, *optional*, defaults to -1
|
The index of the last epoch when resuming training. |
-1
|
Return
torch.optim.lr_scheduler.LambdaLR with the appropriate schedule.
Source code in fastvideo/training/training_utils.py
fastvideo.training.training_utils.get_constant_schedule_with_warmup
¶
get_constant_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, last_epoch: int = -1) -> LambdaLR
Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate increases linearly between 0 and the initial lr set in the optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
[`~torch.optim.Optimizer`]
|
The optimizer for which to schedule the learning rate. |
required |
num_warmup_steps
|
`int`
|
The number of steps for the warmup phase. |
required |
last_epoch
|
`int`, *optional*, defaults to -1
|
The index of the last epoch when resuming training. |
-1
|
Return
torch.optim.lr_scheduler.LambdaLR with the appropriate schedule.
Source code in fastvideo/training/training_utils.py
fastvideo.training.training_utils.get_cosine_schedule_with_min_lr
¶
get_cosine_schedule_with_min_lr(optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, min_lr_ratio: float = 0.1, num_cycles: float = 0.5, last_epoch: int = -1) -> LambdaLR
Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to a minimum lr (min_lr_ratio * initial_lr), after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
[`~torch.optim.Optimizer`]
|
The optimizer for which to schedule the learning rate. |
required |
num_warmup_steps
|
`int`
|
The number of steps for the warmup phase. |
required |
num_training_steps
|
`int`
|
The total number of training steps. |
required |
min_lr_ratio
|
`float`, *optional*, defaults to 0.1
|
The ratio of minimum learning rate to initial learning rate. |
0.1
|
num_cycles
|
`float`, *optional*, defaults to 0.5
|
The number of periods of the cosine function in a schedule. |
0.5
|
last_epoch
|
`int`, *optional*, defaults to -1
|
The index of the last epoch when resuming training. |
-1
|
Return
torch.optim.lr_scheduler.LambdaLR with the appropriate schedule.
Source code in fastvideo/training/training_utils.py
fastvideo.training.training_utils.get_cosine_schedule_with_warmup
¶
get_cosine_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float = 0.5, last_epoch: int = -1) -> LambdaLR
Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
[`~torch.optim.Optimizer`]
|
The optimizer for which to schedule the learning rate. |
required |
num_warmup_steps
|
`int`
|
The number of steps for the warmup phase. |
required |
num_training_steps
|
`int`
|
The total number of training steps. |
required |
num_periods
|
`float`, *optional*, defaults to 0.5
|
The number of periods of the cosine function in a schedule (the default is to just decrease from the max value to 0 following a half-cosine). |
required |
last_epoch
|
`int`, *optional*, defaults to -1
|
The index of the last epoch when resuming training. |
-1
|
Return
torch.optim.lr_scheduler.LambdaLR with the appropriate schedule.
Source code in fastvideo/training/training_utils.py
fastvideo.training.training_utils.get_cosine_with_hard_restarts_schedule_with_warmup
¶
get_cosine_with_hard_restarts_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: int = 1, last_epoch: int = -1) -> LambdaLR
Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to 0, with several hard restarts, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
[`~torch.optim.Optimizer`]
|
The optimizer for which to schedule the learning rate. |
required |
num_warmup_steps
|
`int`
|
The number of steps for the warmup phase. |
required |
num_training_steps
|
`int`
|
The total number of training steps. |
required |
num_cycles
|
`int`, *optional*, defaults to 1
|
The number of hard restarts to use. |
1
|
last_epoch
|
`int`, *optional*, defaults to -1
|
The index of the last epoch when resuming training. |
-1
|
Return
torch.optim.lr_scheduler.LambdaLR with the appropriate schedule.
Source code in fastvideo/training/training_utils.py
fastvideo.training.training_utils.get_linear_schedule_with_warmup
¶
get_linear_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, last_epoch: int = -1) -> LambdaLR
Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
[`~torch.optim.Optimizer`]
|
The optimizer for which to schedule the learning rate. |
required |
num_warmup_steps
|
`int`
|
The number of steps for the warmup phase. |
required |
num_training_steps
|
`int`
|
The total number of training steps. |
required |
last_epoch
|
`int`, *optional*, defaults to -1
|
The index of the last epoch when resuming training. |
-1
|
Return
torch.optim.lr_scheduler.LambdaLR with the appropriate schedule.
Source code in fastvideo/training/training_utils.py
fastvideo.training.training_utils.get_piecewise_constant_schedule
¶
get_piecewise_constant_schedule(optimizer: Optimizer, step_rules: str, last_epoch: int = -1) -> LambdaLR
Create a schedule with a constant learning rate, using the learning rate set in optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
[`~torch.optim.Optimizer`]
|
The optimizer for which to schedule the learning rate. |
required |
step_rules
|
`string`
|
The rules for the learning rate. ex: rule_steps="1:10,0.1:20,0.01:30,0.005" it means that the learning rate if multiple 1 for the first 10 steps, multiple 0.1 for the next 20 steps, multiple 0.01 for the next 30 steps and multiple 0.005 for the other steps. |
required |
last_epoch
|
`int`, *optional*, defaults to -1
|
The index of the last epoch when resuming training. |
-1
|
Return
torch.optim.lr_scheduler.LambdaLR with the appropriate schedule.
Source code in fastvideo/training/training_utils.py
fastvideo.training.training_utils.get_polynomial_decay_schedule_with_warmup
¶
get_polynomial_decay_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, lr_end: float = 1e-07, power: float = 1.0, last_epoch: int = -1) -> LambdaLR
Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the optimizer to end lr defined by lr_end, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
[`~torch.optim.Optimizer`]
|
The optimizer for which to schedule the learning rate. |
required |
num_warmup_steps
|
`int`
|
The number of steps for the warmup phase. |
required |
num_training_steps
|
`int`
|
The total number of training steps. |
required |
lr_end
|
`float`, *optional*, defaults to 1e-7
|
The end LR. |
1e-07
|
power
|
`float`, *optional*, defaults to 1.0
|
Power factor. |
1.0
|
last_epoch
|
`int`, *optional*, defaults to -1
|
The index of the last epoch when resuming training. |
-1
|
Note: power defaults to 1.0 as in the fairseq implementation, which in turn is based on the original BERT implementation at https://github.com/google-research/bert/blob/f39e881b169b9d53bea03d2d341b31707a6c052b/optimization.py#L37
Return
torch.optim.lr_scheduler.LambdaLR with the appropriate schedule.
Source code in fastvideo/training/training_utils.py
fastvideo.training.training_utils.get_scheduler
¶
get_scheduler(name: str | SchedulerType, optimizer: Optimizer, step_rules: str | None = None, num_warmup_steps: int | None = None, num_training_steps: int | None = None, num_cycles: int = 1, power: float = 1.0, min_lr_ratio: float = 0.1, last_epoch: int = -1) -> LambdaLR
Unified API to get any scheduler from its name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
`str` or `SchedulerType`
|
The name of the scheduler to use. |
required |
optimizer
|
`torch.optim.Optimizer`
|
The optimizer that will be used during training. |
required |
step_rules
|
`str`, *optional*
|
A string representing the step rules to use. This is only used by the |
None
|
num_warmup_steps
|
`int`, *optional*
|
The number of warmup steps to do. This is not required by all schedulers (hence the argument being optional), the function will raise an error if it's unset and the scheduler type requires it. |
None
|
num_training_steps
|
`int``, *optional*
|
The number of training steps to do. This is not required by all schedulers (hence the argument being optional), the function will raise an error if it's unset and the scheduler type requires it. |
None
|
num_cycles
|
`int`, *optional*
|
The number of hard restarts used in |
1
|
power
|
`float`, *optional*, defaults to 1.0
|
Power factor. See |
1.0
|
min_lr_ratio
|
`float`, *optional*, defaults to 0.1
|
The ratio of minimum learning rate to initial learning rate. Used in |
0.1
|
last_epoch
|
`int`, *optional*, defaults to -1
|
The index of the last epoch when resuming training. |
-1
|
Source code in fastvideo/training/training_utils.py
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 | |
fastvideo.training.training_utils.load_checkpoint
¶
load_checkpoint(transformer, rank, checkpoint_path, optimizer=None, dataloader=None, scheduler=None, noise_generator=None) -> int
Load checkpoint following finetrainer's distributed checkpoint approach. Returns the step number from which training should resume.
Source code in fastvideo/training/training_utils.py
fastvideo.training.training_utils.load_distillation_checkpoint
¶
load_distillation_checkpoint(generator_transformer, fake_score_transformer, rank, checkpoint_path, generator_optimizer=None, fake_score_optimizer=None, dataloader=None, generator_scheduler=None, fake_score_scheduler=None, noise_generator=None, generator_ema=None, generator_transformer_2=None, real_score_transformer_2=None, fake_score_transformer_2=None, generator_optimizer_2=None, fake_score_optimizer_2=None, generator_scheduler_2=None, fake_score_scheduler_2=None, generator_ema_2=None) -> int
Load distillation checkpoint with both generator and fake_score models. Supports MoE (Mixture of Experts) models with transformer_2 variants. Returns the step number from which training should resume.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
generator_transformer
|
Main generator transformer model |
required | |
fake_score_transformer
|
Main fake score transformer model |
required | |
generator_transformer_2
|
Secondary generator transformer for MoE (optional) |
None
|
|
real_score_transformer_2
|
Secondary real score transformer for MoE (optional) |
None
|
|
fake_score_transformer_2
|
Secondary fake score transformer for MoE (optional) |
None
|
|
generator_optimizer_2
|
Optimizer for generator_transformer_2 (optional) |
None
|
|
fake_score_optimizer_2
|
Optimizer for fake_score_transformer_2 (optional) |
None
|
|
generator_scheduler_2
|
Scheduler for generator_transformer_2 (optional) |
None
|
|
fake_score_scheduler_2
|
Scheduler for fake_score_transformer_2 (optional) |
None
|
|
generator_ema_2
|
EMA for generator_transformer_2 (optional) |
None
|
Source code in fastvideo/training/training_utils.py
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 | |
fastvideo.training.training_utils.save_checkpoint
¶
save_checkpoint(transformer, rank, output_dir, step, optimizer=None, dataloader=None, scheduler=None, noise_generator=None) -> None
Save checkpoint following finetrainer's distributed checkpoint approach. Saves both distributed checkpoint and consolidated model weights.
Source code in fastvideo/training/training_utils.py
fastvideo.training.training_utils.save_distillation_checkpoint
¶
save_distillation_checkpoint(generator_transformer, fake_score_transformer, rank, output_dir, step, generator_optimizer=None, fake_score_optimizer=None, dataloader=None, generator_scheduler=None, fake_score_scheduler=None, noise_generator=None, generator_ema=None, only_save_generator_weight=False, generator_transformer_2=None, real_score_transformer_2=None, fake_score_transformer_2=None, generator_optimizer_2=None, fake_score_optimizer_2=None, generator_scheduler_2=None, fake_score_scheduler_2=None, generator_ema_2=None) -> None
Save distillation checkpoint with both generator and fake_score models. Supports MoE (Mixture of Experts) models with transformer_2 variants. Saves both distributed checkpoint and consolidated model weights. Only saves the generator model for inference (consolidated weights).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
generator_transformer
|
Main generator transformer model |
required | |
fake_score_transformer
|
Main fake score transformer model |
required | |
only_save_generator_weight
|
If True, only save the generator model weights for inference without saving distributed checkpoint for training resume. |
False
|
|
generator_transformer_2
|
Secondary generator transformer for MoE (optional) |
None
|
|
real_score_transformer_2
|
Secondary real score transformer for MoE (optional) |
None
|
|
fake_score_transformer_2
|
Secondary fake score transformer for MoE (optional) |
None
|
|
generator_optimizer_2
|
Optimizer for generator_transformer_2 (optional) |
None
|
|
fake_score_optimizer_2
|
Optimizer for fake_score_transformer_2 (optional) |
None
|
|
generator_scheduler_2
|
Scheduler for generator_transformer_2 (optional) |
None
|
|
fake_score_scheduler_2
|
Scheduler for fake_score_transformer_2 (optional) |
None
|
|
generator_ema_2
|
EMA for generator_transformer_2 (optional) |
None
|
Source code in fastvideo/training/training_utils.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 | |