Large-scale refactoring has been merged into main — migration guide inside
#949
kohya-ss
announced in
Announcements
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Thank you for using and contributing to this repository.
A large-scale internal refactoring is currently in progress and is nearing completion. We plan to merge it into
mainsoon.The user-facing interface of each script (script names, command-line options, dataset configuration, etc.) is essentially unchanged, so you can continue using the scripts as before.
On the implementation side, the architecture-specific classes are largely preserved, but the internal APIs (base classes, utility modules, etc.) have changed significantly. Maintainers of forks and dependent tools are kindly asked to review their code after the merge.
After the merge, a migration guide outlining the main changes and old-to-new mappings will be added to this discussion.
Since the refactoring is still in progress, we would appreciate it if pull requests that touch the common parts could be submitted after the refactoring has been merged.
There may be some temporary inconvenience, but we appreciate your understanding, as this work aims to improve long-term maintainability. Thank you.
日本語
いつも当リポジトリをご利用いただき、また多数の貢献をいただき、ありがとうございます。
現在、大規模な内部リファクタリングを進めており、間もなく完了する見込みです。近日中に
mainへのマージを予定しています。各スクリプト利用時のインターフェース(スクリプト名、コマンドラインオプション、データセット設定など)には基本的には変更ありませんので、そのままお使いいただけます。
実装面では、各アーキテクチャのクラスは基本的に維持されていますが、内部のAPI(基底クラスやユーティリティモジュールなど)は大きく変更されています。そのため、forkされたリポジトリや、依存ツールのメンテナの方々におかれましては、マージ後に確認をお願いいたします。
マージ後に、主要な変更点や新旧の対応を示した移行ガイドをこのdiscussionに追加する予定です。
pull requestにつきまして、リファクタリングが進行中のため、共通部分に関するpull requestはリファクタリングのマージ後にご提出いただければ幸いです。
一時的にご不便をおかけする場面もあるかもしれませんが、将来的な保守性を向上させるための取り組みとしてご理解いただければ幸いです。よろしくお願いいたします。
Migration Guide (post-merge)
The refactor described above has now landed on
mainvia #950. This guide summarises the surface that changed for fork maintainers and authors of dependent tools.1. End users — no changes required
Script names, command-line options, and dataset configuration (TOML) are unchanged. Existing training/inference/cache commands continue to work as before.
If you notice any behavioural change or breakage after updating, please report it in this discussion.
2. Fork / extension maintainers
Backward-compatible re-exports are in place, so most existing imports keep working. However, the canonical locations have moved, and a few APIs have shifted shape. New code should target the new paths.
2.1 New module layout
2.2 Symbol relocation table
NetworkTrainer,DiTOutput,SS_METADATA_KEY_*,SS_METADATA_MINIMUM_KEYSmusubi_tuner.hv_train_networkmusubi_tuner.training.trainer_baseclean_memory_on_device,prepare_accelerator,collator_classmusubi_tuner.hv_train_networkmusubi_tuner.training.accelerator_setupline_to_prompt_dict,load_prompts,should_sample_imagesmusubi_tuner.hv_train_networkmusubi_tuner.training.sampling_promptscompute_density_for_timestep_sampling,get_sigmas,compute_loss_weighting_for_sd3musubi_tuner.hv_train_networkmusubi_tuner.training.timestepssetup_parser_common,read_config_from_filemusubi_tuner.hv_train_networkmusubi_tuner.training.parser_commonBucketSelector,BucketBatchManagermusubi_tuner.dataset.image_video_datasetmusubi_tuner.dataset.bucketContentDatasource,ImageDatasource,VideoDatasource,*DirectoryDatasource,*JsonlDatasourcemusubi_tuner.dataset.image_video_datasetmusubi_tuner.dataset.datasourcessave_latent_cache_*,save_text_encoder_output_cache_*musubi_tuner.dataset.image_video_datasetmusubi_tuner.dataset.cache_ioresize_image_to_bucket, image/video I/O helpersmusubi_tuner.dataset.image_video_datasetmusubi_tuner.dataset.media_utilsARCHITECTURE_*constantsmusubi_tuner.dataset.image_video_datasetmusubi_tuner.dataset.architecturesOld paths re-export the symbols above, so existing code does not need to change immediately.
2.3
NetworkTraineris now architecture-agnosticHunyuanVideo-specific defaults (
load_vae,load_transformer,call_dit,process_sample_prompts,do_inference, …) used to live as concrete methods onNetworkTrainer. They are now onHunyuanVideoNetworkTrainerinhv_train_network.py, and the base class declares them as abstract hooks (NotImplementedError).If your fork inherited HV behaviour by default (rather than overriding it), subclass
HunyuanVideoNetworkTrainerinstead ofNetworkTrainer.2.4
train()split into phase methodsNetworkTrainer.train()(~700 lines) was decomposed into private phase methods:Forks that overrode
train()wholesale should migrate to the extension hooks below, or override a specific phase method.2.5 Breaking API change:
call_ditreturn typeDiTOutputis a dataclass withpred,target, and an optionalextra: dictescape hatch for side outputs (e.g. hidden features). It is exported frommusubi_tuner.training.trainer_base(and re-exported frommusubi_tuner.hv_train_network).**kwargswas added so future per-arch conditioning (e.g. per-token timesteps) can flow through without further signature churn.Any fork that overrides
call_ditmust update its return statement and signature. All in-tree per-architecture trainers have been updated.2.6 New extension hooks (all opt-in; defaults are no-ops)
These were introduced primarily for Self-Flow (PR #913) but are general-purpose. They are documented as internal-only — no API stability guarantees yet so they may evolve based on use.
Lifecycle hooks:
on_transformer_loaded(transformer)load_transformer, beforeeval()andaccelerator.prepareforward_hookon raw blockson_train_start(transformer, network)_run_training_loop, post-prepareon_post_optimizer_step(transformer, sync_gradients)optimizer.step/lr_scheduler.step/zero_gradon_before_sample_images(transformer, network)/on_after_sample_images(...)sample_imagescall siteafterfires on exception)on_post_save(transformer, args, ..., force_sync_upload)save_model, after main checkpoint writtenComputation hooks:
process_batch(batch) → (loss, loss_metrics: dict[str, float])call_dit, loss computation for one stepcompute_loss(output: DiTOutput, ..., weighting) → lossprocess_batchif data flow is standard)predvstargetContributor hooks (return values are merged into existing structures):
extra_trainable_params(args, transformer) → list[param-group]extra_metadata(args) → dictextra_step_logs(args, logs) → dictaccelerator.logpayload2.7 Reference example
src/musubi_tuner/flux_2_train_network_self_flow.pyis a Self-Flow skeleton that exercises every hook above. The algorithmic body isNotImplementedErrorwithTODOcomments referencing PR #913 — the file is not yet runnable, but it is the recommended template for how to wire an extension on top of the new seams.2.8 Minor latent fixes also included
A small follow-up commit (7a22df8) fixes bugs surfaced by Copilot review:
_int_or_floatnow accepts TOML-style float literals like"1.0"/"10.0"for int-typed CLI args (previously fell through to a misleading error).convert_weight_keysis now invoked with the importednetwork_moduleobject, matching its type annotation (the previous string argument was ignored by all overrides, so no behaviour change).AttributeErroron theafter_sample_imagespath when Self-Flow is off.日本語
移行ガイド(マージ後)
上述のリファクタリングは #950 を通じて
mainにマージされました。fork メンテナや依存ツール作者向けに、変更されたインターフェースを以下にまとめます。1. 一般ユーザー — 対応不要
スクリプト名、コマンドラインオプション、データセット設定(TOML)は変更されていません。既存の training/inference/cache コマンドはそのままお使いいただけます。
万一動作が変わった、あるいは動かなくなった等あれば、この discussion でご報告いただけると助かります。
2. fork / 拡張のメンテナ向け
後方互換用の re-export が用意されているため、既存の import の多くはそのまま動作します。ただし、正規の位置は移動しており、いくつかの API はシグネチャが変わっています。新規コードは新パスを推奨します。
2.1 新しいモジュール構成
上の英語セクション 2.1 のツリー図を参照してください。
2.2 シンボル対応表
NetworkTrainer,DiTOutput,SS_METADATA_KEY_*,SS_METADATA_MINIMUM_KEYSmusubi_tuner.hv_train_networkmusubi_tuner.training.trainer_baseclean_memory_on_device,prepare_accelerator,collator_classmusubi_tuner.hv_train_networkmusubi_tuner.training.accelerator_setupline_to_prompt_dict,load_prompts,should_sample_imagesmusubi_tuner.hv_train_networkmusubi_tuner.training.sampling_promptscompute_density_for_timestep_sampling,get_sigmas,compute_loss_weighting_for_sd3musubi_tuner.hv_train_networkmusubi_tuner.training.timestepssetup_parser_common,read_config_from_filemusubi_tuner.hv_train_networkmusubi_tuner.training.parser_commonBucketSelector,BucketBatchManagermusubi_tuner.dataset.image_video_datasetmusubi_tuner.dataset.bucketContentDatasource,ImageDatasource,VideoDatasource,*DirectoryDatasource,*JsonlDatasourcemusubi_tuner.dataset.image_video_datasetmusubi_tuner.dataset.datasourcessave_latent_cache_*,save_text_encoder_output_cache_*musubi_tuner.dataset.image_video_datasetmusubi_tuner.dataset.cache_ioresize_image_to_bucket、画像/動画 I/O ヘルパーmusubi_tuner.dataset.image_video_datasetmusubi_tuner.dataset.media_utilsARCHITECTURE_*定数musubi_tuner.dataset.image_video_datasetmusubi_tuner.dataset.architectures旧パスは引き続き re-export されているので、既存コードを直ちに書き換える必要はありません。
2.3
NetworkTrainerがアーキテクチャ非依存にこれまで
NetworkTrainer基底クラスに HunyuanVideo 固有のデフォルト実装(load_vae,load_transformer,call_dit,process_sample_prompts,do_inference等)が混在していました。これらはhv_train_network.pyのHunyuanVideoNetworkTrainerに移動し、基底クラスでは abstract hook(NotImplementedError)となっています。HV のデフォルト挙動を継承していた fork は、
NetworkTrainerではなくHunyuanVideoNetworkTrainerを継承してください。2.4
train()のフェーズメソッド分割NetworkTrainer.train()(約700行)は以下のプライベートフェーズメソッドに分解されました:train()全体をオーバーライドしていた fork は、後述の拡張フック、または個別のフェーズメソッドのオーバーライドに移行してください。2.5 互換性のない API 変更:
call_ditの戻り値DiTOutputはpred,target, およびオプションのextra: dict(hidden feature 等の副次出力用エスケープハッチ)を持つ dataclass です。musubi_tuner.training.trainer_baseからエクスポートされ、musubi_tuner.hv_train_network経由でも import 可能です。**kwargsは将来のアーキテクチャ固有の追加条件(例: per-token timestep)を後方互換に渡せるよう追加しました。call_ditをオーバーライドしている fork は、return 文とシグネチャの更新が必須です。 in-tree のアーキテクチャ別 trainer はすべて更新済みです。2.6 新しい拡張フック(すべて opt-in、デフォルト no-op)
主に Self-Flow(PR #913)のために導入しましたが、汎用的に使えます。あくまで内部利用を想定した API の位置づけで安定性は保証されませんので、実利用フィードバックに応じて変わる可能性があります。
ライフサイクル系:
on_transformer_loaded(transformer)load_transformer直後、eval()およびaccelerator.prepare前forward_hook登録on_train_start(transformer, network)_run_training_loopの冒頭、prepare後on_post_optimizer_step(transformer, sync_gradients)optimizer.step/lr_scheduler.step/zero_grad直後on_before_sample_images(transformer, network)/on_after_sample_images(...)sample_images呼び出しの前後afterが走る)on_post_save(transformer, args, ..., force_sync_upload)save_model末尾、メインチェックポイント保存後計算系:
process_batch(batch) → (loss, loss_metrics: dict[str, float])call_dit、損失計算を担うcompute_loss(output: DiTOutput, ..., weighting) → lossprocess_batchと分けて差し替え可能)predvstargetの重み付き MSEコントリビューター系(戻り値が既存の構造にマージされる):
extra_trainable_params(args, transformer) → list[param-group]extra_metadata(args) → dictextra_step_logs(args, logs) → dictaccelerator.logペイロード2.7 参考実装
src/musubi_tuner/flux_2_train_network_self_flow.pyは上記すべてのフックを使用している Self-Flow の skeleton です。アルゴリズム本体は PR #913 を参照するTODO付きのNotImplementedErrorのため、現状は実行できませんが、新しい拡張ポイントの上に独自トレーナーを組み立てる際のテンプレートとして参照してください。2.8 細かい修正も含まれます
Copilot レビュー由来の修正コミット(7a22df8):
_int_or_floatが int 型 CLI 引数に対して"1.0"/"10.0"のような TOML 由来の float リテラルを受け付けるように(以前は誤解を招くエラーで落ちていた)。convert_weight_keysが型注釈どおり import 済みnetwork_moduleオブジェクトを受け取るように内部修正(既存オーバーライドは引数を未使用だったため挙動への影響なし)。after_sample_images経路でAttributeErrorが出ないようガード。Beta Was this translation helpful? Give feedback.
All reactions