Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+8
- .gitignoreAdded+12
- LICENSEAdded+201
- README.mdAdded+344
- checkpoints/update-100000.pthAdded+3
- configs/rfm.pyAdded+29
- datasets/__init__.pyAdded+1
- datasets/rfm_data.pyAdded+85
- diffusion/__init__.pyAdded+1
- diffusion/model/__init__.pyAdded+12
- diffusion/model/builder.pyAdded+16
- diffusion/model/nets/PixArt.pyAdded+277
- diffusion/model/nets/PixArt_blocks.pyAdded+451
- diffusion/model/nets/__init__.pyAdded+1
- diffusion/model/t5.pyAdded+239
- diffusion/model/utils.pyAdded+510
- diffusion/rectified_flow.pyAdded+62
- diffusion/utils/__init__.pyAdded
- diffusion/utils/dist_utils.pyAdded+303
- diffusion/utils/logger.pyAdded+94
- diffusion/utils/rfm_checkpoint.pyAdded+46
- diffusion/utils/theta_import.pyAdded+77
- examples/inference_prompts.jsonAdded+22
- examples/validation_prompts.jsonAdded+18
- output/run-validation-100000/validation/update-100000/ema-0.pngAdded
- output/run-validation-100000/validation/update-100000/ema-1.pngAdded
- output/run-validation-100000/validation/update-100000/ema-2.pngAdded
- output/run-validation-100000/validation/update-100000/ema-3.pngAdded
- output/run-validation-100000/validation/update-100000/ema.ptAdded+3
- output/run-validation-100000/validation/update-100000/prompts.jsonAdded+6
- output/run-validation-100000/validation/update-100000/raw-0.pngAdded
- output/run-validation-100000/validation/update-100000/raw-1.pngAdded
- output/run-validation-100000/validation/update-100000/raw-2.pngAdded
- output/run-validation-100000/validation/update-100000/raw-3.pngAdded
- output/run-validation-100000/validation/update-100000/raw.ptAdded+3
- output/run-validation-100000/validation/update-100000/sampler.jsonAdded+24
- output/run-validation-100000/validation_config.jsonAdded+69
- requirements.txtAdded+22
- run.shAdded+74
- scripts/inference_rfm.pyAdded+146
- scripts/preparation/__init__.pyAdded+1
- scripts/preparation/cache_synthetic_dataset.pyAdded+152
- scripts/preparation/encode_image_latents.pyAdded+219
- scripts/preparation/prepare_theta_v.pyAdded+83
- scripts/preparation/verify_rfm_smoke.pyAdded+176
- scripts/train_rfm.pyAdded+490
- scripts/validate_rfm.pyAdded+79
- tests/test_bash_launcher.pyAdded+78
- tests/test_rectified_flow.pyAdded+66
- tests/test_rfm_checkpoint.pyAdded+80
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363738394041424332 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textoutput/run-validation-100000/validation/update-100000/ema-0.png filter=lfs diff=lfs merge=lfs -textoutput/run-validation-100000/validation/update-100000/ema-1.png filter=lfs diff=lfs merge=lfs -textoutput/run-validation-100000/validation/update-100000/ema-2.png filter=lfs diff=lfs merge=lfs -textoutput/run-validation-100000/validation/update-100000/ema-3.png filter=lfs diff=lfs merge=lfs -textoutput/run-validation-100000/validation/update-100000/raw-0.png filter=lfs diff=lfs merge=lfs -textoutput/run-validation-100000/validation/update-100000/raw-1.png filter=lfs diff=lfs merge=lfs -textoutput/run-validation-100000/validation/update-100000/raw-2.png filter=lfs diff=lfs merge=lfs -textoutput/run-validation-100000/validation/update-100000/raw-3.png filter=lfs diff=lfs merge=lfs -text
123456789101112__pycache__/*.py[cod].pytest_cache/.venv/.envoutput/data/assets/*.log*.egg-info/build/dist/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2024 Junsong Chen, Jincheng Yu, Enze Xie
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344# pixelart-alpha2rfm
A standalone repository for text-conditioned Rectified Flow Matching (RFM) withPixArt Alpha. The model starts from pretrained RAW epsilon-prediction weights andtrains for 100,000 optimizer updates, from step 0 to step 100K.
This repository contains the model, dataset definitions, training, preparation,validation, and inference code. `scripts/train_rfm.py` is the single trainingentry point. All project code is local to this repository; datasets, caches,checkpoints, and pretrained VAE/T5 assets must be supplied separately.
## Experiment configuration
The experiment is defined in [configs/rfm.py](configs/rfm.py).
| Setting | Value || --- | --- || Model | PixArt XL/2, 512 × 512, QK RMSNorm || Initialization | RAW epsilon weights from `A_flux1_dev_mix50/checkpoint-010000` || Output head | Four channels; zero-initialized for new training || Flow path | `x(t) = (1 - t) * noise + t * data` || Target and loss | `data - noise`, unweighted MSE || Time sampling | Continuous uniform sampling; model time embedding `999 * (1 - t)` || Datasets | FluxLocalizedNarratives: 50,000 images; FluxSynth: 76,708 images || Data mixture | Exactly four samples from each dataset per GPU batch || Batch size | Four GPUs × eight samples; global batch size 32; no gradient accumulation || Precision | BF16; gradient checkpointing disabled || Optimizer | AdamW, learning rate `1e-5`, 500 warmup updates, zero weight decay || EMA decay | `0.9999` || Text dropout | `0.1` || Training duration | 100,000 optimizer updates, from step 0 to step 100K || Validation | RAW and EMA weights; `dopri5`, CFG 4, `atol=1e-6`, `rtol=1e-3` || Validation seeds | 42, 43, 44, 45 |
The trained output head is restored unchanged when resuming or sampling.`dopri5` uses adaptive steps: `sampling_steps=50` does not impose 50 samplingsteps. Each validation run records its sampler settings and number of functionevaluations in `sampler.json`.
## Repository layout
```textrun.sh # Bash launcher for train, validate, and inferenceconfigs/ rfm.py # Experiment settings and resource pathsexamples/ validation_prompts.json # Four fixed validation prompts and seeds inference_prompts.json # Example custom prompts with case IDsdatasets/ rfm_data.py # CachedDataset, cache loading, and balanced samplingdiffusion/ rectified_flow.py # RFM loss and Heun/dopri5 sampling model/ # PixArt XL/2 and T5 text encoding utils/rfm_checkpoint.py # Checkpoints, EMA, RNG state, and text dropout utils/theta_import.py # Pretrained weight conversion and provenancescripts/ train_rfm.py # Training, resume, validation, and optional background launch validate_rfm.py # RAW/EMA validation from a checkpoint inference_rfm.py # Custom text-to-image inference preparation/ cache_synthetic_dataset.py # VAE posterior and T5 embedding caches encode_image_latents.py # Image preprocessing and latent caching prepare_theta_v.py # Initialization weights and fixed text conditioning verify_rfm_smoke.py # Continuous-training versus resume verificationtests/ # Loss, sampling, data, entry point, and checkpoint checks```
Dataset definitions and runtime data loading live in `datasets/`. Offline assetpreparation tools live in `scripts/preparation/`.
## Installation
The observed runtime used Linux, Python 3.12.13, and PyTorch `2.9.1+cu129`.[requirements.txt](requirements.txt) records the main dependency versions observedduring extraction; it is not a complete lockfile of the original trainingenvironment.
```bashpython3.12 -m venv .venvsource .venv/bin/activatepython -m pip install --upgrade pippython -m pip install torch==2.9.1 torchvision==0.24.1 --index-url https://download.pytorch.org/whl/cu129python -m pip install -r requirements.txt```
Use a CUDA driver and GPU compatible with the selected PyTorch/xformers build.The default training configuration uses four GPUs with BF16 support. An existingcompatible PixArt environment can also be used.
Run the following commands from the repository root unless stated otherwise.
## Bash launcher
```textbash run.sh <train|validate|inference> <config.py> [arguments...]```
The configuration path is required. After preparing the resources describedbelow, use:
```bash# Train using config['world_size'] distributed workers.CUDA_VISIBLE_DEVICES=0,1,2,3 bash run.sh train configs/rfm.py
# Validate both RAW and EMA weights.CUDA_VISIBLE_DEVICES=0 bash run.sh validate configs/rfm.py \ --checkpoint output/rfm_mix50/checkpoints/update-100000.pth \ --output output/validation-100000
# Generate images from custom prompts using EMA weights.CUDA_VISIBLE_DEVICES=0 bash run.sh inference configs/rfm.py \ --checkpoint output/rfm_mix50/checkpoints/update-100000.pth \ --prompts examples/inference_prompts.json \ --weights ema --output output/inference-100000```
The launcher changes to the repository root, so all relative paths are resolvedfrom there. Set `PYTHON_BIN` to select an interpreter:
```bashPYTHON_BIN=/path/to/env/bin/python bash run.sh train configs/rfm.py```
`CUDA_VISIBLE_DEVICES` is passed through unchanged. Validation and inference usethe first visible GPU. Training arguments such as `--resume` and `--work-dir` areforwarded to the trainer. `bash run.sh train configs/rfm.py --help` displays helpwithout starting distributed workers.
Validation and inference read resource paths and sampling settings from thespecified configuration. Its model architecture and flow conventions must matchthe checkpoint. Use `--conditioning-cache` and `--vae-path` to override resourcepaths. Both modes require a new or empty output directory.
Validation uses the checkpoint's fixed prompts and seeds and verifies theconditioning cache against its recorded SHA-256 hash. Inference reads promptsand seeds from `--prompts`; `--cfg`, `--steps`, `--method`, `--atol`, and `--rtol`override the sampling configuration. `--steps` affects Heun only.
## Prepare external resources
The default configuration expects this layout. Resources may be copied into therepository or provided through symbolic links to existing storage.
```textassets/source_model/ # Pretrained checkpoint with transformer/ and scheduler/assets/pixart/ # Model snapshot with vae/, tokenizer/, and text_encoder/data/synth_images/flux1_dev_localized_narratives_synth512/data/synth_images/flux1_dev_synth512/output/theta_raw_to_v_setup/ # initial_raw_epsilon.pth and conditioning.ptoutput/datasets_512/FluxLocalizedNarratives/output/datasets_512/FluxSynth/```
Each source dataset needs a `metadata.jsonl` file. Each completed training cacheneeds `cache_settings.json`, `training_metadata.jsonl`, `latents/*.npz`, and`t5_embeddings/*.npz`.
The trainer checks source metadata, cache counts, source paths, and SHA-256 hashes.Moving a source dataset can invalidate the paths recorded in an existing cache;regenerate the cache or preserve its original source paths.
### Initialization weights and validation conditioning
```bashpython -m scripts.preparation.prepare_theta_v \ --source assets/source_model \ --snapshot assets/pixart \ --prompts examples/validation_prompts.json \ --output output/theta_raw_to_v_setup```
The reference experiment used the PixArt snapshot`50f702106901db6d0f8b67eb88e814c56ded2692`.
### Dataset caches
`cache_synthetic_dataset.py` currently uses that snapshot at:
```text~/.cache/huggingface/hub/models--PixArt-alpha--PixArt-XL-2-512x512/snapshots/50f702106901db6d0f8b67eb88e814c56ded2692```
Provide the model there or update the script's `snapshot` variable to point to`assets/pixart` before generating caches.
Generate and finalize the first dataset cache with one process:
```bashpython -m scripts.preparation.cache_synthetic_dataset \ --source data/synth_images/flux1_dev_localized_narratives_synth512 \ --output output/datasets_512/FluxLocalizedNarratives --shards 1 --shard 0
python -m scripts.preparation.cache_synthetic_dataset \ --source data/synth_images/flux1_dev_localized_narratives_synth512 \ --output output/datasets_512/FluxLocalizedNarratives --shards 1 --finalize```
Repeat both commands for the second dataset, using`data/synth_images/flux1_dev_synth512` as the source and`output/datasets_512/FluxSynth` as the output.
For four-GPU cache preparation, run four workers with `--shards 4` and distinct`--shard` values from 0 through 3, assigning one GPU to each worker. Once everyworker finishes, finalize with `--shards 4 --finalize`.
## Training
After preparing all resources, start a new run:
```bashHF_HUB_OFFLINE=1 CUDA_VISIBLE_DEVICES=0,1,2,3 \ bash run.sh train configs/rfm.py```
The default output directory is `output/rfm_mix50`. Use a new `--work-dir` whenstarting another run or resuming an existing one. The launcher defaults`OMP_NUM_THREADS` to 4 and starts `torch.distributed.run` with the configurednumber of workers.
### Optional background preparation and training
The training entry point also supports the original background controller:
```bashbash run.sh train configs/rfm.py --launch```
This mode requires a passing `output/rfm_mix50_smoke/verification.json`, thecorresponding pilot caches, initialization weights, and model assets. It enforcesfour GPUs and a per-GPU batch size of eight. If the full caches already exist,use direct training as shown above; the smoke verification artifacts are notrequired for that path.
Controller state and logs are written to `preparation/status.json` and`preparation/controller.log` under the work directory. Training output is loggedto `console.log`.
Both launch modes accept `--work-dir`, `--max-train-steps`,`--validate-every-updates`, and `--save-every-updates`. Background mode forwardsthese settings to the training process. `--launch` is for new training only andcannot be combined with `--resume` or invoked under `torchrun`.
### Resume training
Use the same configuration and resource paths as the saved run, with a new outputdirectory. For example, resume a run from step 5,000 toward a total of 100,000optimizer updates:
```bashHF_HUB_OFFLINE=1 CUDA_VISIBLE_DEVICES=0,1,2,3 \ bash run.sh train configs/rfm.py \ --resume output/rfm_mix50/checkpoints/update-005000.pth \ --work-dir output/rfm_mix50_resumed \ --max-train-steps 100000```
The trainer strictly compares the checkpoint's configuration and data hashes.Only the work directory, total update count, and save/validation/logging intervalsmay change. Preserve all other training settings and resource paths.
To resume a checkpoint from the original project, restore the configurationvalues recorded in that checkpoint and make its paths resolve correctly. Theexample paths `assets/source_model` and `assets/pixart/vae` cannot replacehistorical paths during resume without triggering `Resume changed trainingsemantics`. No separate historical configuration is maintained in this repository.
## Validation and reproduction
`scripts/validate_rfm.py` calls the same validation function used during training.It produces four RAW and four EMA images, along with latent tensors, prompts,and sampler metadata under `<output>/validation/update-<step>/`. The effectiveconfiguration is saved as `<output>/validation_config.json`.
For the original 100K checkpoint, the following command uses assets from theparent workspace and the local Hugging Face cache:
```bashCUDA_VISIBLE_DEVICES=0 HF_HUB_OFFLINE=1 \ bash run.sh validate configs/rfm.py \ --checkpoint ../output/rfm_from_A_flux_raw_mix50_100k/resume-030000-to-100000/checkpoints/update-100000.pth \ --conditioning-cache ../output/theta_raw_to_v_setup/conditioning.pt \ --vae-path "$HOME/.cache/huggingface/hub/models--PixArt-alpha--PixArt-XL-2-512x512/snapshots/50f702106901db6d0f8b67eb88e814c56ded2692/vae" \ --output output/revalidate-100000```
These resource locations are specific to the original workspace. Adjust them foranother machine, and select an interpreter with the required dependencies using`PYTHON_BIN` if needed.
A local verification through `run.sh` reproduced all eight original 100K PNGsbyte for byte and both latent tensors exactly. RAW and EMA sampling used 182 and176 function evaluations, respectively. Identical results are not guaranteedacross GPU models or dependency versions.
When calling `python -m scripts.validate_rfm` directly without `--config`, samplersettings and default resource paths come from the checkpoint. Resource paths canstill be overridden with `--conditioning-cache` and `--vae-path`.
## Custom inference
Supply a JSON list with a unique filename-safe `case_id`, a nonempty `prompt`,and a nonnegative integer `seed` for each image:
```json[ { "case_id": "example-01", "prompt": "A small cabin beside a lake at sunrise", "seed": 42 }]```
Use [examples/inference_prompts.json](examples/inference_prompts.json) as astarting point. Select weights with `--weights raw` or `--weights ema`; thedefault is `raw`.
Inference needs `tokenizer/` and `text_encoder/` alongside the configured `vae/`directory. Prompts are lowercased and stripped before encoding and must fit the120-token training limit. The output includes one PNG per case,`prompt_embeddings.pt`, and a `validation.json` report.
Through `run.sh`, sampling defaults come from the supplied configuration:`configs/rfm.py` uses dopri5 and CFG 4. Direct Python invocation without `--config`uses checkpoint resource paths and defaults to Heun with 40 steps and CFG 2.
## Checks
```bashpython -m pytest -q testsbash run.sh train configs/rfm.py --helpbash run.sh validate configs/rfm.py --helpbash run.sh inference configs/rfm.py --help```
The tests run on CPU and cover RFM loss and sampling, dataset loading, samplingcursors, checkpoint restoration, and launcher behavior. Training and imagegeneration require CUDA.
## License
The code retains the original project's Apache-2.0 [LICENSE](LICENSE) and theauthor and license notices in copied files. External models and datasets remainsubject to their respective licenses.123version https://git-lfs.github.com/spec/v1oid sha256:9e57f61d67a087925a4930ac1b191f4fede381caad508f19baf0b36194ad9674size 97878740541234567891011121314151617181920212223242526272829"""PixArt XL/2 RFM: 512px, balanced 50/50 data, 0–100K updates.
Paths are relative to the repository root."""config = dict( model='PixArt_XL_2', image_size=512, prediction_type='flow_velocity', path='linear', time_sampling='uniform_continuous', time_embedding='999*(1-t)', loss='unweighted_mse', out_channels=4, head_initialization='zero', qk_norm='rms_norm', grad_checkpointing=False, mixed_precision='bf16', source_model='assets/source_model', source_weights='raw', source_checkpoint_sha256='fecb75bebf36bcadc3e1ce97ffecf2739482d3f0fe5e61ee33b91ccf30a2de02', init_checkpoint='output/theta_raw_to_v_setup/initial_raw_epsilon.pth', conditioning_cache='output/theta_raw_to_v_setup/conditioning.pt', vae_path='assets/pixart/vae', source_datasets=['data/synth_images/flux1_dev_localized_narratives_synth512', 'data/synth_images/flux1_dev_synth512'], source_counts=[50000, 76708], source_weights_per_batch=[0.5, 0.5], data_roots=['output/datasets_512/FluxLocalizedNarratives', 'output/datasets_512/FluxSynth'], world_size=4, batch_size=8, accumulation_steps=1, dataloader_workers=4, prefetch_factor=2, learning_rate=1e-5, betas=(0.9, 0.999), adam_eps=1e-8, weight_decay=0., warmup_updates=500, max_grad_norm=1., ema_decay=0.9999, class_dropout_prob=0.1, max_train_steps=100000, save_every_updates=5000, validate_every_updates=500, log_every_updates=10, seed=43, sampling_method='dopri5', sampling_steps=50, sampling_atol=1e-6, sampling_rtol=1e-3, cfg_scale=4., validation_seeds=[42, 43, 44, 45], work_dir='output/rfm_mix50',)1"""RFM dataset definitions and their loading and sampling support."""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Cached latent/text loading and balanced, resumable RFM batches."""import mathimport numpy as npimport torchfrom torch.utils.data import Dataset, Sampler
def read_cache(record): root, row = record with np.load(root / row['latent_file'], allow_pickle=False) as data: mean, std = data['latent'], data['std'] if bool(data['scaled']) or not np.isclose(float(data['scaling_factor']), 0.18215): raise ValueError(f'Unexpected latent scaling: {row["latent_file"]}') with np.load(root / row['t5_file'], allow_pickle=False) as data: feature, mask = data['caption_feature'], data['attention_mask'] length = feature.shape[1] if feature.ndim == 3 else 0 if mean.shape != (4, 64, 64) or std.shape != mean.shape or feature.shape != (1, length, 4096) or not 1 <= length <= 120 or mask.shape != (1, length): raise ValueError(f'Unexpected cache shape: {row["file_name"]}') if not all(np.isfinite(value).all() for value in (mean, std, feature)) or np.any(std < 0): raise ValueError(f'Invalid cached values: {row["file_name"]}') if not np.isin(mask, [0, 1]).all() or not mask.any(): raise ValueError(f'Invalid caption mask: {row["file_name"]}') if np.any(np.diff(mask[0].astype(np.int64)) > 0): raise ValueError('Caption masks must use right padding') expected_length = row.get('t5_length', min(row.get('t5_token_count', 120), 120)) if ('t5_length' in row or 't5_token_count' in row) and int(mask.sum()) != expected_length: raise ValueError('Caption length differs from manifest') if length < 120: feature = np.pad(feature, ((0, 0), (0, 120-length), (0, 0))) mask = np.pad(mask, ((0, 0), (0, 120-length))) return mean, std, feature, mask[0]
class CachedDataset(Dataset): """Read only requested NPZ records; workers prepare tensors in host memory."""
def __init__(self, records): self.records = records
def __len__(self): return len(self.records)
def __getitem__(self, index): mean, std, caption, mask = read_cache(self.records[index]) return (torch.from_numpy(mean).float(), torch.from_numpy(std).float(), torch.from_numpy(caption).to(torch.bfloat16), torch.from_numpy(mask).bool())
class BalancedFlowSampler(Sampler): def __init__(self, lengths, batch_size, world_size, rank, seed, start_step, stop_step): if len(lengths) != 2 or batch_size % 2 or min(lengths) < world_size * batch_size // 2: raise ValueError('Two sources need at least one global half-batch each') self.lengths = lengths self.batch_size = batch_size self.world_size = world_size self.rank = rank self.seed = seed self.start_step = start_step self.stop_step = stop_step
def __iter__(self): half = self.batch_size // 2 global_half = half * self.world_size cycles = [-1, -1] orders = [None, None] for step in range(self.start_step, self.stop_step): batch = [] offset = 0 for source, length in enumerate(self.lengths): batches = math.ceil(length / global_half) cycle, position = divmod(step, batches) if cycles[source] != cycle: generator = torch.Generator().manual_seed(self.seed + source * 1000000007 + cycle) order = torch.randperm(length, generator=generator) # Pad only the final global half-batch; no source is truncated. padding = batches * global_half - length orders[source] = torch.cat([order, order[:padding]]) cycles[source] = cycle begin = position * global_half + self.rank * half batch.extend((orders[source][begin:begin + half] + offset).tolist()) offset += length yield batch
def __len__(self): return self.stop_step - self.start_step1"""PixArt rectified-flow training and sampling."""123456789101112"""Diffusion math can be imported without the optional Transformer dependencies."""
__all__ = ["PixArt", "PixArt_XL_2"]
def __getattr__(name): from importlib import import_module nets = import_module(".nets", __name__) try: return getattr(nets, name) except AttributeError: raise AttributeError(name) from None12345678910111213141516from mmcv import Registry
from diffusion.model.utils import set_grad_checkpoint
MODELS = Registry('models')
def build_model(cfg, use_grad_checkpoint=False, use_fp32_attention=False, gc_step=1, **kwargs): from diffusion.model import nets # register models only when building one
if isinstance(cfg, str): cfg = dict(type=cfg) model = MODELS.build(cfg, default_args=kwargs) if use_grad_checkpoint: set_grad_checkpoint(model, use_fp32_attention=use_fp32_attention, gc_step=gc_step) return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.
# This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.# --------------------------------------------------------# References:# GLIDE: https://github.com/openai/glide-text2im# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py# --------------------------------------------------------import mathimport torchimport torch.nn as nnimport osimport numpy as npfrom timm.models.layers import DropPathfrom timm.models.vision_transformer import PatchEmbed, Mlp
from diffusion.model.builder import MODELSfrom diffusion.model.utils import auto_grad_checkpoint, to_2tuplefrom diffusion.model.nets.PixArt_blocks import t2i_modulate, CaptionEmbedder, WindowAttention, MultiHeadCrossAttention, T2IFinalLayer, TimestepEmbedder, LabelEmbedder, FinalLayerfrom diffusion.utils.logger import get_root_logger
class PixArtBlock(nn.Module): """ A PixArt block with adaptive layer norm (adaLN-single) conditioning. """
def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, drop_path=0., window_size=0, input_size=None, use_rel_pos=False, **block_kwargs): super().__init__() self.hidden_size = hidden_size self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.attn = WindowAttention(hidden_size, num_heads=num_heads, qkv_bias=True, input_size=input_size if window_size == 0 else (window_size, window_size), use_rel_pos=use_rel_pos, **block_kwargs) self.cross_attn = MultiHeadCrossAttention(hidden_size, num_heads, **block_kwargs) self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) # to be compatible with lower version pytorch approx_gelu = lambda: nn.GELU(approximate="tanh") self.mlp = Mlp(in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio), act_layer=approx_gelu, drop=0) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.window_size = window_size self.scale_shift_table = nn.Parameter(torch.randn(6, hidden_size) / hidden_size ** 0.5)
def forward(self, x, y, t, mask=None, **kwargs): B, N, C = x.shape
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (self.scale_shift_table[None] + t.reshape(B, 6, -1)).chunk(6, dim=1) x = x + self.drop_path(gate_msa * self.attn(t2i_modulate(self.norm1(x), shift_msa, scale_msa)).reshape(B, N, C)) x = x + self.cross_attn(x, y, mask) x = x + self.drop_path(gate_mlp * self.mlp(t2i_modulate(self.norm2(x), shift_mlp, scale_mlp)))
return x
############################################################################## Core PixArt Model ##################################################################################@MODELS.register_module()class PixArt(nn.Module): """ Diffusion model with a Transformer backbone. """
def __init__(self, input_size=32, patch_size=2, in_channels=4, hidden_size=1152, depth=28, num_heads=16, mlp_ratio=4.0, class_dropout_prob=0.1, pred_sigma=True, drop_path: float = 0., window_size=0, window_block_indexes=None, use_rel_pos=False, caption_channels=4096, lewei_scale=1.0, config=None, model_max_length=120, **kwargs): if window_block_indexes is None: window_block_indexes = [] super().__init__() self.pred_sigma = pred_sigma self.qk_norm = kwargs.get('qk_norm', False) self.in_channels = in_channels self.out_channels = in_channels * 2 if pred_sigma else in_channels self.patch_size = patch_size self.num_heads = num_heads self.lewei_scale = lewei_scale,
self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True) self.t_embedder = TimestepEmbedder(hidden_size) num_patches = self.x_embedder.num_patches self.base_size = input_size // self.patch_size # Will use fixed sin-cos embedding: self.register_buffer("pos_embed", torch.zeros(1, num_patches, hidden_size))
approx_gelu = lambda: nn.GELU(approximate="tanh") self.t_block = nn.Sequential( nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True) ) self.y_embedder = CaptionEmbedder(in_channels=caption_channels, hidden_size=hidden_size, uncond_prob=class_dropout_prob, act_layer=approx_gelu, token_num=model_max_length) drop_path = [x.item() for x in torch.linspace(0, drop_path, depth)] # stochastic depth decay rule self.blocks = nn.ModuleList([ PixArtBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio, drop_path=drop_path[i], input_size=(input_size // patch_size, input_size // patch_size), window_size=window_size if i in window_block_indexes else 0, use_rel_pos=use_rel_pos if i in window_block_indexes else False, qk_norm=self.qk_norm) for i in range(depth) ]) self.final_layer = T2IFinalLayer(hidden_size, patch_size, self.out_channels)
self.initialize_weights()
if config: logger = get_root_logger(os.path.join(config.work_dir, 'train_log.log')) logger.warning(f"lewei scale: {self.lewei_scale}, base size: {self.base_size}") else: print(f'Warning: lewei scale: {self.lewei_scale}, base size: {self.base_size}')
def forward(self, x, timestep, y, mask=None, data_info=None, **kwargs): """ Forward pass of PixArt. x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) t: (N,) tensor of diffusion timesteps y: (N, 1, 120, C) tensor of class labels """ x = x.to(self.dtype) timestep = timestep.to(self.dtype) y = y.to(self.dtype) pos_embed = self.pos_embed.to(self.dtype) self.h, self.w = x.shape[-2]//self.patch_size, x.shape[-1]//self.patch_size x = self.x_embedder(x) + pos_embed # (N, T, D), where T = H * W / patch_size ** 2 t = self.t_embedder(timestep.to(x.dtype)) # (N, D) t0 = self.t_block(t) y = self.y_embedder(y, self.training) # (N, 1, L, D) if self.qk_norm: y = y.squeeze(1) y_lens = mask.reshape(y.shape[0], -1) if mask is not None else None elif mask is not None: if mask.shape[0] != y.shape[0]: mask = mask.repeat(y.shape[0] // mask.shape[0], 1) mask = mask.squeeze(1).squeeze(1) y = y.squeeze(1).masked_select(mask.unsqueeze(-1) != 0).view(1, -1, x.shape[-1]) y_lens = mask.sum(dim=1).tolist() else: y_lens = [y.shape[2]] * y.shape[0] y = y.squeeze(1).view(1, -1, x.shape[-1]) for block in self.blocks: x = auto_grad_checkpoint(block, x, y, t0, y_lens) # (N, T, D) #support grad checkpoint x = self.final_layer(x, t) # (N, T, patch_size ** 2 * out_channels) x = self.unpatchify(x) # (N, out_channels, H, W) return x
def forward_with_dpmsolver(self, x, timestep, y, mask=None, **kwargs): """ dpm solver donnot need variance prediction """ # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb model_out = self.forward(x, timestep, y, mask) return model_out.chunk(2, dim=1)[0]
def forward_with_cfg(self, x, timestep, y, cfg_scale, mask=None, **kwargs): """ Forward pass of PixArt, but also batches the unconditional forward pass for classifier-free guidance. """ # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb half = x[: len(x) // 2] combined = torch.cat([half, half], dim=0) model_out = self.forward(combined, timestep, y, mask, kwargs) model_out = model_out['x'] if isinstance(model_out, dict) else model_out eps, rest = model_out[:, :3], model_out[:, 3:] cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0) half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps) eps = torch.cat([half_eps, half_eps], dim=0) return torch.cat([eps, rest], dim=1)
def unpatchify(self, x): """ x: (N, T, patch_size**2 * C) imgs: (N, H, W, C) """ c = self.out_channels p = self.x_embedder.patch_size[0] h = w = int(x.shape[1] ** 0.5) assert h * w == x.shape[1]
x = x.reshape(shape=(x.shape[0], h, w, p, p, c)) x = torch.einsum('nhwpqc->nchpwq', x) return x.reshape(shape=(x.shape[0], c, h * p, h * p))
def initialize_weights(self): # Initialize transformer layers: def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0)
self.apply(_basic_init)
# Initialize (and freeze) pos_embed by sin-cos embedding: pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5), lewei_scale=self.lewei_scale, base_size=self.base_size) self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d): w = self.x_embedder.proj.weight.data nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
# Initialize timestep embedding MLP: nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02) nn.init.normal_(self.t_block[1].weight, std=0.02)
# Initialize caption embedding MLP: nn.init.normal_(self.y_embedder.y_proj.fc1.weight, std=0.02) nn.init.normal_(self.y_embedder.y_proj.fc2.weight, std=0.02)
# Zero-out adaLN modulation layers in PixArt blocks: for block in self.blocks: nn.init.constant_(block.cross_attn.proj.weight, 0) nn.init.constant_(block.cross_attn.proj.bias, 0)
# Zero-out output layers: nn.init.constant_(self.final_layer.linear.weight, 0) nn.init.constant_(self.final_layer.linear.bias, 0)
@property def dtype(self): return next(self.parameters()).dtype
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0, lewei_scale=1.0, base_size=16): """ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) """ if isinstance(grid_size, int): grid_size = to_2tuple(grid_size) grid_h = np.arange(grid_size[0], dtype=np.float32) / (grid_size[0]/base_size) / lewei_scale grid_w = np.arange(grid_size[1], dtype=np.float32) / (grid_size[1]/base_size) / lewei_scale grid = np.meshgrid(grid_w, grid_h) # here w goes first grid = np.stack(grid, axis=0) grid = grid.reshape([2, 1, grid_size[1], grid_size[0]])
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) if cls_token and extra_tokens > 0: pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0) return pos_embed
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): assert embed_dim % 2 == 0
# use half of dimensions to encode grid_h emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
return np.concatenate([emb_h, emb_w], axis=1)
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): """ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D) """ assert embed_dim % 2 == 0 omega = np.arange(embed_dim // 2, dtype=np.float64) omega /= embed_dim / 2. omega = 1. / 10000 ** omega # (D/2,)
pos = pos.reshape(-1) # (M,) out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
emb_sin = np.sin(out) # (M, D/2) emb_cos = np.cos(out) # (M, D/2)
return np.concatenate([emb_sin, emb_cos], axis=1)
################################################################################## PixArt Configs ##################################################################################@MODELS.register_module()def PixArt_XL_2(**kwargs): return PixArt(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.
# This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.# --------------------------------------------------------# References:# GLIDE: https://github.com/openai/glide-text2im# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py# --------------------------------------------------------import mathimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom timm.models.vision_transformer import Mlp, Attention as Attention_from einops import rearrange, repeatimport xformers.ops
from diffusion.model.utils import add_decomposed_rel_pos
class QKRMSNorm(nn.Module): """Match Theta's per-head RMSNorm, including the FP32 affine multiply."""
def __init__(self, head_dim, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(head_dim)) self.eps = eps
def forward(self, hidden): normalized = hidden.float() * torch.rsqrt(hidden.float().square().mean(-1, keepdim=True) + self.eps) return (normalized * self.weight.float()).to(hidden.dtype)
def modulate(x, shift, scale): return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
def t2i_modulate(x, shift, scale): return x * (1 + scale) + shift
class MultiHeadCrossAttention(nn.Module): def __init__(self, d_model, num_heads, attn_drop=0., proj_drop=0., qk_norm=False, **block_kwargs): super(MultiHeadCrossAttention, self).__init__() assert d_model % num_heads == 0, "d_model must be divisible by num_heads"
self.d_model = d_model self.num_heads = num_heads self.head_dim = d_model // num_heads self.qk_norm = qk_norm if qk_norm not in (False, True, 'rms_norm'): raise ValueError('QK normalization must be disabled, LayerNorm, or rms_norm') norm = QKRMSNorm if qk_norm == 'rms_norm' else nn.LayerNorm self.q_norm = norm(self.head_dim, eps=1e-6) if qk_norm else nn.Identity() self.k_norm = norm(self.head_dim, eps=1e-6) if qk_norm else nn.Identity()
self.q_linear = nn.Linear(d_model, d_model) self.kv_linear = nn.Linear(d_model, d_model*2) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(d_model, d_model) self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, cond, mask=None): # query: img tokens; key/value: condition; mask: if padding tokens B, N, C = x.shape
if self.qk_norm: # Keep padded captions and their masks on the GPU; no packing or CPU lengths. q = self.q_linear(x).view(B, N, self.num_heads, self.head_dim).transpose(1, 2) kv = self.kv_linear(cond).view(B, -1, 2, self.num_heads, self.head_dim) k, v = kv.permute(2, 0, 3, 1, 4).unbind(0) q, k = self.q_norm(q).to(v.dtype), self.k_norm(k).to(v.dtype) attn_mask = mask[:, None, None, :].bool() if mask is not None else None x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=self.attn_drop.p if self.training else 0.) x = x.transpose(1, 2).reshape(B, N, C) return self.proj_drop(self.proj(x))
q = self.q_linear(x).view(1, -1, self.num_heads, self.head_dim) kv = self.kv_linear(cond).view(1, -1, 2, self.num_heads, self.head_dim) k, v = kv.unbind(2) attn_bias = None if mask is not None: attn_bias = xformers.ops.fmha.BlockDiagonalMask.from_seqlens([N] * B, mask) x = xformers.ops.memory_efficient_attention(q, k, v, p=self.attn_drop.p, attn_bias=attn_bias) x = x.view(B, -1, C) x = self.proj(x) x = self.proj_drop(x)
# q = self.q_linear(x).reshape(B, -1, self.num_heads, self.head_dim) # kv = self.kv_linear(cond).reshape(B, -1, 2, self.num_heads, self.head_dim) # k, v = kv.unbind(2) # attn_bias = None # if mask is not None: # attn_bias = torch.zeros([B * self.num_heads, q.shape[1], k.shape[1]], dtype=q.dtype, device=q.device) # attn_bias.masked_fill_(mask.squeeze(1).repeat(self.num_heads, 1, 1) == 0, float('-inf')) # x = xformers.ops.memory_efficient_attention(q, k, v, p=self.attn_drop.p, attn_bias=attn_bias) # x = x.contiguous().reshape(B, -1, C) # x = self.proj(x) # x = self.proj_drop(x)
return x
class WindowAttention(Attention_): """Multi-head Attention block with relative position embeddings."""
def __init__( self, dim, num_heads=8, qkv_bias=True, use_rel_pos=False, rel_pos_zero_init=True, input_size=None, qk_norm=False, **block_kwargs, ): """ Args: dim (int): Number of input channels. num_heads (int): Number of attention heads. qkv_bias (bool: If True, add a learnable bias to query, key, value. rel_pos (bool): If True, add relative positional embeddings to the attention map. rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. input_size (int or None): Input resolution for calculating the relative positional parameter size. """ super().__init__(dim, num_heads=num_heads, qkv_bias=qkv_bias, **block_kwargs) self.qk_norm = qk_norm if qk_norm not in (False, True, 'rms_norm'): raise ValueError('QK normalization must be disabled, LayerNorm, or rms_norm') norm = QKRMSNorm if qk_norm == 'rms_norm' else nn.LayerNorm self.q_norm = norm(self.head_dim, eps=1e-6) if qk_norm else nn.Identity() self.k_norm = norm(self.head_dim, eps=1e-6) if qk_norm else nn.Identity()
self.use_rel_pos = use_rel_pos if self.use_rel_pos: # initialize relative positional embeddings self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, self.head_dim)) self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, self.head_dim))
if not rel_pos_zero_init: nn.init.trunc_normal_(self.rel_pos_h, std=0.02) nn.init.trunc_normal_(self.rel_pos_w, std=0.02)
def forward(self, x, mask=None): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) q, k, v = qkv.unbind(2) if self.qk_norm: q, k = self.q_norm(q).to(v.dtype), self.k_norm(k).to(v.dtype) x = F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), dropout_p=self.attn_drop.p if self.training else 0.) return self.proj_drop(self.proj(x.transpose(1, 2).reshape(B, N, C))) if use_fp32_attention := getattr(self, 'fp32_attention', False): q, k, v = q.float(), k.float(), v.float()
attn_bias = None if mask is not None: attn_bias = torch.zeros([B * self.num_heads, q.shape[1], k.shape[1]], dtype=q.dtype, device=q.device) attn_bias.masked_fill_(mask.squeeze(1).repeat(self.num_heads, 1, 1) == 0, float('-inf')) x = xformers.ops.memory_efficient_attention(q, k, v, p=self.attn_drop.p, attn_bias=attn_bias)
x = x.view(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x
################################################################################## AMP attention with fp32 softmax to fix loss NaN problem during training ##################################################################################class Attention(Attention_): def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple) use_fp32_attention = getattr(self, 'fp32_attention', False) if use_fp32_attention: q, k = q.float(), k.float() with torch.cuda.amp.autocast(enabled=not use_fp32_attention): attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x
class FinalLayer(nn.Module): """ The final layer of PixArt. """
def __init__(self, hidden_size, patch_size, out_channels): super().__init__() self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True) self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True) )
def forward(self, x, c): shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) x = modulate(self.norm_final(x), shift, scale) x = self.linear(x) return x
class T2IFinalLayer(nn.Module): """ The final layer of PixArt. """
def __init__(self, hidden_size, patch_size, out_channels): super().__init__() self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True) self.scale_shift_table = nn.Parameter(torch.randn(2, hidden_size) / hidden_size ** 0.5) self.out_channels = out_channels
def forward(self, x, t): shift, scale = (self.scale_shift_table[None] + t[:, None]).chunk(2, dim=1) x = t2i_modulate(self.norm_final(x), shift, scale) x = self.linear(x) return x
class MaskFinalLayer(nn.Module): """ The final layer of PixArt. """
def __init__(self, final_hidden_size, c_emb_size, patch_size, out_channels): super().__init__() self.norm_final = nn.LayerNorm(final_hidden_size, elementwise_affine=False, eps=1e-6) self.linear = nn.Linear(final_hidden_size, patch_size * patch_size * out_channels, bias=True) self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(c_emb_size, 2 * final_hidden_size, bias=True) ) def forward(self, x, t): shift, scale = self.adaLN_modulation(t).chunk(2, dim=1) x = modulate(self.norm_final(x), shift, scale) x = self.linear(x) return x
class DecoderLayer(nn.Module): """ The final layer of PixArt. """
def __init__(self, hidden_size, decoder_hidden_size): super().__init__() self.norm_decoder = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.linear = nn.Linear(hidden_size, decoder_hidden_size, bias=True) self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True) ) def forward(self, x, t): shift, scale = self.adaLN_modulation(t).chunk(2, dim=1) x = modulate(self.norm_decoder(x), shift, scale) x = self.linear(x) return x
################################################################################## Embedding Layers for Timesteps and Class Labels ##################################################################################class TimestepEmbedder(nn.Module): """ Embeds scalar timesteps into vector representations. """
def __init__(self, hidden_size, frequency_embedding_size=256): super().__init__() self.mlp = nn.Sequential( nn.Linear(frequency_embedding_size, hidden_size, bias=True), nn.SiLU(), nn.Linear(hidden_size, hidden_size, bias=True), ) self.frequency_embedding_size = frequency_embedding_size
@staticmethod def timestep_embedding(t, dim, max_period=10000): """ Create sinusoidal timestep embeddings. :param t: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an (N, D) Tensor of positional embeddings. """ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half) args = t[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding
def forward(self, t): t_freq = self.timestep_embedding(t, self.frequency_embedding_size).to(self.dtype) return self.mlp(t_freq)
@property def dtype(self): # 返回模型参数的数据类型 return next(self.parameters()).dtype
class SizeEmbedder(TimestepEmbedder): """ Embeds scalar timesteps into vector representations. """
def __init__(self, hidden_size, frequency_embedding_size=256): super().__init__(hidden_size=hidden_size, frequency_embedding_size=frequency_embedding_size) self.mlp = nn.Sequential( nn.Linear(frequency_embedding_size, hidden_size, bias=True), nn.SiLU(), nn.Linear(hidden_size, hidden_size, bias=True), ) self.frequency_embedding_size = frequency_embedding_size self.outdim = hidden_size
def forward(self, s, bs): if s.ndim == 1: s = s[:, None] assert s.ndim == 2 if s.shape[0] != bs: s = s.repeat(bs//s.shape[0], 1) assert s.shape[0] == bs b, dims = s.shape[0], s.shape[1] s = rearrange(s, "b d -> (b d)") s_freq = self.timestep_embedding(s, self.frequency_embedding_size).to(self.dtype) s_emb = self.mlp(s_freq) s_emb = rearrange(s_emb, "(b d) d2 -> b (d d2)", b=b, d=dims, d2=self.outdim) return s_emb
@property def dtype(self): # 返回模型参数的数据类型 return next(self.parameters()).dtype
class LabelEmbedder(nn.Module): """ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. """
def __init__(self, num_classes, hidden_size, dropout_prob): super().__init__() use_cfg_embedding = dropout_prob > 0 self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size) self.num_classes = num_classes self.dropout_prob = dropout_prob
def token_drop(self, labels, force_drop_ids=None): """ Drops labels to enable classifier-free guidance. """ if force_drop_ids is None: drop_ids = torch.rand(labels.shape[0]).cuda() < self.dropout_prob else: drop_ids = force_drop_ids == 1 labels = torch.where(drop_ids, self.num_classes, labels) return labels
def forward(self, labels, train, force_drop_ids=None): use_dropout = self.dropout_prob > 0 if (train and use_dropout) or (force_drop_ids is not None): labels = self.token_drop(labels, force_drop_ids) return self.embedding_table(labels)
class CaptionEmbedder(nn.Module): """ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. """
def __init__(self, in_channels, hidden_size, uncond_prob, act_layer=nn.GELU(approximate='tanh'), token_num=120): super().__init__() self.y_proj = Mlp(in_features=in_channels, hidden_features=hidden_size, out_features=hidden_size, act_layer=act_layer, drop=0) self.register_buffer("y_embedding", torch.randn(token_num, in_channels) / in_channels ** 0.5) self.uncond_prob = uncond_prob
def token_drop(self, caption, force_drop_ids=None): """ Drops labels to enable classifier-free guidance. """ if force_drop_ids is None: drop_ids = torch.rand(caption.shape[0], device=caption.device) < self.uncond_prob else: drop_ids = force_drop_ids == 1 caption = torch.where(drop_ids[:, None, None, None], self.y_embedding, caption) return caption
def forward(self, caption, train, force_drop_ids=None): if train: assert caption.shape[2:] == self.y_embedding.shape use_dropout = self.uncond_prob > 0 if (train and use_dropout) or (force_drop_ids is not None): caption = self.token_drop(caption, force_drop_ids) caption = self.y_proj(caption) return caption
class CaptionEmbedderDoubleBr(nn.Module): """ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. """
def __init__(self, in_channels, hidden_size, uncond_prob, act_layer=nn.GELU(approximate='tanh'), token_num=120): super().__init__() self.proj = Mlp(in_features=in_channels, hidden_features=hidden_size, out_features=hidden_size, act_layer=act_layer, drop=0) self.embedding = nn.Parameter(torch.randn(1, in_channels) / 10 ** 0.5) self.y_embedding = nn.Parameter(torch.randn(token_num, in_channels) / 10 ** 0.5) self.uncond_prob = uncond_prob
def token_drop(self, global_caption, caption, force_drop_ids=None): """ Drops labels to enable classifier-free guidance. """ if force_drop_ids is None: drop_ids = torch.rand(global_caption.shape[0]).cuda() < self.uncond_prob else: drop_ids = force_drop_ids == 1 global_caption = torch.where(drop_ids[:, None], self.embedding, global_caption) caption = torch.where(drop_ids[:, None, None, None], self.y_embedding, caption) return global_caption, caption
def forward(self, caption, train, force_drop_ids=None): assert caption.shape[2: ] == self.y_embedding.shape global_caption = caption.mean(dim=2).squeeze() use_dropout = self.uncond_prob > 0 if (train and use_dropout) or (force_drop_ids is not None): global_caption, caption = self.token_drop(global_caption, caption, force_drop_ids) y_embed = self.proj(global_caption) return y_embed, caption1from .PixArt import PixArt, PixArt_XL_2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239# -*- coding: utf-8 -*-import osimport reimport htmlimport urllib.parse as ul
import ftfyimport torchfrom bs4 import BeautifulSoupfrom transformers import T5EncoderModel, AutoTokenizerfrom huggingface_hub import hf_hub_download
class T5Embedder:
available_models = ['t5-v1_1-xxl'] bad_punct_regex = re.compile(r'['+'#®•©™&@·º½¾¿¡§~'+'\)'+'\('+'\]'+'\['+'\}'+'\{'+'\|'+'\\'+'\/'+'\*' + r']{1,}') # noqa
def __init__(self, device, dir_or_name='t5-v1_1-xxl', *, local_cache=False, cache_dir=None, hf_token=None, use_text_preprocessing=True, t5_model_kwargs=None, torch_dtype=None, use_offload_folder=None, model_max_length=120): self.device = torch.device(device) self.torch_dtype = torch_dtype or torch.bfloat16 if t5_model_kwargs is None: t5_model_kwargs = {'low_cpu_mem_usage': True, 'torch_dtype': self.torch_dtype} if use_offload_folder is not None: t5_model_kwargs['offload_folder'] = use_offload_folder t5_model_kwargs['device_map'] = { 'shared': self.device, 'encoder.embed_tokens': self.device, 'encoder.block.0': self.device, 'encoder.block.1': self.device, 'encoder.block.2': self.device, 'encoder.block.3': self.device, 'encoder.block.4': self.device, 'encoder.block.5': self.device, 'encoder.block.6': self.device, 'encoder.block.7': self.device, 'encoder.block.8': self.device, 'encoder.block.9': self.device, 'encoder.block.10': self.device, 'encoder.block.11': self.device, 'encoder.block.12': 'disk', 'encoder.block.13': 'disk', 'encoder.block.14': 'disk', 'encoder.block.15': 'disk', 'encoder.block.16': 'disk', 'encoder.block.17': 'disk', 'encoder.block.18': 'disk', 'encoder.block.19': 'disk', 'encoder.block.20': 'disk', 'encoder.block.21': 'disk', 'encoder.block.22': 'disk', 'encoder.block.23': 'disk', 'encoder.final_layer_norm': 'disk', 'encoder.dropout': 'disk', } else: t5_model_kwargs['device_map'] = {'shared': self.device, 'encoder': self.device}
self.use_text_preprocessing = use_text_preprocessing self.hf_token = hf_token self.cache_dir = cache_dir or os.path.expanduser('~/.cache/IF_') self.dir_or_name = dir_or_name tokenizer_path, path = dir_or_name, dir_or_name if local_cache: cache_dir = os.path.join(self.cache_dir, dir_or_name) tokenizer_path, path = cache_dir, cache_dir elif dir_or_name in self.available_models: cache_dir = os.path.join(self.cache_dir, dir_or_name) for filename in [ 'config.json', 'special_tokens_map.json', 'spiece.model', 'tokenizer_config.json', 'pytorch_model.bin.index.json', 'pytorch_model-00001-of-00002.bin', 'pytorch_model-00002-of-00002.bin' ]: hf_hub_download(repo_id=f'DeepFloyd/{dir_or_name}', filename=filename, cache_dir=cache_dir, force_filename=filename, token=self.hf_token) tokenizer_path, path = cache_dir, cache_dir else: cache_dir = os.path.join(self.cache_dir, 't5-v1_1-xxl') for filename in [ 'config.json', 'special_tokens_map.json', 'spiece.model', 'tokenizer_config.json', ]: hf_hub_download(repo_id='DeepFloyd/t5-v1_1-xxl', filename=filename, cache_dir=cache_dir, force_filename=filename, token=self.hf_token) tokenizer_path = cache_dir
# Also accept a fully cached official Diffusers snapshot. Keep native # caption cleaning/tokenization and T5 model unchanged. if local_cache and os.path.isdir(os.path.join(path, 'text_encoder')): tokenizer_path = os.path.join(path, 'tokenizer') path = os.path.join(path, 'text_encoder')
print(tokenizer_path) self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path) self.model = T5EncoderModel.from_pretrained(path, **t5_model_kwargs).eval() self.model_max_length = model_max_length
def get_text_embeddings(self, texts): texts = [self.text_preprocessing(text) for text in texts]
text_tokens_and_mask = self.tokenizer( texts, max_length=self.model_max_length, padding='max_length', truncation=True, return_attention_mask=True, add_special_tokens=True, return_tensors='pt' )
text_tokens_and_mask['input_ids'] = text_tokens_and_mask['input_ids'] text_tokens_and_mask['attention_mask'] = text_tokens_and_mask['attention_mask']
with torch.no_grad(): text_encoder_embs = self.model( input_ids=text_tokens_and_mask['input_ids'].to(self.device), attention_mask=text_tokens_and_mask['attention_mask'].to(self.device), )['last_hidden_state'].detach() return text_encoder_embs, text_tokens_and_mask['attention_mask'].to(self.device)
def text_preprocessing(self, text): if self.use_text_preprocessing: # The exact text cleaning as was in the training stage: text = self.clean_caption(text) text = self.clean_caption(text) return text else: return text.lower().strip()
@staticmethod def basic_clean(text): text = ftfy.fix_text(text) text = html.unescape(html.unescape(text)) return text.strip()
def clean_caption(self, caption): caption = str(caption) caption = ul.unquote_plus(caption) caption = caption.strip().lower() caption = re.sub('<person>', 'person', caption) # urls: caption = re.sub( r'\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))', # noqa '', caption) # regex for urls caption = re.sub( r'\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))', # noqa '', caption) # regex for urls # html: caption = BeautifulSoup(caption, features='html.parser').text
# @<nickname> caption = re.sub(r'@[\w\d]+\b', '', caption)
# 31C0—31EF CJK Strokes # 31F0—31FF Katakana Phonetic Extensions # 3200—32FF Enclosed CJK Letters and Months # 3300—33FF CJK Compatibility # 3400—4DBF CJK Unified Ideographs Extension A # 4DC0—4DFF Yijing Hexagram Symbols # 4E00—9FFF CJK Unified Ideographs caption = re.sub(r'[\u31c0-\u31ef]+', '', caption) caption = re.sub(r'[\u31f0-\u31ff]+', '', caption) caption = re.sub(r'[\u3200-\u32ff]+', '', caption) caption = re.sub(r'[\u3300-\u33ff]+', '', caption) caption = re.sub(r'[\u3400-\u4dbf]+', '', caption) caption = re.sub(r'[\u4dc0-\u4dff]+', '', caption) caption = re.sub(r'[\u4e00-\u9fff]+', '', caption) #######################################################
# все виды тире / all types of dash --> "-" caption = re.sub( r'[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+', # noqa '-', caption)
# кавычки к одному стандарту caption = re.sub(r'[`´«»“”¨]', '"', caption) caption = re.sub(r'[‘’]', "'", caption)
# " caption = re.sub(r'"?', '', caption) # & caption = re.sub(r'&', '', caption)
# ip adresses: caption = re.sub(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', ' ', caption)
# article ids: caption = re.sub(r'\d:\d\d\s+$', '', caption)
# \n caption = re.sub(r'\\n', ' ', caption)
# "#123" caption = re.sub(r'#\d{1,3}\b', '', caption) # "#12345.." caption = re.sub(r'#\d{5,}\b', '', caption) # "123456.." caption = re.sub(r'\b\d{6,}\b', '', caption) # filenames: caption = re.sub(r'[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)', '', caption)
# caption = re.sub(r'[\"\']{2,}', r'"', caption) # """AUSVERKAUFT""" caption = re.sub(r'[\.]{2,}', r' ', caption) # """AUSVERKAUFT"""
caption = re.sub(self.bad_punct_regex, r' ', caption) # ***AUSVERKAUFT***, #AUSVERKAUFT caption = re.sub(r'\s+\.\s+', r' ', caption) # " . "
# this-is-my-cute-cat / this_is_my_cute_cat regex2 = re.compile(r'(?:\-|\_)') if len(re.findall(regex2, caption)) > 3: caption = re.sub(regex2, ' ', caption)
caption = self.basic_clean(caption)
caption = re.sub(r'\b[a-zA-Z]{1,3}\d{3,15}\b', '', caption) # jc6640 caption = re.sub(r'\b[a-zA-Z]+\d+[a-zA-Z]+\b', '', caption) # jc6640vc caption = re.sub(r'\b\d+[a-zA-Z]+\d+\b', '', caption) # 6640vc231
caption = re.sub(r'(worldwide\s+)?(free\s+)?shipping', '', caption) caption = re.sub(r'(free\s)?download(\sfree)?', '', caption) caption = re.sub(r'\bclick\b\s(?:for|on)\s\w+', '', caption) caption = re.sub(r'\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?', '', caption) caption = re.sub(r'\bpage\s+\d+\b', '', caption)
caption = re.sub(r'\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b', r' ', caption) # j2d1a2a...
caption = re.sub(r'\b\d+\.?\d*[xх×]\d+\.?\d*\b', '', caption)
caption = re.sub(r'\b\s+\:\s+', r': ', caption) caption = re.sub(r'(\D[,\./])\b', r'\1 ', caption) caption = re.sub(r'\s+', ' ', caption)
caption.strip()
caption = re.sub(r'^[\"\']([\w\W]+)[\"\']$', r'\1', caption) caption = re.sub(r'^[\'\_,\-\:;]', r'', caption) caption = re.sub(r'[\'\_,\-\:\-\+]$', r'', caption) caption = re.sub(r'^\.\S+$', '', caption)
return caption.strip()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510import osimport sysimport torch.nn as nnfrom torch.utils.checkpoint import checkpoint, checkpoint_sequentialimport torch.nn.functional as Fimport torchimport torch.distributed as distimport reimport mathfrom collections.abc import Iterablefrom itertools import repeatfrom torchvision import transforms as Timport randomfrom PIL import Image
def _ntuple(n): def parse(x): if isinstance(x, Iterable) and not isinstance(x, str): return x return tuple(repeat(x, n)) return parse
to_1tuple = _ntuple(1)to_2tuple = _ntuple(2)
def set_grad_checkpoint(model, use_fp32_attention=False, gc_step=1): assert isinstance(model, nn.Module)
def set_attr(module): module.grad_checkpointing = True module.fp32_attention = use_fp32_attention module.grad_checkpointing_step = gc_step model.apply(set_attr)
def auto_grad_checkpoint(module, *args, **kwargs): if getattr(module, 'grad_checkpointing', False): if not isinstance(module, Iterable): return checkpoint(module, *args, use_reentrant=False, **kwargs) gc_step = module[0].grad_checkpointing_step return checkpoint_sequential(module, gc_step, *args, **kwargs) return module(*args, **kwargs)
def checkpoint_sequential(functions, step, input, *args, **kwargs):
# Hack for keyword-only parameter in a python 2.7-compliant way preserve = kwargs.pop('preserve_rng_state', True) if kwargs: raise ValueError("Unexpected keyword arguments: " + ",".join(kwargs))
def run_function(start, end, functions): def forward(input): for j in range(start, end + 1): input = functions[j](input, *args) return input return forward
if isinstance(functions, torch.nn.Sequential): functions = list(functions.children())
# the last chunk has to be non-volatile end = -1 segment = len(functions) // step for start in range(0, step * (segment - 1), step): end = start + step - 1 input = checkpoint(run_function(start, end, functions), input, preserve_rng_state=preserve) return run_function(end + 1, len(functions) - 1, functions)(input)
def window_partition(x, window_size): """ Partition into non-overlapping windows with padding if needed. Args: x (tensor): input tokens with [B, H, W, C]. window_size (int): window size.
Returns: windows: windows after partition with [B * num_windows, window_size, window_size, C]. (Hp, Wp): padded height and width before partition """ B, H, W, C = x.shape
pad_h = (window_size - H % window_size) % window_size pad_w = (window_size - W % window_size) % window_size if pad_h > 0 or pad_w > 0: x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) Hp, Wp = H + pad_h, W + pad_w
x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows, (Hp, Wp)
def window_unpartition(windows, window_size, pad_hw, hw): """ Window unpartition into original sequences and removing padding. Args: x (tensor): input tokens with [B * num_windows, window_size, window_size, C]. window_size (int): window size. pad_hw (Tuple): padded height and width (Hp, Wp). hw (Tuple): original height and width (H, W) before padding.
Returns: x: unpartitioned sequences with [B, H, W, C]. """ Hp, Wp = pad_hw H, W = hw B = windows.shape[0] // (Hp * Wp // window_size // window_size) x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
if Hp > H or Wp > W: x = x[:, :H, :W, :].contiguous() return x
def get_rel_pos(q_size, k_size, rel_pos): """ Get relative positional embeddings according to the relative positions of query and key sizes. Args: q_size (int): size of query q. k_size (int): size of key k. rel_pos (Tensor): relative position embeddings (L, C).
Returns: Extracted positional embeddings according to relative positions. """ max_rel_dist = int(2 * max(q_size, k_size) - 1) # Interpolate rel pos if needed. if rel_pos.shape[0] != max_rel_dist: # Interpolate rel pos. rel_pos_resized = F.interpolate( rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), size=max_rel_dist, mode="linear", ) rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) else: rel_pos_resized = rel_pos
# Scale the coords with short length if shapes for q and k are different. q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
return rel_pos_resized[relative_coords.long()]
def add_decomposed_rel_pos(attn, q, rel_pos_h, rel_pos_w, q_size, k_size): """ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 Args: attn (Tensor): attention map. q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis. rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. q_size (Tuple): spatial sequence size of query q with (q_h, q_w). k_size (Tuple): spatial sequence size of key k with (k_h, k_w).
Returns: attn (Tensor): attention map with added relative positional embeddings. """ q_h, q_w = q_size k_h, k_w = k_size Rh = get_rel_pos(q_h, k_h, rel_pos_h) Rw = get_rel_pos(q_w, k_w, rel_pos_w)
B, _, dim = q.shape r_q = q.reshape(B, q_h, q_w, dim) rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)
attn = ( attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :] ).view(B, q_h * q_w, k_h * k_w)
return attn
def mean_flat(tensor): return tensor.mean(dim=list(range(1, tensor.ndim)))
################################################################################## Token Masking and Unmasking ##################################################################################def get_mask(batch, length, mask_ratio, device, mask_type=None, data_info=None, extra_len=0): """ Get the binary mask for the input sequence. Args: - batch: batch size - length: sequence length - mask_ratio: ratio of tokens to mask - data_info: dictionary with info for reconstruction return: mask_dict with following keys: - mask: binary mask, 0 is keep, 1 is remove - ids_keep: indices of tokens to keep - ids_restore: indices to restore the original order """ assert mask_type in ['random', 'fft', 'laplacian', 'group'] mask = torch.ones([batch, length], device=device) len_keep = int(length * (1 - mask_ratio)) - extra_len
if mask_type in ['random', 'group']: noise = torch.rand(batch, length, device=device) # noise in [0, 1] ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove ids_restore = torch.argsort(ids_shuffle, dim=1) # keep the first subset ids_keep = ids_shuffle[:, :len_keep] ids_removed = ids_shuffle[:, len_keep:]
elif mask_type in ['fft', 'laplacian']: if 'strength' in data_info: strength = data_info['strength']
else: N = data_info['N'][0] img = data_info['ori_img'] # 获取原图的尺寸信息 _, C, H, W = img.shape if mask_type == 'fft': # 对图片进行reshape,将其变为patch (3, H/N, N, W/N, N) reshaped_image = img.reshape((batch, -1, H // N, N, W // N, N)) fft_image = torch.fft.fftn(reshaped_image, dim=(3, 5)) # 取绝对值并求和获取频率强度 strength = torch.sum(torch.abs(fft_image), dim=(1, 3, 5)).reshape((batch, -1,)) elif type == 'laplacian': laplacian_kernel = torch.tensor([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], dtype=torch.float32).reshape(1, 1, 3, 3) laplacian_kernel = laplacian_kernel.repeat(C, 1, 1, 1) # 对图片进行reshape,将其变为patch (3, H/N, N, W/N, N) reshaped_image = img.reshape(-1, C, H // N, N, W // N, N).permute(0, 2, 4, 1, 3, 5).reshape(-1, C, N, N) laplacian_response = F.conv2d(reshaped_image, laplacian_kernel, padding=1, groups=C) strength = laplacian_response.sum(dim=[1, 2, 3]).reshape((batch, -1,))
# 对频率强度进行归一化,然后使用torch.multinomial进行采样 probabilities = strength / (strength.max(dim=1)[0][:, None]+1e-5) ids_shuffle = torch.multinomial(probabilities.clip(1e-5, 1), length, replacement=False) ids_keep = ids_shuffle[:, :len_keep] ids_restore = torch.argsort(ids_shuffle, dim=1) ids_removed = ids_shuffle[:, len_keep:]
mask[:, :len_keep] = 0 mask = torch.gather(mask, dim=1, index=ids_restore)
return {'mask': mask, 'ids_keep': ids_keep, 'ids_restore': ids_restore, 'ids_removed': ids_removed}
def mask_out_token(x, ids_keep, ids_removed=None): """ Mask out the tokens specified by ids_keep. Args: - x: input sequence, [N, L, D] - ids_keep: indices of tokens to keep return: - x_masked: masked sequence """ N, L, D = x.shape # batch, length, dim x_remain = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D)) if ids_removed is not None: x_masked = torch.gather(x, dim=1, index=ids_removed.unsqueeze(-1).repeat(1, 1, D)) return x_remain, x_masked else: return x_remain
def mask_tokens(x, mask_ratio): """ Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random noise. x: [N, L, D], sequence """ N, L, D = x.shape # batch, length, dim len_keep = int(L * (1 - mask_ratio))
noise = torch.rand(N, L, device=x.device) # noise in [0, 1]
# sort noise for each sample ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove ids_restore = torch.argsort(ids_shuffle, dim=1)
# keep the first subset ids_keep = ids_shuffle[:, :len_keep] x_masked = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D))
# generate the binary mask: 0 is keep, 1 is remove mask = torch.ones([N, L], device=x.device) mask[:, :len_keep] = 0 mask = torch.gather(mask, dim=1, index=ids_restore)
return x_masked, mask, ids_restore
def unmask_tokens(x, ids_restore, mask_token): # x: [N, T, D] if extras == 0 (i.e., no cls token) else x: [N, T+1, D] mask_tokens = mask_token.repeat(x.shape[0], ids_restore.shape[1] - x.shape[1], 1) x = torch.cat([x, mask_tokens], dim=1) x = torch.gather(x, dim=1, index=ids_restore.unsqueeze(-1).repeat(1, 1, x.shape[2])) # unshuffle return x
# Parse 'None' to None and others to float valuedef parse_float_none(s): assert isinstance(s, str) return None if s == 'None' else float(s)
#----------------------------------------------------------------------------# Parse a comma separated list of numbers or ranges and return a list of ints.# Example: '1,2,5-10' returns [1, 2, 5, 6, 7, 8, 9, 10]
def parse_int_list(s): if isinstance(s, list): return s ranges = [] range_re = re.compile(r'^(\d+)-(\d+)$') for p in s.split(','): if m := range_re.match(p): ranges.extend(range(int(m.group(1)), int(m.group(2))+1)) else: ranges.append(int(p)) return ranges
def init_processes(fn, args): """ Initialize the distributed environment. """ os.environ['MASTER_ADDR'] = args.master_address os.environ['MASTER_PORT'] = str(random.randint(2000, 6000)) print(f'MASTER_ADDR = {os.environ["MASTER_ADDR"]}') print(f'MASTER_PORT = {os.environ["MASTER_PORT"]}') torch.cuda.set_device(args.local_rank) dist.init_process_group(backend='nccl', init_method='env://', rank=args.global_rank, world_size=args.global_size) fn(args) if args.global_size > 1: cleanup()
def mprint(*args, **kwargs): """ Print only from rank 0. """ if dist.get_rank() == 0: print(*args, **kwargs)
def cleanup(): """ End DDP training. """ dist.barrier() mprint("Done!") dist.barrier() dist.destroy_process_group()
#----------------------------------------------------------------------------# logging info.class Logger(object): """ Redirect stderr to stdout, optionally print stdout to a file, and optionally force flushing on both stdout and the file. """
def __init__(self, file_name=None, file_mode="w", should_flush=True): self.file = None
if file_name is not None: self.file = open(file_name, file_mode)
self.should_flush = should_flush self.stdout = sys.stdout self.stderr = sys.stderr
sys.stdout = self sys.stderr = self
def __enter__(self): return self
def __exit__(self, exc_type, exc_value, traceback): self.close()
def write(self, text): """Write text to stdout (and a file) and optionally flush.""" if len(text) == 0: # workaround for a bug in VSCode debugger: sys.stdout.write(''); sys.stdout.flush() => crash return
if self.file is not None: self.file.write(text)
self.stdout.write(text)
if self.should_flush: self.flush()
def flush(self): """Flush written text to both stdout and a file, if open.""" if self.file is not None: self.file.flush()
self.stdout.flush()
def close(self): """Flush, close possible files, and remove stdout/stderr mirroring.""" self.flush()
# if using multiple loggers, prevent closing in wrong order if sys.stdout is self: sys.stdout = self.stdout if sys.stderr is self: sys.stderr = self.stderr
if self.file is not None: self.file.close()
class StackedRandomGenerator: def __init__(self, device, seeds): super().__init__() self.generators = [torch.Generator(device).manual_seed(int(seed) % (1 << 32)) for seed in seeds]
def randn(self, size, **kwargs): assert size[0] == len(self.generators) return torch.stack([torch.randn(size[1:], generator=gen, **kwargs) for gen in self.generators])
def randn_like(self, input): return self.randn(input.shape, dtype=input.dtype, layout=input.layout, device=input.device)
def randint(self, *args, size, **kwargs): assert size[0] == len(self.generators) return torch.stack([torch.randint(*args, size=size[1:], generator=gen, **kwargs) for gen in self.generators])
def prepare_prompt_ar(prompt, ratios, device='cpu', show=True): # get aspect_ratio or ar aspect_ratios = re.findall(r"--aspect_ratio\s+(\d+:\d+)", prompt) ars = re.findall(r"--ar\s+(\d+:\d+)", prompt) custom_hw = re.findall(r"--hw\s+(\d+:\d+)", prompt) if show: print("aspect_ratios:", aspect_ratios, "ars:", ars, "hws:", custom_hw) prompt_clean = prompt.split("--aspect_ratio")[0].split("--ar")[0].split("--hw")[0] if len(aspect_ratios) + len(ars) + len(custom_hw) == 0 and show: print( "Wrong prompt format. Set to default ar: 1. change your prompt into format '--ar h:w or --hw h:w' for correct generating") if len(aspect_ratios) != 0: ar = float(aspect_ratios[0].split(':')[0]) / float(aspect_ratios[0].split(':')[1]) elif len(ars) != 0: ar = float(ars[0].split(':')[0]) / float(ars[0].split(':')[1]) else: ar = 1. closest_ratio = min(ratios.keys(), key=lambda ratio: abs(float(ratio) - ar)) if len(custom_hw) != 0: custom_hw = [float(custom_hw[0].split(':')[0]), float(custom_hw[0].split(':')[1])] else: custom_hw = ratios[closest_ratio] default_hw = ratios[closest_ratio] prompt_show = f'prompt: {prompt_clean.strip()}\nSize: --ar {closest_ratio}, --bin hw {ratios[closest_ratio]}, --custom hw {custom_hw}' return prompt_clean, prompt_show, torch.tensor(default_hw, device=device)[None], torch.tensor([float(closest_ratio)], device=device)[None], torch.tensor(custom_hw, device=device)[None]
def resize_and_crop_tensor(samples: torch.Tensor, new_width: int, new_height: int): orig_hw = torch.tensor([samples.shape[2], samples.shape[3]], dtype=torch.int) custom_hw = torch.tensor([int(new_height), int(new_width)], dtype=torch.int)
if (orig_hw != custom_hw).all(): ratio = max(custom_hw[0] / orig_hw[0], custom_hw[1] / orig_hw[1]) resized_width = int(orig_hw[1] * ratio) resized_height = int(orig_hw[0] * ratio)
transform = T.Compose([ T.Resize((resized_height, resized_width)), T.CenterCrop(custom_hw.tolist()) ]) return transform(samples) else: return samples
def resize_and_crop_img(img: Image, new_width, new_height): orig_width, orig_height = img.size
ratio = max(new_width/orig_width, new_height/orig_height) resized_width = int(orig_width * ratio) resized_height = int(orig_height * ratio)
img = img.resize((resized_width, resized_height), Image.LANCZOS)
left = (resized_width - new_width)/2 top = (resized_height - new_height)/2 right = (resized_width + new_width)/2 bottom = (resized_height + new_height)/2
img = img.crop((left, top, right, bottom))
return img
def mask_feature(emb, mask): if emb.shape[0] == 1: keep_index = mask.sum().item() return emb[:, :, :keep_index, :], keep_index else: masked_feature = emb * mask[:, None, :, None] return masked_feature, emb.shape[2]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Linear noise-to-data flow matching; no VP schedule or variance objective."""import torch
def flow_matching_loss(model, clean, noise, time, condition, mask): if clean.shape != noise.shape or time.shape != (clean.shape[0],): raise ValueError('Noise and continuous time must match the data batch') fraction = time.float()[:, None, None, None] noisy = (1 - fraction) * noise.float() + fraction * clean.float() target = clean.float() - noise.float() # Preserve the pretrained embedding's scale/direction, not its VP schedule. prediction = model(noisy, 999 * (1 - time.float()), condition, mask=mask) if prediction.shape != clean.shape: raise ValueError('RFM must predict exactly four latent channels') return (prediction.float() - target).square().flatten(1).mean(1)
@torch.no_grad()def sample_rfm(model, noise, condition, mask, empty, empty_mask, cfg_scale=4., method='dopri5', steps=50, atol=1e-6, rtol=1e-3): """Integrate dx/dt=u from noise at t=0 to data at t=1 in FP32.""" evaluations = 0 condition = torch.cat([empty.expand_as(condition), condition]) mask = torch.cat([empty_mask.expand_as(mask), mask])
def velocity(time, latent): nonlocal evaluations evaluations += 1 if evaluations > 10000: raise RuntimeError('ODE exceeded 10000 evaluations; inspect model stability') inputs = torch.cat([latent, latent]) # As in SiT's ODE wrapper, retain continuous RK evaluation times. timestep = (999 * (1 - time)).expand(len(inputs)).float() with torch.autocast('cuda', dtype=torch.bfloat16, enabled=latent.is_cuda): output = model(inputs, timestep, condition, mask=mask).float() if output.shape != inputs.shape: raise ValueError('RFM sampler received a non-flow output head') unconditional, conditional = output.chunk(2) result = unconditional + cfg_scale * (conditional - unconditional) if not torch.isfinite(result).all(): raise FloatingPointError('Nonfinite flow velocity') return result
latent = noise.float().clone() grid = torch.linspace(0, 1, steps + 1, device=noise.device) if method == 'heun': for start, end in zip(grid[:-1], grid[1:]): delta = end - start first = velocity(start, latent) second = velocity(end, latent + delta * first) latent = latent + delta * (first + second) / 2 elif method == 'dopri5': from torchdiffeq import odeint latent = odeint(velocity, latent, grid[[0, -1]], method='dopri5', atol=atol, rtol=rtol)[-1] else: raise ValueError('Supported RFM solvers: dopri5, heun') if not torch.isfinite(latent).all(): raise FloatingPointError('Nonfinite integrated latent') return latent, dict(method=method, nfe=evaluations, cfg_scale=cfg_scale, atol=atol, rtol=rtol, steps=steps if method == 'heun' else None, direction='noise_to_data', time_embedding='999*(1-t)')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303"""This file contains primitives for multi-gpu communication.This is useful when doing distributed training."""import osimport pickleimport shutil
import gcimport mmcvimport torchimport torch.distributed as distfrom mmcv.runner import get_dist_info
def is_distributed(): return get_world_size() > 1
def get_world_size(): if not dist.is_available(): return 1 return dist.get_world_size() if dist.is_initialized() else 1
def get_rank(): if not dist.is_available(): return 0 return dist.get_rank() if dist.is_initialized() else 0
def get_local_rank(): if not dist.is_available(): return 0 return int(os.getenv('LOCAL_RANK', 0)) if dist.is_initialized() else 0
def is_master(): return get_rank() == 0
def is_local_master(): return get_local_rank() == 0
def get_local_proc_group(group_size=8): world_size = get_world_size() if world_size <= group_size or group_size == 1: return None assert world_size % group_size == 0, f'world size ({world_size}) should be evenly divided by group size ({group_size}).' process_groups = getattr(get_local_proc_group, 'process_groups', {}) if group_size not in process_groups: num_groups = dist.get_world_size() // group_size groups = [list(range(i * group_size, (i + 1) * group_size)) for i in range(num_groups)] process_groups.update({group_size: [torch.distributed.new_group(group) for group in groups]}) get_local_proc_group.process_groups = process_groups
group_idx = get_rank() // group_size return get_local_proc_group.process_groups.get(group_size)[group_idx]
def synchronize(): """ Helper function to synchronize (barrier) among all processes when using distributed training """ if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return dist.barrier()
def all_gather(data): """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ to_device = torch.device("cuda") # to_device = torch.device("cpu")
world_size = get_world_size() if world_size == 1: return [data]
# serialized to a Tensor buffer = pickle.dumps(data) storage = torch.ByteStorage.from_buffer(buffer) tensor = torch.ByteTensor(storage).to(to_device)
# obtain Tensor size of each rank local_size = torch.LongTensor([tensor.numel()]).to(to_device) size_list = [torch.LongTensor([0]).to(to_device) for _ in range(world_size)] dist.all_gather(size_list, local_size) size_list = [int(size.item()) for size in size_list] max_size = max(size_list)
tensor_list = [ torch.ByteTensor(size=(max_size,)).to(to_device) for _ in size_list ] if local_size != max_size: padding = torch.ByteTensor(size=(max_size - local_size,)).to(to_device) tensor = torch.cat((tensor, padding), dim=0) dist.all_gather(tensor_list, tensor)
data_list = [] for size, tensor in zip(size_list, tensor_list): buffer = tensor.cpu().numpy().tobytes()[:size] data_list.append(pickle.loads(buffer))
return data_list
def reduce_dict(input_dict, average=True): """ Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fields as input_dict, after reduction. """ world_size = get_world_size() if world_size < 2: return input_dict with torch.no_grad(): reduced_dict = _extracted_from_reduce_dict_14(input_dict, average, world_size) return reduced_dict
# TODO Rename this here and in `reduce_dict`def _extracted_from_reduce_dict_14(input_dict, average, world_size): names = [] values = [] # sort the keys so that they are consistent across processes for k in sorted(input_dict.keys()): names.append(k) values.append(input_dict[k]) values = torch.stack(values, dim=0) dist.reduce(values, dst=0) if dist.get_rank() == 0 and average: # only main process gets accumulated, so only divide by # world_size in this case values /= world_size return dict(zip(names, values))
def broadcast(data, **kwargs): if get_world_size() == 1: return data data = [data] dist.broadcast_object_list(data, **kwargs) return data[0]
def all_gather_cpu(result_part, tmpdir=None, collect_by_master=True): rank, world_size = get_dist_info() if tmpdir is None: tmpdir = './tmp' if rank == 0: mmcv.mkdir_or_exist(tmpdir) synchronize() # dump the part result to the dir mmcv.dump(result_part, os.path.join(tmpdir, f'part_{rank}.pkl')) synchronize() if collect_by_master and rank != 0: return None # load results of all parts from tmp dir results = [] for i in range(world_size): part_file = os.path.join(tmpdir, f'part_{i}.pkl') results.append(mmcv.load(part_file)) if not collect_by_master: synchronize() # remove tmp dir if rank == 0: shutil.rmtree(tmpdir) return results
def all_gather_tensor(tensor, group_size=None, group=None): if group_size is None: group_size = get_world_size() if group_size == 1: output = [tensor] else: output = [torch.zeros_like(tensor) for _ in range(group_size)] dist.all_gather(output, tensor, group=group) return output
def gather_difflen_tensor(feat, num_samples_list, concat=True, group=None, group_size=None): world_size = get_world_size() if world_size == 1: return feat if concat else [feat] num_samples, *feat_dim = feat.size() # padding to max number of samples feat_padding = feat.new_zeros((max(num_samples_list), *feat_dim)) feat_padding[:num_samples] = feat # gather feat_gather = all_gather_tensor(feat_padding, group=group, group_size=group_size) for r, num in enumerate(num_samples_list): feat_gather[r] = feat_gather[r][:num] if concat: feat_gather = torch.cat(feat_gather) return feat_gather
class GatherLayer(torch.autograd.Function): '''Gather tensors from all process, supporting backward propagation. '''
@staticmethod def forward(ctx, input): ctx.save_for_backward(input) num_samples = torch.tensor(input.size(0), dtype=torch.long, device=input.device) ctx.num_samples_list = all_gather_tensor(num_samples) output = gather_difflen_tensor(input, ctx.num_samples_list, concat=False) return tuple(output)
@staticmethod def backward(ctx, *grads): # tuple(output)'s grad input, = ctx.saved_tensors num_samples_list = ctx.num_samples_list rank = get_rank() start, end = sum(num_samples_list[:rank]), sum(num_samples_list[:rank + 1]) grads = torch.cat(grads) if is_distributed(): dist.all_reduce(grads) grad_out = torch.zeros_like(input) grad_out[:] = grads[start:end] return grad_out, None, None
class GatherLayerWithGroup(torch.autograd.Function): '''Gather tensors from all process, supporting backward propagation. '''
@staticmethod def forward(ctx, input, group, group_size): ctx.save_for_backward(input) ctx.group_size = group_size output = all_gather_tensor(input, group=group, group_size=group_size) return tuple(output)
@staticmethod def backward(ctx, *grads): # tuple(output)'s grad input, = ctx.saved_tensors grads = torch.stack(grads) if is_distributed(): dist.all_reduce(grads) grad_out = torch.zeros_like(input) grad_out[:] = grads[get_rank() % ctx.group_size] return grad_out, None, None
def gather_layer_with_group(data, group=None, group_size=None): if group_size is None: group_size = get_world_size() return GatherLayer.apply(data, group, group_size)
from typing import Unionimport math# from torch.distributed.fsdp.fully_sharded_data_parallel import TrainingState_, _calc_grad_norm
@torch.no_grad()def clip_grad_norm_( self, max_norm: Union[float, int], norm_type: Union[float, int] = 2.0) -> None: self._lazy_init() self._wait_for_previous_optim_step() assert self._is_root, "clip_grad_norm should only be called on the root (parent) instance" self._assert_state(TrainingState_.IDLE)
max_norm = float(max_norm) norm_type = float(norm_type) # Computes the max norm for this shard's gradients and sync's across workers local_norm = _calc_grad_norm(self.params_with_grad, norm_type).cuda() # type: ignore[arg-type] if norm_type == math.inf: total_norm = local_norm dist.all_reduce(total_norm, op=torch.distributed.ReduceOp.MAX, group=self.process_group) else: total_norm = local_norm ** norm_type dist.all_reduce(total_norm, group=self.process_group) total_norm = total_norm ** (1.0 / norm_type)
clip_coef = torch.tensor(max_norm, dtype=total_norm.dtype, device=total_norm.device) / (total_norm + 1e-6) if clip_coef < 1: # multiply by clip_coef, aka, (max_norm/total_norm). for p in self.params_with_grad: assert p.grad is not None p.grad.detach().mul_(clip_coef.to(p.grad.device)) return total_norm
def flush(): gc.collect() torch.cuda.empty_cache()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import loggingimport osimport torch.distributed as distfrom datetime import datetimefrom .dist_utils import is_local_masterfrom mmcv.utils.logging import logger_initialized
def get_root_logger(log_file=None, log_level=logging.INFO, name='PixArt'): """Get root logger.
Args: log_file (str, optional): File path of log. Defaults to None. log_level (int, optional): The level of logger. Defaults to logging.INFO. name (str): logger name Returns: :obj:`logging.Logger`: The obtained logger """ if log_file is None: log_file = '/dev/null' return get_logger(name=name, log_file=log_file, log_level=log_level)
def get_logger(name, log_file=None, log_level=logging.INFO): """Initialize and get a logger by name.
If the logger has not been initialized, this method will initialize the logger by adding one or two handlers, otherwise the initialized logger will be directly returned. During initialization, a StreamHandler will always be added. If `log_file` is specified and the process rank is 0, a FileHandler will also be added.
Args: name (str): Logger name. log_file (str | None): The log filename. If specified, a FileHandler will be added to the logger. log_level (int): The logger level. Note that only the process of rank 0 is affected, and other processes will set the level to "Error" thus be silent most of the time.
Returns: logging.Logger: The expected logger. """ logger = logging.getLogger(name) logger.propagate = False # disable root logger to avoid duplicate logging
if name in logger_initialized: return logger # handle hierarchical names # e.g., logger "a" is initialized, then logger "a.b" will skip the # initialization since it is a child of "a". for logger_name in logger_initialized: if name.startswith(logger_name): return logger
stream_handler = logging.StreamHandler() handlers = [stream_handler]
rank = dist.get_rank() if dist.is_available() and dist.is_initialized() else 0 # only rank 0 will add a FileHandler if rank == 0 and log_file is not None: file_handler = logging.FileHandler(log_file, 'w') handlers.append(file_handler)
formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') for handler in handlers: handler.setFormatter(formatter) handler.setLevel(log_level) logger.addHandler(handler)
# only rank0 for each node will print logs log_level = log_level if is_local_master() else logging.ERROR logger.setLevel(log_level)
logger_initialized[name] = True
return logger
def rename_file_with_creation_time(file_path): # 获取文件的创建时间 creation_time = os.path.getctime(file_path) creation_time_str = datetime.fromtimestamp(creation_time).strftime('%Y-%m-%d_%H-%M-%S')
# 构建新的文件名 dir_name, file_name = os.path.split(file_path) name, ext = os.path.splitext(file_name) new_file_name = f"{name}_{creation_time_str}{ext}" new_file_path = os.path.join(dir_name, new_file_name)
# 重命名文件 os.rename(file_path, new_file_path) print(f"File renamed to: {new_file_path}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""RFM checkpoint serialization, random state, EMA and text dropout."""import randomfrom pathlib import Path
import numpy as npimport torch
def rng_state(): return dict(python=random.getstate(), numpy=np.random.get_state(), torch=torch.get_rng_state(), cuda=torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None)
def restore_rng(state): random.setstate(state['python']) np.random.set_state(state['numpy']) torch.set_rng_state(state['torch']) if state['cuda'] is not None: torch.cuda.set_rng_state_all(state['cuda'])
@torch.no_grad()def update_ema(ema, model, decay): for destination, source in zip(ema.parameters(), model.parameters()): destination.mul_(decay).add_(source.detach().float(), alpha=1 - decay) for destination, source in zip(ema.buffers(), model.buffers()): destination.copy_(source)
def drop_to_empty_text(caption, mask, empty, empty_mask, probability): dropped = torch.rand(caption.shape[0], device=caption.device) < probability return (torch.where(dropped[:, None, None, None], empty, caption), torch.where(dropped[:, None], empty_mask, mask))
def save_training_checkpoint(path, model, ema, optimizer, scheduler, metadata, progress, rank_rng): if progress['micro_step'] % progress['accumulation_steps']: raise ValueError('Checkpoint must be saved at a complete optimizer update boundary') metadata = dict(metadata, optimizer_step=progress['optimizer_step'], samples_seen=progress['samples_seen']) path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix('.tmp') torch.save(dict(state_dict=model.state_dict(), state_dict_ema=ema.state_dict(), optimizer=optimizer.state_dict(), scheduler=scheduler.state_dict(), metadata=metadata, progress=progress, rank_rng=rank_rng), temporary) temporary.replace(path)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Strict Diffusers Theta RAW -> native PixArt parameter mapping."""import hashlibimport importlib.metadataimport subprocess
import numpy as npimport torch
def import_theta_state(model, source, empty_embedding): source = dict(source) state = {} names = { 'x_embedder.proj': 'pos_embed.proj', 'y_embedder.y_proj.fc1': 'caption_projection.linear_1', 'y_embedder.y_proj.fc2': 'caption_projection.linear_2', 't_embedder.mlp.0': 'adaln_single.emb.timestep_embedder.linear_1', 't_embedder.mlp.2': 'adaln_single.emb.timestep_embedder.linear_2', 't_block.1': 'adaln_single.linear', 'final_layer.linear': 'proj_out', } for target, original in names.items(): for suffix in ('weight', 'bias'): state[f'{target}.{suffix}'] = source.pop(f'{original}.{suffix}') state['final_layer.scale_shift_table'] = source.pop('scale_shift_table') for index in range(len(model.blocks)): target = f'blocks.{index}' original = f'transformer_blocks.{index}' state[f'{target}.scale_shift_table'] = source.pop(f'{original}.scale_shift_table') for suffix in ('weight', 'bias'): state[f'{target}.attn.qkv.{suffix}'] = torch.cat([ source.pop(f'{original}.attn1.to_{letter}.{suffix}') for letter in ('q', 'k', 'v')]) state[f'{target}.cross_attn.kv_linear.{suffix}'] = torch.cat([ source.pop(f'{original}.attn2.to_{letter}.{suffix}') for letter in ('k', 'v')]) layers = {'attn.proj': 'attn1.to_out.0', 'cross_attn.q_linear': 'attn2.to_q', 'cross_attn.proj': 'attn2.to_out.0', 'mlp.fc1': 'ff.net.0.proj', 'mlp.fc2': 'ff.net.2'} for new_name, old_name in layers.items(): for suffix in ('weight', 'bias'): state[f'{target}.{new_name}.{suffix}'] = source.pop(f'{original}.{old_name}.{suffix}') for new_name, old_name in [('attn', 'attn1'), ('cross_attn', 'attn2')]: for letter in ('q', 'k'): state[f'{target}.{new_name}.{letter}_norm.weight'] = source.pop( f'{original}.{old_name}.norm_{letter}.weight') if source: raise ValueError(f'Unmapped source tensors: {sorted(source)}') state['pos_embed'] = model.pos_embed.detach().clone() state['y_embedder.y_embedding'] = empty_embedding.float().reshape_as(model.y_embedder.y_embedding) model.load_state_dict(state, strict=True)
def make_initial_metadata(config, scaling_factor, model, manifest_hashes=None): if config['prediction_type'] != 'epsilon': raise ValueError('Initialization requires the original epsilon checkpoint') # Preserve the source checkpoint metadata without importing a VP sampler. betas = np.linspace(0.0001, 0.02, 1000, dtype=np.float64) revision = subprocess.run(['git', 'rev-parse', 'HEAD'], capture_output=True, text=True) versions = {} for package in ('torch', 'numpy', 'accelerate', 'diffusers', 'transformers', 'mmcv', 'timm', 'xformers'): try: versions[package] = importlib.metadata.version(package) except importlib.metadata.PackageNotFoundError: versions[package] = None return dict( format_version=1, prediction_type=config['prediction_type'], validation_prediction_path='epsilon_to_x0', schedule=dict(name='linear', steps=1000, beta_sha256=hashlib.sha256(betas.tobytes()).hexdigest()), vae_scaling_factor=float(scaling_factor), latent_cache_scaled=False, architecture={key: list(value.shape) for key, value in model.state_dict().items()}, source_model=config['source_model'], source_prediction_type=config.get('source_prediction_type', 'epsilon'), source_weights=config.get('source_weights', 'raw'), source_optimizer_step=config.get('source_optimizer_step'), source_checkpoint_sha256=config.get('source_checkpoint_sha256'), source_checkpoint=config.get('init_checkpoint'), training_config=dict(config), versions=versions, manifest_hashes=manifest_hashes, git_commit=revision.stdout.strip() if revision.returncode == 0 else None, )12345678910111213141516171819202122[ { "case_id": "example-0", "prompt": "A red panda sitting on a moss-covered branch in a lush forest, soft morning light, detailed wildlife photograph.", "seed": 42 }, { "case_id": "example-1", "prompt": "A cozy living room with a green velvet sofa, wooden furniture, large windows and warm afternoon sunlight, interior photography.", "seed": 43 }, { "case_id": "example-2", "prompt": "A mountain lake reflecting snow-covered peaks at sunrise, pine trees along the shore, realistic landscape photograph.", "seed": 44 }, { "case_id": "example-3", "prompt": "A watercolor illustration of a small seaside village with colorful houses and fishing boats, soft pastel colors.", "seed": 45 }]123456789101112131415161718[ { "prompt": "A red panda sitting on a moss-covered branch in a lush forest, soft morning light, detailed wildlife photograph.", "seed": 42 }, { "prompt": "A cozy living room with a green velvet sofa, wooden furniture, large windows and warm afternoon sunlight, interior photography.", "seed": 43 }, { "prompt": "A mountain lake reflecting snow-covered peaks at sunrise, pine trees along the shore, realistic landscape photograph.", "seed": 44 }, { "prompt": "A watercolor illustration of a small seaside village with colorful houses and fishing boats, soft pastel colors.", "seed": 45 }]123version https://git-lfs.github.com/spec/v1oid sha256:9003b14392fb8d8141fcfc0da2cef94737f0edb93604b975ce701fb46bc156casize 263885123456[ "A red panda sitting on a moss-covered branch in a lush forest, soft morning light, detailed wildlife photograph.", "A cozy living room with a green velvet sofa, wooden furniture, large windows and warm afternoon sunlight, interior photography.", "A mountain lake reflecting snow-covered peaks at sunrise, pine trees along the shore, realistic landscape photograph.", "A watercolor illustration of a small seaside village with colorful houses and fishing boats, soft pastel colors."]123version https://git-lfs.github.com/spec/v1oid sha256:63b3e0e974244e75d7152f37b8e249e1004134b21c603a2605b6840c87cd9266size 263885123456789101112131415161718192021222324{ "raw": { "method": "dopri5", "nfe": 182, "cfg_scale": 4.0, "atol": 1e-06, "rtol": 0.001, "steps": null, "direction": "noise_to_data", "time_embedding": "999*(1-t)", "latent_rms": 1.0735021829605103 }, "ema": { "method": "dopri5", "nfe": 176, "cfg_scale": 4.0, "atol": 1e-06, "rtol": 0.001, "steps": null, "direction": "noise_to_data", "time_embedding": "999*(1-t)", "latent_rms": 1.083146333694458 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869{ "model": "PixArt_XL_2", "image_size": 512, "prediction_type": "flow_velocity", "path": "linear", "time_sampling": "uniform_continuous", "time_embedding": "999*(1-t)", "loss": "unweighted_mse", "out_channels": 4, "head_initialization": "zero", "qk_norm": "rms_norm", "grad_checkpointing": false, "mixed_precision": "bf16", "source_model": "../pixelart-alpha-e-qknorm/outputs/A_flux1_dev_mix50/checkpoint-010000", "source_weights": "raw", "source_checkpoint_sha256": "fecb75bebf36bcadc3e1ce97ffecf2739482d3f0fe5e61ee33b91ccf30a2de02", "init_checkpoint": "output/theta_raw_to_v_setup/initial_raw_epsilon.pth", "conditioning_cache": "../output/theta_raw_to_v_setup/conditioning.pt", "vae_path": "/home/yyh/.cache/huggingface/hub/models--PixArt-alpha--PixArt-XL-2-512x512/snapshots/50f702106901db6d0f8b67eb88e814c56ded2692/vae", "source_datasets": [ "data/synth_images/flux1_dev_localized_narratives_synth512", "data/synth_images/flux1_dev_synth512" ], "source_counts": [ 50000, 76708 ], "source_weights_per_batch": [ 0.5, 0.5 ], "data_roots": [ "output/datasets_512/FluxLocalizedNarratives", "output/datasets_512/FluxSynth" ], "world_size": 4, "batch_size": 8, "accumulation_steps": 1, "dataloader_workers": 4, "prefetch_factor": 2, "learning_rate": 1e-05, "betas": [ 0.9, 0.999 ], "adam_eps": 1e-08, "weight_decay": 0.0, "warmup_updates": 500, "max_grad_norm": 1.0, "ema_decay": 0.9999, "class_dropout_prob": 0.1, "max_train_steps": 100000, "save_every_updates": 5000, "validate_every_updates": 500, "log_every_updates": 10, "seed": 43, "sampling_method": "dopri5", "sampling_steps": 50, "sampling_atol": 1e-06, "sampling_rtol": 0.001, "cfg_scale": 4.0, "validation_seeds": [ 42, 43, 44, 45 ], "work_dir": "output/run-validation-100000"}12345678910111213141516171819202122# Versions observed in the source runtime during extraction (2026-10-15).# Install the matching Torch/CUDA wheels first; see README.md.torch==2.9.1torchvision==0.24.1mmcv==1.7.0timm==1.0.22xformers==0.0.33.post2diffusers==0.37.0transformers==5.3.0accelerate==1.13.0numpy==2.3.5Pillow==12.0.0scipy==1.17.1einops==0.8.2safetensors==0.7.0sentencepiece==0.2.2ftfy==6.3.1beautifulsoup4==4.14.3protobuf==7.34.0yapf==0.40.1torchdiffeq==0.2.5pytest==8.4.21234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374#!/usr/bin/env bashset -euo pipefail
if [[ $# -eq 0 || ${1:-} == -h || ${1:-} == --help ]]; then cat <<'HELP'Usage: bash run.sh <train|validate|inference> <config.py> [arguments...]
train Start torchrun using config['world_size']; accepts --resume, --work-dir, etc. validate Generate RAW/EMA validation images; requires --checkpoint and --output. inference Generate images for custom prompts; requires --checkpoint, --prompts and --output.
Examples: bash run.sh train configs/rfm.py bash run.sh validate configs/rfm.py --checkpoint model.pth --output output/validation bash run.sh inference configs/rfm.py --checkpoint model.pth --prompts examples/inference_prompts.json --output output/inference
All relative paths are resolved from this repository's root.Set PYTHON_BIN to select Python and CUDA_VISIBLE_DEVICES to select GPUs.For train, --launch uses background preparation; --help displays trainer help without starting workers.HELP exit 0fi
if [[ $# -lt 2 ]]; then echo 'Expected an action and config path. Run: bash run.sh --help' >&2 exit 2fi
action=$1config=$2shift 2case "$action" in train|validate|inference) ;; *) echo "Unknown action: $action (expected train, validate or inference)" >&2; exit 2 ;;esac
RFM_ROOT=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)cd -- "$RFM_ROOT"if [[ ! -f "$config" ]]; then echo "Config file not found: $config" >&2 exit 2fiPYTHON_BIN=${PYTHON_BIN:-python}export OMP_NUM_THREADS=${OMP_NUM_THREADS:-4}export PYTHONUNBUFFERED=1
case "$action" in train) for argument in "$@"; do if [[ "$argument" == --launch || "$argument" == -h || "$argument" == --help ]]; then exec "$PYTHON_BIN" -m scripts.train_rfm "$config" "$@" fi done world_size=$("$PYTHON_BIN" - "$config" <<'PY'import runpyimport sys
config = runpy.run_path(sys.argv[1])['config']world_size = config['world_size']if type(world_size) is not int or world_size < 1: raise SystemExit('config.world_size must be a positive integer')print(world_size)PY ) exec "$PYTHON_BIN" -m torch.distributed.run --standalone "--nproc_per_node=$world_size" \ scripts/train_rfm.py "$config" "$@" ;; validate) exec "$PYTHON_BIN" -m scripts.validate_rfm --config "$config" "$@" ;; inference) exec "$PYTHON_BIN" -m scripts.inference_rfm --config "$config" "$@" ;;esac123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146"""Text-only inference from a trained four-channel PixArt rectified-flow checkpoint."""import argparseimport gcimport hashlibimport jsonfrom pathlib import Pathimport runpy
from PIL import Imageimport torchfrom transformers import AutoTokenizer, T5EncoderModel
from diffusion.model.builder import build_modelfrom diffusion.rectified_flow import sample_rfm
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--config', help='Python config with resource paths and sampling settings') parser.add_argument('--checkpoint', required=True) parser.add_argument('--prompts', required=True, help='JSON list of case_id, prompt and seed objects') parser.add_argument('--output', required=True) parser.add_argument('--weights', choices=('raw', 'ema'), default='raw') parser.add_argument('--conditioning-cache') parser.add_argument('--vae-path') parser.add_argument('--cfg', type=float) parser.add_argument('--steps', type=int) parser.add_argument('--method', choices=('heun', 'dopri5')) parser.add_argument('--atol', type=float) parser.add_argument('--rtol', type=float) args = parser.parse_args() runtime = runpy.run_path(args.config)['config'] if args.config else {} for name, key, default in [('cfg', 'cfg_scale', 2.), ('steps', 'sampling_steps', 40), ('method', 'sampling_method', 'heun'), ('atol', 'sampling_atol', 1e-6), ('rtol', 'sampling_rtol', 1e-3)]: if getattr(args, name) is None: setattr(args, name, runtime.get(key, default)) if args.steps < 1 or args.atol <= 0 or args.rtol <= 0: raise ValueError('Sampling steps and tolerances must be positive') if args.method not in ('heun', 'dopri5'): raise ValueError('Supported sampling methods: heun, dopri5') output = Path(args.output) if output.exists() and any(output.iterdir()): raise ValueError(f'Refusing to overwrite existing results: {output}') entries = json.loads(Path(args.prompts).read_text()) ids = [entry['case_id'] for entry in entries] if not entries or len(set(ids)) != len(ids) or any(Path(name).name != name or name in ('.', '..') for name in ids): raise ValueError('Each prompt requires a unique filename-safe case_id') if any(not entry['prompt'].strip() or not isinstance(entry['seed'], int) or entry['seed'] < 0 for entry in entries): raise ValueError('Each case requires a nonempty prompt and nonnegative integer seed') torch.set_num_threads(4) torch.backends.cuda.matmul.allow_tf32 = True checkpoint = torch.load(args.checkpoint, map_location='cpu', weights_only=False, mmap=True) metadata = checkpoint['metadata'] for key, expected in dict(prediction_type='flow_velocity', path='linear', time_embedding='999*(1-t)', vae_scaling_factor=.18215).items(): if metadata.get(key) != expected: raise ValueError(f'Incompatible RFM checkpoint convention: {key}') config = dict(metadata['training_config']) for key in ('model', 'image_size', 'prediction_type', 'path', 'time_embedding', 'out_channels', 'qk_norm'): if key in runtime and runtime[key] != config.get(key): raise ValueError(f'Config differs from checkpoint architecture/convention: {key}') for key in ('conditioning_cache', 'vae_path'): override = getattr(args, key) if override is not None: config[key] = override elif key in runtime: config[key] = runtime[key] if config['model'] != 'PixArt_XL_2' or config['qk_norm'] != 'rms_norm': raise ValueError('Expected the pretrained PixArt XL/2 RFM with QK RMSNorm') state_key = 'state_dict' if args.weights == 'raw' else 'state_dict_ema' state = checkpoint[state_key] if 'y_embedder.y_embedding' not in state or 'blocks.0.cross_attn.q_linear.weight' not in state: raise ValueError('Expected the original T2I model with text cross-attention') original_conditioning = torch.load(config['conditioning_cache'], map_location='cpu', weights_only=True) if not torch.equal(state['y_embedder.y_embedding'], original_conditioning['empty'][0, 0].float()): raise ValueError('Unconditional text embedding differs from the original training cache') snapshot = Path(config['vae_path']).parent tokenizer = AutoTokenizer.from_pretrained(snapshot / 'tokenizer', local_files_only=True) # The synthetic training cache used T5Embedder(use_text_preprocessing=False), # which lowercases and strips but does not perform native caption cleaning. prompts = [entry['prompt'].lower().strip() for entry in entries] token_counts = [len(tokenizer(prompt, add_special_tokens=True)['input_ids']) for prompt in prompts] if max(token_counts) > 120: raise ValueError(f'Prompts exceed the 120-token training limit: {token_counts}') tokens = tokenizer(prompts, max_length=120, padding='max_length', truncation=False, return_tensors='pt').to('cuda') encoder = T5EncoderModel.from_pretrained(snapshot / 'text_encoder', local_files_only=True, torch_dtype=torch.bfloat16).cuda().eval().requires_grad_(False) with torch.inference_mode(): condition = encoder(**tokens).last_hidden_state[:, None].clone() mask = tokens.attention_mask.bool() output.mkdir(parents=True, exist_ok=True) torch.save(dict(condition=condition.cpu(), mask=mask.cpu(), prompts=prompts, t5_snapshot=str(snapshot), preprocessing='lowercase and strip', token_counts=token_counts), output / 'prompt_embeddings.pt') del encoder, tokens gc.collect() torch.cuda.empty_cache() model = build_model(config['model'], input_size=64, pred_sigma=False, model_max_length=120, class_dropout_prob=0., qk_norm='rms_norm', use_grad_checkpoint=False, lewei_scale=1.).float() # Load the trained output head unchanged: initialization-time head reset must # never be repeated when sampling an already trained RFM checkpoint. model.load_state_dict(state, strict=True) model.cuda().eval().requires_grad_(False) empty = original_conditioning['empty'].cuda().bfloat16() empty_mask = original_conditioning['empty_mask'].cuda().bool() from diffusers import AutoencoderKL vae = AutoencoderKL.from_pretrained(config['vae_path'], local_files_only=True).cuda().float().eval().requires_grad_(False) if abs(vae.config.scaling_factor - .18215) > 1e-6: raise ValueError('Unexpected VAE scaling factor') report = dict(model='PixArt_XL_2_T2I_RFM', weights=args.weights, state_key=state_key, optimizer_step=checkpoint['progress']['optimizer_step'], checkpoint=str(Path(args.checkpoint).resolve()), prediction_type='flow_velocity', conditioning='text_only', semantic_maps_used=False, cfg_scale=args.cfg, sampling_method=args.method, sampling_steps=args.steps if args.method == 'heun' else None, sampling_atol=args.atol, sampling_rtol=args.rtol, resolution=[512, 512], t5_snapshot=str(snapshot), text_preprocessing='lowercase and strip', unconditional_source=config['conditioning_cache'], cases=[]) print(json.dumps(dict(event='ready', token_counts=token_counts, weights=args.weights)), flush=True) with torch.inference_mode(): for index, entry in enumerate(entries): noise = torch.randn(1, 4, 64, 64, device='cuda', generator=torch.Generator(device='cuda').manual_seed(entry['seed'])) latent, sampling = sample_rfm(model, noise, condition[index:index+1], mask[index:index+1], empty, empty_mask, cfg_scale=args.cfg, method=args.method, steps=args.steps, atol=args.atol, rtol=args.rtol) decoded = vae.decode(latent.float() / .18215).sample[0] if not torch.isfinite(decoded).all(): raise FloatingPointError(f'Nonfinite decoded image: {entry["case_id"]}') pixels = ((decoded / 2 + .5).clamp(0, 1) * 255).round().byte().permute(1, 2, 0).cpu().numpy() Image.fromarray(pixels).save(output / f'{entry["case_id"]}.png') report['cases'].append(dict(case_id=entry['case_id'], prompt=entry['prompt'], encoded_prompt=prompts[index], token_count=token_counts[index], seed=entry['seed'], image=f'{entry["case_id"]}.png', latent_rms=latent.square().mean().sqrt().item(), sampler=sampling)) print(json.dumps(dict(event='image_saved', case_id=entry['case_id'])), flush=True) with Path(args.checkpoint).open('rb') as handle: report['checkpoint_sha256'] = hashlib.file_digest(handle, 'sha256').hexdigest() (output / 'validation.json').write_text(json.dumps(report, indent=2) + '\n') print(json.dumps(report, indent=2), flush=True)
if __name__ == '__main__': main()1"""Model initialization and pre-training preparation tools."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""Cache synthetic image posteriors and original generation-prompt T5 features.
Each worker owns a disjoint shard. Features retain only unmasked tokens; maskedpadding is reconstructed during training without changing attention outputs."""import argparsefrom concurrent.futures import ThreadPoolExecutorimport hashlibimport jsonimport osfrom pathlib import Pathimport sysimport time
ROOT = Path(__file__).resolve().parents[2]sys.path.insert(0, str(ROOT))sys.path.insert(0, str(ROOT / 'output/t5_dependencies'))import numpy as npfrom PIL import Imageimport torchfrom diffusers import AutoencoderKLfrom diffusion.model.t5 import T5Embedderfrom scripts.preparation.encode_image_latents import load_image, save_latent, verify_latent
def save_caption(job): path, feature = job temporary = path.with_suffix('.tmp') with temporary.open('wb') as handle: np.savez_compressed(handle, caption_feature=feature, attention_mask=np.ones((1, feature.shape[1]), dtype=np.int64)) temporary.replace(path)
if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source', default='data/synth_images/pixelart_synth512') parser.add_argument('--output', default='output/datasets_512/PixelArtSynth') parser.add_argument('--shard', type=int, default=0) parser.add_argument('--shards', type=int, default=2) parser.add_argument('--batch-size', type=int, default=32) parser.add_argument('--limit', type=int, default=0) parser.add_argument('--finalize', action='store_true') args = parser.parse_args() if not 0 <= args.shard < args.shards or args.batch_size < 1 or args.limit < 0: raise ValueError('Invalid shard, batch size or limit') source, output = Path(args.source).resolve(), Path(args.output).resolve() snapshot = Path.home()/'.cache/huggingface/hub/models--PixArt-alpha--PixArt-XL-2-512x512/snapshots/50f702106901db6d0f8b67eb88e814c56ded2692' content = (source/'metadata.jsonl').read_bytes() rows = [json.loads(line) for line in content.splitlines()] if args.limit: rows = rows[:args.limit] if len({row['file_name'] for row in rows}) != len(rows): raise ValueError('Duplicate source filenames') output.mkdir(parents=True, exist_ok=True) for name in ('latents', 't5_embeddings'): (output/name).mkdir(exist_ok=True) settings = dict(source=str(source), source_metadata_sha256=hashlib.sha256(content).hexdigest(), snapshot=str(snapshot), shards=args.shards, count=len(rows), latent_dtype='float32', latent_scaled=False, scaling_factor=.18215, t5_inference_dtype='bfloat16', t5_storage_dtype='float32', max_length=120, prompt_field='model_prompt', text_preprocessing=False, caption_storage='unmasked_tokens_only', vae_tf32=False, cache_format_version=1) settings_path = output/'cache_settings.json' if settings_path.exists(): if json.loads(settings_path.read_text()) != settings: raise ValueError('Existing cache settings differ; use a new output directory') else: # Same immutable settings in every shard; atomic publication. temporary = output/f'settings-{args.shard}.tmp' temporary.write_text(json.dumps(settings, indent=2)+'\n') temporary.replace(settings_path) if args.finalize: completed = [] for shard in range(args.shards): summary = json.loads((output/f'completed-{shard}.json').read_text()) if summary['settings'] != settings: raise ValueError('Shard settings mismatch') completed.extend(json.loads(line) for line in (output/f'metadata-{shard}.jsonl').read_text().splitlines()) completed.sort(key=lambda row: row['index']) if [row['index'] for row in completed] != [row['index'] for row in rows]: raise ValueError('Missing, duplicate or unexpected records') if any(not (output/row[key]).is_file() for row in completed for key in ('latent_file','t5_file')): raise ValueError('Missing cache files') temporary = output/'training_metadata.tmp' temporary.write_text(''.join(json.dumps(row, ensure_ascii=False)+'\n' for row in completed)) temporary.replace(output/'training_metadata.jsonl') summary = dict(settings, complete=True, images=len(completed), total_caption_tokens=sum(row['t5_length'] for row in completed)) (output/'summary.json').write_text(json.dumps(summary, indent=2)+'\n') print(json.dumps(summary, indent=2), flush=True) sys.exit(0) assigned = rows[args.shard::args.shards] for row in assigned: if row['width'] != 512 or row['height'] != 512 or not isinstance(row['model_prompt'], str): raise ValueError(f'Invalid source row: {row["index"]}') row['file_name'] = str(source/row['file_name']) row['prompt'] = row['model_prompt'] row['latent_file'] = f'latents/{row["index"]:06d}.npz' row['t5_file'] = f't5_embeddings/{row["index"]:06d}.npz' torch.set_num_threads(4) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False os.environ['HF_HUB_OFFLINE'] = '1' vae = AutoencoderKL.from_pretrained(snapshot/'vae', local_files_only=True, torch_dtype=torch.float32).cuda().eval().requires_grad_(False) text = T5Embedder('cuda', dir_or_name=snapshot.name, cache_dir=str(snapshot.parent), local_cache=True, torch_dtype=torch.bfloat16, use_text_preprocessing=False) text.model.eval().requires_grad_(False) started = time.monotonic() with torch.inference_mode(), ThreadPoolExecutor(max_workers=8) as pool: with (output/f'metadata-{args.shard}.jsonl').open('w') as journal: for start in range(0,len(assigned),args.batch_size): batch = assigned[start:start+args.batch_size] pending = [row for row in batch if not (output/row['latent_file']).exists()] if pending: pixels = torch.from_numpy(np.stack(list(pool.map(load_image, [row['file_name'] for row in pending])))).cuda() posterior = vae.encode(pixels).latent_dist means, stds = posterior.mean.cpu().numpy(), posterior.std.cpu().numpy() if not np.isfinite(means).all() or not np.isfinite(stds).all() or not (stds > 0).all(): raise ValueError('Invalid VAE posterior') list(pool.map(save_latent, [(output/row['latent_file'], mean, std, .18215) for row,mean,std in zip(pending,means,stds)])) del pixels, posterior pending = [row for row in batch if not (output/row['t5_file']).exists()] if pending: feature, mask = text.get_text_embeddings([row['prompt'] for row in pending]) feature, mask = feature.float().cpu().numpy(), mask.cpu().numpy() if not np.isfinite(feature).all(): raise ValueError('Nonfinite caption features') jobs = [(output/row['t5_file'], feature[i:i+1,:int(mask[i].sum())]) for i,row in enumerate(pending)] list(pool.map(save_caption, jobs)) # Verify saved or resumed files before publishing their manifest records. for row in batch: verify_latent(output/row['latent_file']) with np.load(output/row['t5_file'], allow_pickle=False) as cached: value, attention = cached['caption_feature'], cached['attention_mask'] length = value.shape[1] if value.shape != (1,length,4096) or not 1 <= length <= 120 or value.dtype != np.float32: raise ValueError('Invalid caption shape or dtype') if not np.isfinite(value).all() or attention.shape != (1,length) or not (attention == 1).all(): raise ValueError('Invalid cached caption values/mask') row['t5_length'] = length journal.write(json.dumps(row, ensure_ascii=False)+'\n') journal.flush() saved = start+len(batch) if saved % (args.batch_size*10) == 0 or saved == len(assigned): elapsed = time.monotonic()-started progress = dict(saved=saved,total=len(assigned),seconds=elapsed,images_per_second=saved/elapsed) (output/f'progress-{args.shard}.json').write_text(json.dumps(progress)+'\n') print(f'Shard {args.shard}: {progress}',flush=True) (output/f'completed-{args.shard}.json').write_text(json.dumps(dict(settings=settings, count=len(assigned)))+'\n')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219"""Cache PixArt-Alpha VAE posterior statistics as one NPZ per image.
Each file contains unscaled FP32 `latent` (posterior mean) and `std`, bothshaped (4, 64, 64), plus scalar `scaling_factor` and `scaled=False`.For diffusion training: z = (latent + std * noise) * scaling_factor.For deterministic reconstruction: vae.decode(latent).
Run one shard per GPU with CUDA_VISIBLE_DEVICES and --shard-index.After all shards finish, --finalize verifies every NPZ and exportslatent_metadata.jsonl without changing the image/caption metadata."""
import argparseimport hashlibimport importlib.metadataimport itertoolsimport jsonimport osimport timefrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Path
import numpy as npfrom PIL import Image
MODEL_ID = "PixArt-alpha/PixArt-XL-2-512x512"REVISION = "50f702106901db6d0f8b67eb88e814c56ded2692"
def load_image(path): with Image.open(path) as image: if image.size != (512, 512) or image.mode != "RGB": raise ValueError(f"Expected a 512x512 RGB image: {path}") pixels = np.asarray(image, dtype=np.float32) return (pixels.transpose(2, 0, 1).copy() / 255.0 - 0.5) / 0.5
def save_latent(job): path, mean, std, scaling_factor = job temporary = path.with_suffix(".npz.tmp") with temporary.open("wb") as handle: np.savez_compressed( handle, latent=mean, std=std, scaling_factor=np.float32(scaling_factor), scaled=np.bool_(False), ) os.replace(temporary, path)
def verify_latent(path): with np.load(path, allow_pickle=False) as data: if set(data.files) != {"latent", "std", "scaling_factor", "scaled"}: raise ValueError(f"Unexpected NPZ keys: {path}") for key in ("latent", "std"): array = data[key] if array.shape != (4, 64, 64) or array.dtype != np.float32: raise ValueError(f"Unexpected {key} shape or dtype: {path}") if not np.isfinite(array).all(): raise ValueError(f"Non-finite {key}: {path}") if np.any(data["std"] <= 0): raise ValueError(f"Nonpositive posterior standard deviation: {path}") if data["scaled"].shape != () or bool(data["scaled"]): raise ValueError(f"Expected an unscaled posterior: {path}") if data["scaling_factor"].shape != () or not np.isclose(float(data["scaling_factor"]), 0.18215): raise ValueError(f"Unexpected scaling factor: {path}") return path.stat().st_size
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--dataset-root", type=Path, default=Path("output/datasets_512")) parser.add_argument("--datasets", nargs="+", default=["LSDIR", "Unsplash"]) parser.add_argument("--vae-path", type=Path, default=( Path.home() / ".cache/huggingface/hub" / "models--PixArt-alpha--PixArt-XL-2-512x512" / "snapshots" / REVISION / "vae" )) parser.add_argument("--latent-dir", default="latents") parser.add_argument("--num-shards", type=int, default=4) parser.add_argument("--shard-index", type=int, default=0) parser.add_argument("--batch-size", type=int, default=16) parser.add_argument("--workers", type=int, default=8) parser.add_argument("--limit", type=int, default=0) parser.add_argument("--finalize", action="store_true") args = parser.parse_args() if not 0 <= args.shard_index < args.num_shards or min(args.batch_size, args.workers) < 1: parser.error("Invalid shard, batch size, or worker count") if args.limit < 0 or (args.finalize and args.limit): parser.error("Limit must be nonnegative; pilot runs cannot be finalized") if Path(args.latent_dir).name != args.latent_dir or args.latent_dir in (".", "..", "images"): parser.error("latent-dir must be a separate simple directory name")
if len(set(args.datasets)) != len(args.datasets) or any(Path(name).name != name or name in (".", "..") for name in args.datasets): parser.error("Dataset names must be unique simple directory names")
datasets = [] hashes = {} for name in args.datasets: root = args.dataset_root / name content = (root / "metadata.jsonl").read_bytes() hashes[name] = hashlib.sha256(content).hexdigest() rows = [json.loads(line) for line in content.splitlines()] if len({row["file_name"] for row in rows}) != len(rows): raise ValueError(f"Duplicate image references in {name}") for row in rows: row["dataset"] = name row["latent_file"] = str(Path(args.latent_dir) / (Path(row["file_name"]).stem + ".npz")) if len({row["latent_file"] for row in rows}) != len(rows): raise ValueError(f"Latent filename collision in {name}") datasets.append(rows) records = [row for pair in itertools.zip_longest(*datasets) for row in pair if row] if args.limit: records = records[:args.limit] config_path = args.vae_path / "config.json" weight_path = args.vae_path / "diffusion_pytorch_model.safetensors" settings = { "vae_model": MODEL_ID, "vae_revision": REVISION, "vae_subfolder": "vae", "vae_config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), "vae_weights_sha256": hashlib.sha256(weight_path.read_bytes()).hexdigest(), "metadata_sha256": hashes, "image_size": [512, 512], "latent_shape": [4, 64, 64], "dtype": "float32", "latent": "unscaled posterior mean (deterministic mode)", "std": "unscaled posterior standard deviation", "scaling_factor": 0.18215, "scaled": False, "normalization": "(RGB / 255 - 0.5) / 0.5", "num_shards": args.num_shards, "limit": args.limit, "versions": {package: importlib.metadata.version(package) for package in ("torch", "diffusers", "numpy")}, } run_directory = args.dataset_root / "latent_runs" / args.latent_dir run_directory.mkdir(parents=True, exist_ok=True)
if args.finalize: for shard in range(args.num_shards): recorded = json.loads((run_directory / f"settings-{shard:03d}.json").read_text()) if recorded != settings: raise ValueError(f"Settings mismatch for shard {shard}") with ThreadPoolExecutor(max_workers=args.workers) as pool: for name, rows in zip(args.datasets, datasets): root = args.dataset_root / name paths = [root / row["latent_file"] for row in rows] if set(paths) != set((root / args.latent_dir).glob("*.npz")): raise ValueError(f"Missing or extra latents in {name}") total_bytes = sum(pool.map(verify_latent, paths)) destination = root / "latent_metadata.jsonl" content = "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows) if destination.exists() and destination.read_text() != content: raise ValueError(f"Refusing to overwrite different metadata: {destination}") temporary = destination.with_suffix(".jsonl.tmp") temporary.write_text(content) os.replace(temporary, destination) summary = dict(settings, dataset=name, count=len(rows), complete=True, all_npz_verified=True, total_bytes=total_bytes) (root / "latent_summary.json").write_text(json.dumps(summary, indent=2) + "\n") print(f"{name}: verified and indexed {len(rows):,} NPZ files", flush=True) return
settings_path = run_directory / f"settings-{args.shard_index:03d}.json" if settings_path.exists() and json.loads(settings_path.read_text()) != settings: raise ValueError("Cache settings have changed; use a new --latent-dir") assigned = records[args.shard_index::args.num_shards] pending = [] for row in assigned: path = args.dataset_root / row["dataset"] / row["latent_file"] path.parent.mkdir(parents=True, exist_ok=True) if path.exists(): if not settings_path.exists(): raise ValueError(f"Existing latent has no provenance: {path}") verify_latent(path) else: pending.append(row) settings_path.write_text(json.dumps(settings, indent=2) + "\n") saved = len(assigned) - len(pending) print(f"Shard {args.shard_index}: {saved:,} complete, {len(pending):,} pending", flush=True) if not pending: return
import torch from diffusers import AutoencoderKL
torch.set_num_threads(4) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False vae = AutoencoderKL.from_pretrained( args.vae_path, local_files_only=True, use_safetensors=True, torch_dtype=torch.float32 ).to("cuda").eval().requires_grad_(False) if vae.config.latent_channels != 4 or vae.config.scaling_factor != settings["scaling_factor"]: raise ValueError("Unexpected VAE configuration") started = time.monotonic() with torch.inference_mode(), ThreadPoolExecutor(max_workers=args.workers) as pool: for start in range(0, len(pending), args.batch_size): batch = pending[start:start + args.batch_size] paths = [args.dataset_root / row["dataset"] / row["file_name"] for row in batch] pixels = torch.from_numpy(np.stack(list(pool.map(load_image, paths)))).to("cuda") posterior = vae.encode(pixels).latent_dist means = posterior.mean.cpu().numpy() stds = posterior.std.cpu().numpy() if means.shape != (len(batch), 4, 64, 64) or not np.isfinite(means).all(): raise ValueError("Invalid VAE means") if not np.isfinite(stds).all() or np.any(stds <= 0): raise ValueError("Invalid VAE standard deviations") jobs = [(args.dataset_root / row["dataset"] / row["latent_file"], mean, std, vae.config.scaling_factor) for row, mean, std in zip(batch, means, stds)] list(pool.map(save_latent, jobs)) saved += len(batch) if (start // args.batch_size + 1) % 10 == 0 or saved == len(assigned): elapsed = time.monotonic() - started print(f"Shard {args.shard_index}: {saved:,}/{len(assigned):,} saved; " f"{(start + len(batch)) / elapsed:.2f} images/s; {elapsed:.1f}s elapsed", flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""Prepare frozen conditioning and strictly map a Theta RAW checkpoint to native PixArt."""import argparseimport hashlibimport jsonimport osfrom pathlib import Pathimport sys
ROOT = Path(__file__).resolve().parents[2]sys.path.insert(0, str(ROOT))sys.path.insert(0, str(ROOT / 'output/training_dependencies'))sys.path.insert(0, str(ROOT / 'output/t5_dependencies'))
import torchfrom safetensors.torch import load_file
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source', required=True) parser.add_argument('--prompts', required=True) parser.add_argument('--output', required=True) parser.add_argument('--snapshot', required=True) args = parser.parse_args() os.environ['HF_HUB_OFFLINE'] = '1' torch.set_num_threads(4) source, work, snapshot = Path(args.source).resolve(), Path(args.output), Path(args.snapshot).resolve() work.mkdir(parents=True, exist_ok=True) entries = json.loads(Path(args.prompts).read_text()) if len(entries) != 4: raise ValueError('Exactly four validation prompts are required') config = json.loads((source / 'transformer/config.json').read_text()) expected = dict(num_layers=28, num_attention_heads=16, attention_head_dim=72, in_channels=4, out_channels=8, patch_size=2, sample_size=64, qk_norm='rms_norm', qk_norm_eps=1e-6, use_additional_conditions=False, noise_preconditioning_config=None) for key, value in expected.items(): if config.get(key) != value: raise ValueError(f'Unexpected source architecture: {key}') schedule = json.loads((source / 'scheduler/scheduler_config.json').read_text()) for key, value in dict(prediction_type='epsilon', beta_schedule='linear', beta_start=.0001, beta_end=.02, num_train_timesteps=1000, rescale_betas_zero_snr=False).items(): if schedule.get(key) != value: raise ValueError(f'Unexpected source schedule: {key}') from transformers import AutoTokenizer, T5EncoderModel tokenizer = AutoTokenizer.from_pretrained(snapshot / 'tokenizer', local_files_only=True) encoder = T5EncoderModel.from_pretrained(snapshot / 'text_encoder', local_files_only=True, dtype=torch.bfloat16).cuda().eval().requires_grad_(False) prompts = [entry['prompt'] for entry in entries] tokens = tokenizer([''] + [prompt.strip() for prompt in prompts], max_length=120, padding='max_length', truncation=True, return_tensors='pt').to('cuda') with torch.inference_mode(): features = encoder(**tokens).last_hidden_state.cpu()[:, None] masks = tokens.attention_mask.bool().cpu() torch.save(dict(empty=features[:1], empty_mask=masks[:1], condition=features[1:], mask=masks[1:], prompts=prompts, seeds=[entry['seed'] for entry in entries], t5_snapshot=str(snapshot), preprocessing='strip only; matches source TextConditioner'), work / 'conditioning.pt') del encoder, tokens torch.cuda.empty_cache() from diffusion.model.builder import build_model from diffusion.utils.theta_import import import_theta_state, make_initial_metadata model = build_model('PixArt_XL_2', input_size=64, pred_sigma=True, model_max_length=120, class_dropout_prob=0., qk_norm='rms_norm', use_grad_checkpoint=False, lewei_scale=1.).float() weight_path = source / 'transformer/diffusion_pytorch_model.safetensors' weights = load_file(weight_path) import_theta_state(model, weights, features[0, 0]) provenance = dict(source=str(source), source_weights='raw', source_prediction_type='epsilon', source_sha256=hashlib.file_digest(weight_path.open('rb'), 'sha256').hexdigest(), source_tensor_count=len(weights), source_optimizer_step=10000, mapping='all learned tensors strictly mapped; regenerate sin/cos position buffer; encode empty text', conditioning_sha256=hashlib.file_digest((work / 'conditioning.pt').open('rb'), 'sha256').hexdigest()) native_config = dict(prediction_type='epsilon', qk_norm='rms_norm', qk_norm_eps=1e-6, source_model=str(source), source_weights='raw', conditioning_mode='empty_text') metadata = make_initial_metadata(native_config, .18215, model) torch.save(dict(state_dict=model.state_dict(), metadata=metadata, import_provenance=provenance), work / 'initial_raw_epsilon.pth') (work / 'import.json').write_text(json.dumps(provenance, indent=2) + '\n') (work / 'prompts.json').write_text(json.dumps(entries, indent=2) + '\n') print(json.dumps(provenance, indent=2), flush=True)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176"""Compare uninterrupted/resumed RFM updates and publish a local HTML report."""import hashlibimport htmlimport jsonfrom pathlib import Pathimport sys
ROOT = Path(__file__).resolve().parents[2]sys.path[:0] = [str(ROOT), str(ROOT / 'output/training_dependencies')]import numpy as npfrom PIL import Imageimport torch
from diffusion.model.builder import build_modelfrom diffusion.rectified_flow import flow_matching_loss, sample_rfmfrom datasets.rfm_data import read_cache
def compare(left, right, path, report): if isinstance(left, torch.Tensor): if left.shape != right.shape or left.dtype != right.dtype: raise AssertionError(f'{path}: shape/dtype mismatch') report['tensors_compared'] += 1 if not torch.equal(left, right): difference = (left.float() - right.float()).abs().max().item() report['differences'].append(dict(path=path, max_abs=difference)) tolerance = 2e-5 if path.startswith('optimizer.') else 1e-6 if not left.is_floating_point() or not torch.allclose(left, right, atol=tolerance, rtol=1e-5): report['outside_numerical_tolerance'].append(path) elif isinstance(left, np.ndarray): if not np.array_equal(left, right): report['differences'].append(dict(path=path, kind='numpy')) report['outside_numerical_tolerance'].append(path) elif isinstance(left, dict): if left.keys() != right.keys(): raise AssertionError(f'{path}: keys mismatch') for key in left: compare(left[key], right[key], f'{path}.{key}', report) elif isinstance(left, (list, tuple)): if len(left) != len(right): raise AssertionError(f'{path}: length mismatch') for index, (first, second) in enumerate(zip(left, right)): compare(first, second, f'{path}.{index}', report) elif left != right: report['differences'].append(dict(path=path, kind='scalar')) report['outside_numerical_tolerance'].append(path)
def main(): torch.set_num_threads(4) work = ROOT / 'output/rfm_mix50_smoke' uninterrupted = torch.load(work/'uninterrupted/checkpoints/update-000020.pth', map_location='cpu', weights_only=False, mmap=True) resumed = torch.load(work/'resumed/checkpoints/update-000020.pth', map_location='cpu', weights_only=False, mmap=True) report = dict(tensors_compared=0, differences=[], outside_numerical_tolerance=[], resume_tolerance=dict(model_atol=1e-6, optimizer_atol=2e-5, rtol=1e-5)) for key in ('state_dict', 'state_dict_ema', 'optimizer', 'scheduler', 'progress', 'rank_rng'): compare(uninterrupted[key], resumed[key], key, report) report['resume_bitwise_equal'] = not report['differences'] report['resume_numerically_close'] = not report['outside_numerical_tolerance'] report['resume_rng_cursor_scheduler_exact'] = not any( item['path'].split('.')[0] in ('rank_rng', 'progress', 'scheduler') for item in report['differences']) report['resume_max_abs'] = {key: max((item['max_abs'] for item in report['differences'] if item['path'].startswith(key + '.') and 'max_abs' in item), default=0.) for key in ('state_dict', 'state_dict_ema', 'optimizer')} records = [json.loads(line) for line in (work/'uninterrupted/train.jsonl').read_text().splitlines()] replay = [json.loads(line) for line in (work/'resumed/train.jsonl').read_text().splitlines()] report['replayed_metrics_equal'] = all( a[key] == b[key] for a, b in zip(records[10:], replay) for key in ('step', 'loss', 'grad_norm', 'learning_rate', 'samples_seen', 'time_bins_sum_count')) report['replayed_steps'] = [row['step'] for row in replay] report['replayed_loss_max_abs'] = max(abs(a['loss']-b['loss']) for a,b in zip(records[10:], replay)) assert report['replayed_steps'] == list(range(11, 21)) report['all_steps_balanced'] = all(row['source_counts_per_update'] == [16, 16] for row in records + replay) report['all_metrics_finite'] = all(np.isfinite([r['loss'], r['grad_norm']]).all() for r in records + replay) report['peak_training_gpu_gib'] = max(max(r['peak_gpu_gib_per_rank']) for r in records + replay) report['steady_training_seconds_per_step'] = float(np.median([r['seconds_per_step'] for r in records[2:]])) report['validation_images'] = [] for folder in ('uninterrupted', 'resumed'): for path in sorted((work/folder/'validation/update-000020').glob('*.png')): with Image.open(path) as image: image.load() assert image.size == (512, 512) and image.mode == 'RGB' report['validation_images'].append(str(path.relative_to(work))) assert len(report['validation_images']) == 16 config = uninterrupted['metadata']['training_config'] source = Path(config['source_model'])/'transformer/diffusion_pytorch_model.safetensors' with source.open('rb') as handle: report['source_checkpoint_unchanged'] = hashlib.file_digest(handle, 'sha256').hexdigest() == config['source_checkpoint_sha256'] initial = torch.load(config['init_checkpoint'], map_location='cpu', weights_only=False, mmap=True) head = ['final_layer.linear.weight', 'final_layer.linear.bias'] report['changed_backbone_tensors'] = sum(not torch.equal(value, initial['state_dict'][key]) for key, value in uninterrupted['state_dict'].items() if key not in head) report['head_max_abs'] = uninterrupted['state_dict'][head[0]].abs().max().item() assert report['changed_backbone_tensors'] > 0 and report['head_max_abs'] > 0 del resumed, initial
# Fixed data/noise/time probe: confirm a real forward after optimization. device = torch.device('cuda', 0) model = build_model('PixArt_XL_2', input_size=64, pred_sigma=False, model_max_length=120, class_dropout_prob=0., qk_norm='rms_norm', use_grad_checkpoint=False, lewei_scale=1.).float().to(device).eval() model.load_state_dict(uninterrupted['state_dict'], strict=True) fixed = [] for name in config['data_roots']: root = Path(name) rows = [json.loads(line) for line in (root/'training_metadata.jsonl').read_text().splitlines()] fixed.extend(read_cache((root, row)) for row in rows[:4]) mean, std, caption, mask = [torch.from_numpy(np.stack([row[column] for row in fixed])).to(device) for column in range(4)] caption, mask = caption.bfloat16(), mask.bool() generator = torch.Generator(device=device).manual_seed(914) clean = (mean + std * torch.randn(mean.shape, generator=generator, device=device)) * .18215 noise = torch.randn(clean.shape, generator=generator, device=device) times = torch.linspace(0, 1, 8, device=device) with torch.no_grad(), torch.autocast('cuda', dtype=torch.bfloat16): losses = flow_matching_loss(model, clean, noise, times, caption, mask) report['fixed_probe'] = dict(time=times.tolist(), zero_head_loss=(clean-noise).square().flatten(1).mean(1).tolist(), trained_loss=losses.tolist()) assert torch.isfinite(losses).all() text = torch.load(config['conditioning_cache'], map_location='cpu', weights_only=True) sample_noise = torch.cat([torch.randn(1, 4, 64, 64, device=device, generator=torch.Generator(device=device).manual_seed(seed)) for seed in config['validation_seeds']]) heun, heun_report = sample_rfm(model, sample_noise, text['condition'].to(device).bfloat16(), text['mask'].to(device).bool(), text['empty'].to(device).bfloat16(), text['empty_mask'].to(device).bool(), method='heun', steps=50) reference = torch.load(work/'uninterrupted/validation/update-000020/raw.pt', weights_only=True)['latents'].to(device) report['heun_check'] = dict(**heun_report, relative_latent_l2=float((heun-reference).norm()/reference.norm())) torch.save(dict(latents=heun.cpu(), **heun_report), work/'heun_raw.pt') report['passed'] = all(report[key] for key in ('resume_numerically_close', 'resume_rng_cursor_scheduler_exact', 'all_steps_balanced', 'all_metrics_finite', 'source_checkpoint_unchanged')) report['status'] = ('PASS' if report['resume_bitwise_equal'] else 'PASS_WITH_NUMERICAL_DRIFT') if report['passed'] else 'FAIL' (work/'verification.json').write_text(json.dumps(report, indent=2))
images = ''.join(f'<figure><img loading="lazy" src="{path}"><figcaption>{path}</figcaption></figure>' for path in report['validation_images'] if path.startswith('uninterrupted/')) summary = html.escape(json.dumps({key: value for key, value in report.items() if key not in ('validation_images', 'fixed_probe', 'differences')}, indent=2, ensure_ascii=False)) source_rows = json.loads((work/'source_audit.json').read_text()) dataset_rows = ''.join(f'<tr><td>{html.escape(row["source"])}</td><td>{row["images"]:,}</td><td>50%</td><td>256</td></tr>' for row in source_rows) (work/'report.html').write_text(f'''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>PixArt RFM 50/50 短程验证</title><style>body{{font:16px/1.7 system-ui;max-width:1150px;margin:40px auto;padding:0 24px;color:#172333;background:#f6f8fb}}table{{border-collapse:collapse;width:100%;background:white}}td,th{{padding:12px;border:1px solid #d5dce5;text-align:left}}.gallery{{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px}}figure{{margin:0}}img{{width:100%;border-radius:8px}}figcaption{{font-size:12px;overflow-wrap:anywhere}}pre{{background:#e9eef5;padding:20px;overflow:auto}}.notice{{background:#fff1c9;padding:18px;border-radius:8px}}</style><h1>PixArt RFM · 50/50 数据混合短程验证</h1><p>状态:<strong>{report['status']}</strong>。4 GPUs × batch 8,无梯度累积,BF16,关闭 gradient checkpointing。</p><p class="notice">本次只验证工程流程:20 iter 连续训练,与第 10 iter 恢复后再训练到 20 iter。输出头从零开始,且尚处于 500 iter warmup,以下图像主要是噪声,不能作为生成质量或收敛结论。未启动 100K 正式训练,未完成全量 latent/T5 缓存。</p><h2>数据</h2><table><tr><th>来源</th><th>全量清单</th><th>每 batch 比例</th><th>本次缓存</th></tr>{dataset_rows}</table><p>全量检查为路径存在、文件名/索引唯一、元数据尺寸和提示词检查;实际解码与编码的是本次 512 张样本。使用 model_prompt 原始生成提示词。两个来源独立打乱、循环,不截断较大的数据集。</p><h2>训练定义</h2><p>x(t)=(1−t)ε+t·z;target=z−ε;t~Uniform(0,1);普通 MSE,无 VB。时间 embedding 使用连续 999(1−t),不使用旧 VP β schedule。保留 QK RMSNorm 骨干,4 通道输出投影零初始化;EMA 从新 RAW 复制。</p><h2>验证结果</h2><p>恢复检查不满足逐位一致:RAW/EMA 和 optimizer 存在下列微小数值差异。随机状态、数据游标、scheduler 完全一致;单独按报告列出的绝对/相对容差检查模型和 optimizer。误差来源尚未单独定位,不声称严格确定性恢复。</p><pre>{summary}</pre><p><a href="verification.json">完整验证 JSON</a> · <a href="source_audit.json">全量清单检查</a> ·<a href="uninterrupted/train.jsonl">连续训练日志</a> · <a href="resumed/train.jsonl">恢复日志</a> ·<a href="uninterrupted/initialization.json">初始化记录</a> · <a href="uninterrupted/validation/update-000020/sampler.json">采样器记录</a></p><h2>RAW / EMA 流程输出</h2><div class="gallery">{images}</div><h2>下一阶段</h2><p>完成两个来源的全量缓存后,正式配置会检查 50,000 / 76,708 条记录。正式训练默认 100K iter,每 500 iter 生成 RAW/EMA 各 4 张,每 5000 iter 保存。先在早期 checkpoint 观察目标适配、时间分桶 loss 与生成质量,再判断 RFM 是否改善质感。</p></html>''') print(json.dumps({key: value for key, value in report.items() if key not in ('validation_images', 'fixed_probe', 'differences')}, indent=2)) if not report['passed']: raise AssertionError('RFM smoke verification failed; see verification.json')
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490"""PixArt RFM training: use torchrun directly, or --launch for background cache preparation and training."""import argparsefrom copy import deepcopyfrom datetime import datetime, timedelta, timezoneimport fcntlimport hashlibimport jsonimport osfrom pathlib import Pathimport randomimport runpyimport shutilimport subprocessimport sysimport time
ROOT = Path(__file__).resolve().parents[1]sys.path[:0] = [str(ROOT), str(ROOT / 'output/training_dependencies')]
import numpy as npfrom PIL import Imageimport torchimport torch.distributed as distfrom torch.nn.parallel import DistributedDataParallelfrom torch.utils.data import DataLoader
from diffusion.model.builder import build_modelfrom diffusion.rectified_flow import flow_matching_loss, sample_rfmfrom diffusion.utils.rfm_checkpoint import (drop_to_empty_text, rng_state, restore_rng, update_ema, save_training_checkpoint)from datasets.rfm_data import CachedDataset, BalancedFlowSampler
@torch.no_grad()def validate(model, ema, vae, text, config, step, device): folder = Path(config['work_dir']) / 'validation' / f'update-{step:06d}' folder.mkdir(parents=True, exist_ok=True) (folder / 'prompts.json').write_text(json.dumps(text['prompts'], indent=2)) condition = text['condition'].to(device, dtype=torch.bfloat16) mask = text['mask'].to(device, dtype=torch.bool) empty = text['empty'].to(device, dtype=torch.bfloat16) empty_mask = text['empty_mask'].to(device, dtype=torch.bool) noise = torch.cat([torch.randn(1, 4, 64, 64, device=device, generator=torch.Generator(device=device).manual_seed(seed)) for seed in config['validation_seeds']]) reports = {} for label, network in [('raw', model), ('ema', ema)]: network.eval() latents, report = sample_rfm(network, noise, condition, mask, empty, empty_mask, config['cfg_scale'], config['sampling_method'], config['sampling_steps'], config['sampling_atol'], config['sampling_rtol']) report['latent_rms'] = latents.square().mean().sqrt().item() for index, latent in enumerate(latents): decoded = vae.decode(latent[None] / .18215).sample[0] if not torch.isfinite(decoded).all(): raise FloatingPointError('Nonfinite VAE decode') pixels = ((decoded / 2 + .5).clamp(0, 1) * 255).round().byte().permute(1, 2, 0) Image.fromarray(pixels.cpu().numpy()).save(folder / f'{label}-{index}.png') torch.save(dict(latents=latents.cpu(), seeds=config['validation_seeds'], **report), folder / f'{label}.pt') reports[label] = report (folder / 'sampler.json').write_text(json.dumps(reports, indent=2)) model.train() return reports
def publish_status(folder, stage, **details): status = dict(stage=stage, controller_pid=os.getpid(), updated_at=datetime.now(timezone.utc).isoformat(), **details) temporary = folder / 'status.tmp' temporary.write_text(json.dumps(status, indent=2)) temporary.replace(folder / 'status.json')
def launch_training(args, config): """Prepare caches and run a detached controller, or execute that controller.""" overrides = [] for key in ('work_dir', 'max_train_steps', 'validate_every_updates', 'save_every_updates'): value = getattr(args, key) if value is not None: overrides.extend(['--' + key.replace('_', '-'), str(value)]) work = Path(config['work_dir']) work.mkdir(parents=True, exist_ok=True) preparation = work / 'preparation' preparation.mkdir(exist_ok=True) if not args.controller: lock = (preparation / 'launch.lock').open('w') fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) if (preparation / 'controller.json').exists(): previous = json.loads((preparation / 'controller.json').read_text()) proc = Path(f'/proc/{previous["pid"]}/cmdline') if proc.exists() and b'--controller' in proc.read_bytes() and b'train_rfm' in proc.read_bytes(): raise RuntimeError(f'RFM preparation/training already active: PID {previous["pid"]}') if (work / 'train.jsonl').exists(): raise FileExistsError('An existing training run requires an explicit resume, not a fresh launch') verification = json.loads((ROOT / 'output/rfm_mix50_smoke/verification.json').read_text()) if not verification['passed']: raise RuntimeError('The RFM smoke verification has not passed') files = [args.config, 'scripts/train_rfm.py', 'datasets/rfm_data.py', 'diffusion/rectified_flow.py', 'diffusion/model/nets/PixArt.py', 'diffusion/model/nets/PixArt_blocks.py', 'diffusion/model/builder.py', 'diffusion/utils/rfm_checkpoint.py', 'scripts/preparation/cache_synthetic_dataset.py', 'scripts/preparation/encode_image_latents.py', 'diffusion/model/t5.py', 'requirements.txt'] hashes = {} for name in files: path = Path(name) hashes[name] = hashlib.sha256(path.read_bytes()).hexdigest() relative = path.resolve().relative_to(ROOT) if path.resolve().is_relative_to(ROOT) else Path('config.py') destination = preparation / 'source_snapshot' / relative destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, destination) (preparation / 'source_sha256.json').write_text(json.dumps(hashes, indent=2)) shutil.copy2('output/rfm_mix50_smoke/verification.json', preparation / 'smoke_verification.json') (work / 'config.json').write_text(json.dumps(config, indent=2)) environment = dict(os.environ, OMP_NUM_THREADS='4', HF_HUB_OFFLINE='1', PYTHONUNBUFFERED='1', PYTHONPATH='output/training_dependencies:output/t5_dependencies:.') command = [sys.executable, '-u', 'scripts/train_rfm.py', args.config, '--controller', *overrides] with (preparation / 'controller.log').open('a') as log: process = subprocess.Popen(command, cwd=ROOT, env=environment, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) launch = dict(pid=process.pid, command=command, config=args.config, started_at=datetime.now(timezone.utc).isoformat()) (preparation / 'controller.json').write_text(json.dumps(launch, indent=2)) print(json.dumps(launch, indent=2)) return
lock = (preparation / 'controller.lock').open('w') fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) children = [] completed_sources = [] gpu_ids = list(range(config['world_size'])) if gpu_ids != [0, 1, 2, 3] or config['batch_size'] != 8: raise ValueError('This launcher is configured for four GPUs, eight samples per GPU') try: publish_status(preparation, 'preflight', target_steps=config['max_train_steps'], gpu_ids=gpu_ids) required = shutil.disk_usage(work).free if required < 350 * 2**30: raise RuntimeError('Need at least 350 GiB free for full caches and retained checkpoints') for source, cache, expected in zip(config['source_datasets'], config['data_roots'], config['source_counts']): source, cache = Path(source), Path(cache) cache.mkdir(parents=True, exist_ok=True) # These immutable NPZ records were encoded with the identical VAE/T5 settings. pilot_name = 'localized_narratives' if 'localized_narratives' in source.name else 'flux1_dev' pilot = Path('output/rfm_mix50_smoke/cache') / pilot_name settings = json.loads((pilot / 'cache_settings.json').read_text()) if settings['source'] != str(source.resolve()): raise ValueError('Pilot cache source mismatch') if hashlib.sha256((source / 'metadata.jsonl').read_bytes()).hexdigest() != settings['source_metadata_sha256']: raise ValueError('Source metadata changed since smoke test') for subfolder in ('latents', 't5_embeddings'): (cache / subfolder).mkdir(exist_ok=True) for existing in (pilot / subfolder).glob('*.npz'): destination = cache / subfolder / existing.name if not destination.exists(): os.link(existing, destination) children = [] for gpu in gpu_ids: command = [sys.executable, '-u', 'scripts/preparation/cache_synthetic_dataset.py', '--source', str(source), '--output', str(cache), '--shards', '4', '--shard', str(gpu), '--batch-size', '32'] with (preparation / f'cache-{source.name}-{gpu}.log').open('a') as log: child = subprocess.Popen(command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT) children.append(child) while True: progress = [] for gpu, child in zip(gpu_ids, children): path = cache / f'progress-{gpu}.json' try: row = json.loads(path.read_text()) if path.exists() else {} except json.JSONDecodeError: row = {} # Worker progress files are informational and may be mid-write. progress.append(dict(gpu=gpu, pid=child.pid, returncode=child.poll(), **row)) publish_status(preparation, 'caching', source=str(source), cache=str(cache), source_images=expected, completed_sources=completed_sources, workers=progress, training_started=False) if any(child.poll() not in (None, 0) for child in children): raise RuntimeError(f'Cache worker failed for {source}; inspect preparation/cache-*.log') if all(child.poll() == 0 for child in children): break time.sleep(10) subprocess.run([sys.executable, 'scripts/preparation/cache_synthetic_dataset.py', '--source', str(source), '--output', str(cache), '--shards', '4', '--finalize'], check=True) summary = json.loads((cache / 'summary.json').read_text()) if not summary['complete'] or summary['images'] != expected: raise RuntimeError('Finalized cache count mismatch') completed_sources.append(dict(source=str(source), cache=str(cache), images=expected)) hashes = json.loads((preparation / 'source_sha256.json').read_text()) for name, expected_hash in hashes.items(): if hashlib.sha256(Path(name).read_bytes()).hexdigest() != expected_hash: raise RuntimeError(f'{name} changed during cache preparation; training was not started') command = [sys.executable, '-u', '-m', 'torch.distributed.run', '--standalone', '--nproc_per_node=4', 'scripts/train_rfm.py', args.config, *overrides] with (work / 'console.log').open('a') as log: trainer = subprocess.Popen(command, env=dict(os.environ, CUDA_VISIBLE_DEVICES='0,1,2,3'), stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT) children = [trainer] launch = dict(pid=trainer.pid, command=command, started_at=datetime.now(timezone.utc).isoformat(), source_sha256=hashes, completed_sources=completed_sources) (work / 'launch.json').write_text(json.dumps(launch, indent=2)) (work / 'train.pid').write_text(str(trainer.pid) + '\n') while True: metrics = work / 'train.jsonl' latest = None if metrics.exists(): lines = metrics.read_text().splitlines() if lines: try: latest = json.loads(lines[-1]) except json.JSONDecodeError: latest = json.loads(lines[-2]) if len(lines) > 1 else None validations = sorted((work / 'validation').glob('update-*/sampler.json')) publish_status(preparation, 'training_running' if latest else 'training_starting', trainer_pid=trainer.pid, latest_metrics=latest, latest_validation=str(validations[-1]) if validations else None, completed_sources=completed_sources, training_started=bool(latest)) result = trainer.poll() if result is not None: if result or not (work / 'completed.json').exists(): raise RuntimeError(f'RFM trainer exited with status {result}; inspect console.log') publish_status(preparation, 'completed', trainer_pid=trainer.pid, progress=json.loads((work / 'completed.json').read_text())) break time.sleep(10) except BaseException as error: for child in children: if child.poll() is None: child.terminate() for child in children: try: child.wait(timeout=20) except subprocess.TimeoutExpired: child.kill() publish_status(preparation, 'failed', error=str(error), completed_sources=completed_sources) raise
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('config', nargs='?', default='configs/rfm.py') mode = parser.add_mutually_exclusive_group() mode.add_argument('--launch', action='store_true', help='Prepare caches and launch fresh training in the background') mode.add_argument('--controller', action='store_true', help=argparse.SUPPRESS) parser.add_argument('--resume') parser.add_argument('--work-dir') parser.add_argument('--max-train-steps', type=int) parser.add_argument('--validate-every-updates', type=int) parser.add_argument('--save-every-updates', type=int) args = parser.parse_args() if args.launch or args.controller: if any(key in os.environ for key in ('RANK', 'LOCAL_RANK', 'WORLD_SIZE')): parser.error('Launch mode must run outside torchrun') if args.resume: parser.error('Launch mode starts fresh training; use torchrun with --resume to continue a checkpoint') os.chdir(ROOT) elif not all(key in os.environ for key in ('RANK', 'LOCAL_RANK', 'WORLD_SIZE')): parser.error('Use torchrun for direct training, or --launch for background preparation and training') config = dict(runpy.run_path(args.config)['config']) for key in ('work_dir', 'max_train_steps', 'validate_every_updates', 'save_every_updates'): if getattr(args, key) is not None: config[key] = getattr(args, key) required = dict(prediction_type='flow_velocity', path='linear', time_sampling='uniform_continuous', time_embedding='999*(1-t)', loss='unweighted_mse', out_channels=4, head_initialization='zero', qk_norm='rms_norm', mixed_precision='bf16', grad_checkpointing=False, accumulation_steps=1, source_weights='raw', source_weights_per_batch=[.5, .5]) if any(config.get(key) != value for key, value in required.items()): raise ValueError('Unsupported RFM numerical/architecture configuration') for key in ('max_train_steps', 'save_every_updates', 'validate_every_updates', 'log_every_updates', 'warmup_updates', 'dataloader_workers', 'prefetch_factor'): if config[key] < 1: raise ValueError(f'{key} must be positive') if args.launch or args.controller: if config['world_size'] != 4 or config['batch_size'] != 8: parser.error('Launch mode requires four GPUs and eight samples per GPU') launch_training(args, config) return rank, world = int(os.environ['RANK']), int(os.environ['WORLD_SIZE']) local = int(os.environ['LOCAL_RANK']) if world != config['world_size']: raise ValueError('World size differs from configuration') torch.cuda.set_device(local) device = torch.device('cuda', local) dist.init_process_group('nccl', device_id=device, timeout=timedelta(minutes=30)) torch.set_num_threads(4) random.seed(config['seed'] + rank) np.random.seed(config['seed'] + rank) torch.manual_seed(config['seed'] + rank) torch.backends.cuda.matmul.allow_tf32 = True work = Path(config['work_dir']) if rank == 0: work.mkdir(parents=True, exist_ok=True) if (work / 'train.jsonl').exists(): raise FileExistsError('Use a fresh work directory for each launch, including resume verification') (work / 'config.json').write_text(json.dumps(config, indent=2)) dist.barrier()
records, lengths, hashes = [], [], {} if any(len(config[key]) != 2 for key in ('data_roots', 'source_datasets', 'source_counts')): raise ValueError('Exactly two cache roots, original sources and expected counts are required') for name, source, expected in zip(config['data_roots'], config['source_datasets'], config['source_counts']): root = Path(name) manifest = root / 'training_metadata.jsonl' content = manifest.read_bytes() hashes[str(manifest)] = hashlib.sha256(content).hexdigest() rows = [json.loads(line) for line in content.splitlines()] settings = json.loads((root / 'cache_settings.json').read_text()) source_hash = hashlib.sha256((Path(source) / 'metadata.jsonl').read_bytes()).hexdigest() if settings['source'] != str(Path(source).resolve()) or settings['source_metadata_sha256'] != source_hash: raise ValueError('Cached source provenance mismatch') if settings['count'] != len(rows) or len(rows) != expected: raise ValueError(f'Unexpected cache count for {root}: {len(rows)} != {expected}') if settings['latent_scaled'] or settings['scaling_factor'] != .18215 or settings['text_preprocessing']: raise ValueError('Unexpected cache preprocessing') if len({row['file_name'] for row in rows}) != len(rows): raise ValueError('Duplicate cache records') if any(not (root / row[key]).is_file() for row in rows for key in ('latent_file', 't5_file')): raise FileNotFoundError('Incomplete cache') records.extend((root, row) for row in rows) lengths.append(len(rows)) if len(lengths) != 2: raise ValueError('Exactly two datasets are required') text_path = Path(config['conditioning_cache']) hashes[str(text_path)] = hashlib.sha256(text_path.read_bytes()).hexdigest() text = torch.load(text_path, map_location='cpu', weights_only=True) if text['seeds'] != config['validation_seeds'] or len(text['prompts']) != 4: raise ValueError('Validation text/seeds mismatch') empty = text['empty'].to(device, dtype=torch.bfloat16) empty_mask = text['empty_mask'].to(device, dtype=torch.bool)
model = build_model(config['model'], input_size=64, pred_sigma=False, model_max_length=120, class_dropout_prob=0., qk_norm='rms_norm', use_grad_checkpoint=False, lewei_scale=1.).float() # The approved converted epsilon checkpoint already strictly maps the original RAW. initial = torch.load(config['init_checkpoint'], map_location='cpu', weights_only=False, mmap=True) provenance = initial['import_provenance'] if (provenance['source_weights'] != 'raw' or provenance['source_sha256'] != config['source_checkpoint_sha256'] or provenance['conditioning_sha256'] != hashes[str(text_path)] or initial['metadata']['prediction_type'] != 'epsilon'): raise ValueError('Initialization provenance mismatch') original = Path(config['source_model']) / 'transformer' / 'diffusion_pytorch_model.safetensors' with original.open('rb') as handle: source_digest = hashlib.file_digest(handle, 'sha256').hexdigest() if source_digest != config['source_checkpoint_sha256']: raise ValueError('Original RAW checkpoint changed') state = dict(initial['state_dict']) reset = ['final_layer.linear.weight', 'final_layer.linear.bias'] for key in reset: state[key] = torch.zeros_like(model.state_dict()[key]) model.load_state_dict(state, strict=True) if not torch.equal(model.y_embedder.y_embedding, empty[0, 0].cpu().float()): raise ValueError('Null conditioning differs from initialization') if rank == 0: matched = [key for key in model.state_dict() if key not in reset] if not all(torch.equal(model.state_dict()[key], initial['state_dict'][key]) for key in matched): raise AssertionError('Backbone transfer was not exact') (work / 'initialization.json').write_text(json.dumps(dict(source=str(original), source_sha256=config['source_checkpoint_sha256'], source_weights='raw', preserved_tensors=len(matched), zero_initialized=reset, out_channels=4, optimizer_reset=True, ema_initialization='copy_migrated_raw'), indent=2)) del state, initial model.to(device).train() if any(getattr(module, 'grad_checkpointing', False) for module in model.modules()): raise AssertionError('Gradient checkpointing must be disabled') ema = deepcopy(model).eval().requires_grad_(False) optimizer = torch.optim.AdamW(model.parameters(), lr=config['learning_rate'], betas=config['betas'], eps=config['adam_eps'], weight_decay=config['weight_decay'], fused=True) scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda step: min((step + 1) / config['warmup_updates'], 1.)) metadata = dict(format_version='rfm_v1', prediction_type='flow_velocity', path='linear', time_embedding=config['time_embedding'], vae_scaling_factor=.18215, training_config=config, manifest_hashes=hashes) progress = dict(micro_step=0, optimizer_step=0, consumed_batches=0, samples_seen=0, accumulation_steps=1) saved_rng = None if args.resume: checkpoint = torch.load(args.resume, map_location='cpu', weights_only=False, mmap=True) old = checkpoint['metadata'] if old['format_version'] != 'rfm_v1' or old['manifest_hashes'] != hashes: raise ValueError('Resume format or dataset mismatch') mutable = {'work_dir', 'max_train_steps', 'save_every_updates', 'validate_every_updates', 'log_every_updates'} if any(old['training_config'].get(key) != config.get(key) for key in set(old['training_config']) | set(config) if key not in mutable): raise ValueError('Resume changed training semantics') progress = dict(checkpoint['progress']) if (len(checkpoint['rank_rng']) != world or progress['optimizer_step'] != progress['consumed_batches'] or progress['micro_step'] != progress['optimizer_step'] or progress['samples_seen'] != progress['optimizer_step'] * world * config['batch_size']): raise ValueError('Invalid resume cursor') model.load_state_dict(checkpoint['state_dict'], strict=True) ema.load_state_dict(checkpoint['state_dict_ema'], strict=True) optimizer.load_state_dict(checkpoint['optimizer']) scheduler.load_state_dict(checkpoint['scheduler']) saved_rng = checkpoint['rank_rng'][rank] if rank == 0: (work / 'resume.json').write_text(json.dumps(dict(checkpoint=args.resume, **progress), indent=2)) del checkpoint if config['max_train_steps'] <= progress['optimizer_step']: raise ValueError('Training budget must extend beyond the resume step') model = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, gradient_as_bucket_view=True, static_graph=True) sampler = BalancedFlowSampler(lengths, config['batch_size'], world, rank, config['seed'], progress['consumed_batches'], config['max_train_steps']) loader = DataLoader(CachedDataset(records), batch_sampler=sampler, num_workers=config['dataloader_workers'], prefetch_factor=config['prefetch_factor'], persistent_workers=True, pin_memory=True, generator=torch.Generator().manual_seed(config['seed'] + rank), multiprocessing_context='spawn') vae = None if rank == 0: from diffusers import AutoencoderKL vae = AutoencoderKL.from_pretrained(config['vae_path'], local_files_only=True).float().to(device).eval().requires_grad_(False) if not np.isclose(vae.config.scaling_factor, .18215): raise ValueError('VAE scale mismatch') (work / 'dataset.json').write_text(json.dumps(dict(counts=lengths, source_fraction=[.5, .5], batch_per_gpu=config['batch_size'], source_per_gpu=[config['batch_size']//2]*2, global_batch=world*config['batch_size'], sampler='independent_shuffled_source_cycles', cache_loading='dataloader_prefetch'), indent=2)) dist.barrier() # Setup/validation must not consume the training RNG stream, including on resume. if saved_rng is not None: restore_rng(saved_rng) else: random.seed(config['seed'] + rank) np.random.seed(config['seed'] + rank) torch.manual_seed(config['seed'] + rank) torch.cuda.reset_peak_memory_stats() for mean, std, caption, mask in loader: started = time.monotonic() mean, std, caption, mask = [value.to(device, non_blocking=True) for value in (mean, std, caption, mask)] caption, mask = drop_to_empty_text(caption, mask, empty, empty_mask, config['class_dropout_prob']) clean = (mean + std * torch.randn_like(mean)) * .18215 noise = torch.randn_like(clean) flow_time = torch.rand(len(clean), device=device) optimizer.zero_grad(set_to_none=True) with torch.autocast('cuda', dtype=torch.bfloat16): per_sample = flow_matching_loss(model, clean, noise, flow_time, caption, mask) loss = per_sample.mean() loss.backward() norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config['max_grad_norm'], foreach=True) finite = (torch.isfinite(loss) & torch.isfinite(norm)).int() dist.all_reduce(finite, op=dist.ReduceOp.MIN) if not finite.item(): raise FloatingPointError('Nonfinite RFM loss or gradients') used_lr = optimizer.param_groups[0]['lr'] optimizer.step() scheduler.step() update_ema(ema, model.module, config['ema_decay']) for key in ('optimizer_step', 'micro_step', 'consumed_batches'): progress[key] += 1 progress['samples_seen'] += world * config['batch_size'] step = progress['optimizer_step'] if step % config['log_every_updates'] == 0 or step == config['max_train_steps']: values = torch.stack([loss.detach(), norm.detach()]) dist.all_reduce(values) bins = torch.zeros(5, 2, device=device) for index in range(5): selected = (flow_time >= index/5) & (flow_time < (index+1)/5) bins[index, 0] = per_sample.detach()[selected].sum() bins[index, 1] = selected.sum() dist.all_reduce(bins) memory = [None] * world dist.all_gather_object(memory, torch.cuda.max_memory_allocated() / 2**30) if rank == 0: report = dict(step=step, loss=float(values[0]/world), grad_norm=float(values[1]/world), learning_rate=used_lr, samples_seen=progress['samples_seen'], peak_gpu_gib_per_rank=memory, seconds_per_step=time.monotonic()-started, source_counts_per_update=[world*config['batch_size']//2]*2, time_bins_sum_count=bins.tolist()) with (work / 'train.jsonl').open('a') as handle: handle.write(json.dumps(report) + '\n') print(json.dumps(report), flush=True) if step % config['validate_every_updates'] == 0 or step == config['max_train_steps']: state = rng_state() dist.barrier() if rank == 0: print(f'Validation {step}: {validate(model.module, ema, vae, text, config, step, device)}', flush=True) dist.barrier() restore_rng(state) if step % config['save_every_updates'] == 0 or step == config['max_train_steps']: states = [None] * world dist.all_gather_object(states, rng_state()) if rank == 0: path = work / 'checkpoints' / f'update-{step:06d}.pth' save_training_checkpoint(path, model.module, ema, optimizer, scheduler, metadata, progress, states) (work / 'latest_checkpoint.txt').write_text(str(path) + '\n') print(f'Saved {path}', flush=True) dist.barrier() if rank == 0: (work / 'completed.json').write_text(json.dumps(progress, indent=2)) dist.destroy_process_group()
if __name__ == '__main__': main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Run the original RAW/EMA validation from an existing RFM checkpoint."""import argparsefrom copy import deepcopyimport hashlibimport jsonfrom pathlib import Pathimport runpy
import torchfrom diffusers import AutoencoderKL
from diffusion.model.builder import build_modelfrom scripts.train_rfm import validate
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--config', help='Python config with resource paths and validation sampling settings') parser.add_argument('--checkpoint', required=True) parser.add_argument('--output', required=True) parser.add_argument('--conditioning-cache') parser.add_argument('--vae-path') args = parser.parse_args() output = Path(args.output) if output.exists() and any(output.iterdir()): raise FileExistsError(f'Use an empty output directory: {output}') checkpoint = torch.load(args.checkpoint, map_location='cpu', weights_only=False, mmap=True) metadata = checkpoint['metadata'] for key, expected in dict(format_version='rfm_v1', prediction_type='flow_velocity', path='linear', time_embedding='999*(1-t)', vae_scaling_factor=.18215).items(): if metadata.get(key) != expected: raise ValueError(f'Incompatible RFM checkpoint: {key}') config = dict(metadata['training_config']) conditioning_hash = metadata['manifest_hashes'][config['conditioning_cache']] if args.config: runtime = runpy.run_path(args.config)['config'] for key in ('model', 'image_size', 'prediction_type', 'path', 'time_embedding', 'out_channels', 'qk_norm'): if key in runtime and runtime[key] != config.get(key): raise ValueError(f'Config differs from checkpoint architecture/convention: {key}') for key in ('conditioning_cache', 'vae_path', 'cfg_scale', 'sampling_method', 'sampling_steps', 'sampling_atol', 'sampling_rtol'): if key in runtime: config[key] = runtime[key] config['work_dir'] = str(output) if args.conditioning_cache: config['conditioning_cache'] = args.conditioning_cache if args.vae_path: config['vae_path'] = args.vae_path if hashlib.sha256(Path(config['conditioning_cache']).read_bytes()).hexdigest() != conditioning_hash: raise ValueError('Conditioning cache differs from the original training cache') text = torch.load(config['conditioning_cache'], map_location='cpu', weights_only=True) if text['seeds'] != config['validation_seeds'] or len(text['prompts']) != 4: raise ValueError('Conditioning prompts/seeds do not match the training configuration') torch.set_num_threads(4) torch.backends.cuda.matmul.allow_tf32 = True model = build_model(config['model'], input_size=64, pred_sigma=False, model_max_length=120, class_dropout_prob=0., qk_norm=config['qk_norm'], use_grad_checkpoint=False, lewei_scale=1.).float() model.load_state_dict(checkpoint['state_dict'], strict=True) ema = deepcopy(model) ema.load_state_dict(checkpoint['state_dict_ema'], strict=True) for network in (model, ema): if not torch.equal(network.y_embedder.y_embedding, text['empty'][0, 0].float()): raise ValueError('Unconditional embedding differs from the training cache') network.cuda().eval().requires_grad_(False) vae = AutoencoderKL.from_pretrained(config['vae_path'], local_files_only=True) vae = vae.cuda().float().eval().requires_grad_(False) if abs(vae.config.scaling_factor - .18215) > 1e-6: raise ValueError('Unexpected VAE scaling factor') step = checkpoint['progress']['optimizer_step'] del checkpoint report = validate(model, ema, vae, text, config, step, torch.device('cuda')) (output / 'validation_config.json').write_text(json.dumps(config, indent=2) + '\n') print(json.dumps(report, indent=2))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import jsonimport osfrom pathlib import Pathimport subprocessimport sys
import pytest
@pytest.fixturedef launcher_environment(tmp_path): record = tmp_path / 'command.json' python = tmp_path / 'python with spaces' python.write_text(f'#!{sys.executable}\n' + '''import jsonimport osfrom pathlib import Pathimport sysif sys.argv[1] == '-': sys.argv = sys.argv[1:] exec(compile(sys.stdin.read(), '<launcher config reader>', 'exec'))else: Path(os.environ['RFM_COMMAND_RECORD']).write_text(json.dumps(dict( args=sys.argv[1:], cwd=os.getcwd(), cuda=os.environ.get('CUDA_VISIBLE_DEVICES'))))''') python.chmod(0o755) config = tmp_path / 'config with spaces.py' config.write_text("config = dict(world_size=3)\n") environment = dict(os.environ, PYTHON_BIN=str(python), RFM_COMMAND_RECORD=str(record), CUDA_VISIBLE_DEVICES='2,3,5') return config, record, environment
@pytest.mark.parametrize('mode', ['train', 'validate', 'inference'])def test_launcher_dispatches_with_config_and_preserves_arguments(tmp_path, launcher_environment, mode): config, record, environment = launcher_environment root = Path(__file__).resolve().parents[1] extras = ['--work-dir', 'output/with spaces'] if mode == 'train' else [ '--checkpoint', 'weights/model with spaces.pth', '--output', 'output/with spaces'] if mode == 'inference': extras += ['--prompts', 'prompts with spaces.json', '--weights', 'ema'] result = subprocess.run(['bash', str(root / 'run.sh'), mode, str(config), *extras], cwd=tmp_path, env=environment, capture_output=True, text=True) assert result.returncode == 0, result.stderr command = json.loads(record.read_text()) if mode == 'train': expected = ['-m', 'torch.distributed.run', '--standalone', '--nproc_per_node=3', 'scripts/train_rfm.py', str(config), *extras] else: expected = ['-m', f'scripts.{mode}_rfm', '--config', str(config), *extras] assert command['args'] == expected assert command['cwd'] == str(root) and command['cuda'] == '2,3,5'
@pytest.mark.parametrize('flag', ['--launch', '--help'])def test_launch_and_help_do_not_start_torchrun(tmp_path, launcher_environment, flag): config, record, environment = launcher_environment root = Path(__file__).resolve().parents[1] result = subprocess.run(['bash', str(root / 'run.sh'), 'train', str(config), flag], cwd=tmp_path, env=environment, capture_output=True, text=True) assert result.returncode == 0, result.stderr assert json.loads(record.read_text())['args'] == ['-m', 'scripts.train_rfm', str(config), flag]
@pytest.mark.parametrize('invalid', ['action', 'config', 'world_size'])def test_invalid_launcher_inputs_do_not_start_a_process(tmp_path, launcher_environment, invalid): config, record, environment = launcher_environment root = Path(__file__).resolve().parents[1] action = 'train' if invalid == 'action': action = 'unknown' elif invalid == 'config': config = tmp_path / 'missing.py' else: config.write_text('config = dict(world_size=0)\n') result = subprocess.run(['bash', str(root / 'run.sh'), action, str(config)], cwd=tmp_path, env=environment, capture_output=True, text=True) assert result.returncode != 0 assert not record.exists()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""RFM contracts: direction, loss, ODE/CFG, source balance and resume cursor."""import unittestimport torchfrom diffusion.rectified_flow import flow_matching_loss, sample_rfmfrom datasets.rfm_data import BalancedFlowSampler
class RectifiedFlowTests(unittest.TestCase): def test_path_target_time_and_gradient(self): clean = torch.randn(3, 4, 2, 2) noise = torch.randn_like(clean) time = torch.tensor([0., .37, 1.]) offset = torch.tensor(.25, requires_grad=True)
def oracle(x, embedding_time, condition, mask): self.assertTrue(torch.equal(x[0], noise[0])) self.assertTrue(torch.equal(x[-1], clean[-1])) torch.testing.assert_close(embedding_time, 999 * (1-time)) torch.testing.assert_close(x[1], .63*noise[1]+.37*clean[1]) return clean - noise + offset
loss = flow_matching_loss(oracle, clean, noise, time, None, None).mean() torch.testing.assert_close(loss, torch.tensor(.25**2)) loss.backward() torch.testing.assert_close(offset.grad, torch.tensor(.5))
def test_cfg_and_solver_direction_all_four_channels(self): noise = torch.randn(2, 4, 2, 2) condition = torch.ones(2, 1, 1, 1) empty = torch.zeros(1, 1, 1, 1) mask = torch.ones(2, 1, dtype=torch.bool)
def model(x, time, y, mask): return y.expand_as(x)
for method in ('heun', 'dopri5'): result, report = sample_rfm(model, noise, condition, mask, empty, mask[:1], cfg_scale=2., method=method, steps=4) torch.testing.assert_close(result, noise + 2, atol=2e-5, rtol=2e-5) self.assertGreater(report['nfe'], 0) if method == 'heun': self.assertEqual(report['nfe'], 8)
def test_unequal_sources_balance_coverage_and_resume(self): lengths = [50, 77] rank_batches = [list(BalancedFlowSampler(lengths, 8, 4, rank, 43, 0, 20)) for rank in range(4)] seen = [set(), set()] for step in range(20): for rank in range(4): batch = rank_batches[rank][step] self.assertEqual(sum(index < 50 for index in batch), 4) self.assertEqual(sum(index >= 50 for index in batch), 4) self.assertEqual(len(set(batch)), 8) seen[0].update(index for index in batch if index < 50) seen[1].update(index for index in batch if index >= 50) if step < 3: # Full global half-batches before either source's padded tail. combined = sum([rank_batches[rank][step] for rank in range(4)], []) self.assertEqual(len(set(combined)), 32) self.assertEqual(seen, [set(range(50)), set(range(50, 127))]) for rank in range(4): resumed = list(BalancedFlowSampler(lengths, 8, 4, rank, 43, 7, 20)) self.assertEqual(resumed, rank_batches[rank][7:])
if __name__ == '__main__': unittest.main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980from copy import deepcopyimport hashlibimport random
import numpy as npimport pytestimport torch
from diffusion.utils.rfm_checkpoint import rng_state, restore_rng, update_ema, save_training_checkpointfrom diffusion.utils.theta_import import make_initial_metadata
def test_checkpoint_restores_the_next_update_and_all_random_streams(tmp_path): model = torch.nn.Linear(2, 2) model.register_buffer('updates', torch.tensor(0)) ema = deepcopy(model).requires_grad_(False) optimizer = torch.optim.AdamW(model.parameters(), lr=.01) scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda step: 1 / (step + 1)) loss = model(torch.randn(3, 2)).square().mean() loss.backward() optimizer.step() scheduler.step() model.updates.add_(1) update_ema(ema, model, .9) progress = dict(micro_step=1, optimizer_step=1, consumed_batches=1, accumulation_steps=1, samples_seen=3) metadata = dict(format_version='rfm_v1', prediction_type='flow_velocity', path='linear', time_embedding='999*(1-t)', vae_scaling_factor=.18215) path = tmp_path / 'checkpoints/update-000001.pth' save_training_checkpoint(path, model, ema, optimizer, scheduler, metadata, progress, [rng_state()]) checkpoint = torch.load(path, map_location='cpu', weights_only=False) assert checkpoint['progress'] == progress assert checkpoint['metadata'] == dict(metadata, optimizer_step=1, samples_seen=3) assert not path.with_suffix('.tmp').exists()
results = [] for resumed in (False, True): if resumed: model.load_state_dict(checkpoint['state_dict']) ema.load_state_dict(checkpoint['state_dict_ema']) optimizer.load_state_dict(checkpoint['optimizer']) scheduler.load_state_dict(checkpoint['scheduler']) restore_rng(checkpoint['rank_rng'][0]) inputs = torch.randn(3, 2) * (random.random() + np.random.rand()) optimizer.zero_grad(set_to_none=True) model(inputs).square().mean().backward() optimizer.step() scheduler.step() model.updates.add_(1) previous_ema = ema.weight.detach().clone() update_ema(ema, model, .9) torch.testing.assert_close(ema.weight, previous_ema * .9 + model.weight * .1) assert torch.equal(ema.updates, model.updates) results.append(deepcopy(dict(model=model.state_dict(), ema=ema.state_dict(), optimizer=optimizer.state_dict(), scheduler=scheduler.state_dict()))) for key in ('model', 'ema'): for name, value in results[0][key].items(): assert torch.equal(value, results[1][key][name]) for index, state in results[0]['optimizer']['state'].items(): for name, value in state.items(): assert torch.equal(value, results[1]['optimizer']['state'][index][name]) assert results[0]['scheduler'] == results[1]['scheduler']
def test_checkpoint_rejects_incomplete_updates(tmp_path): with pytest.raises(ValueError, match='optimizer update boundary'): save_training_checkpoint(tmp_path / 'incomplete.pth', None, None, None, None, {}, dict(micro_step=1, accumulation_steps=2), []) assert not (tmp_path / 'incomplete.pth').exists()
def test_initial_metadata_without_git_history_preserves_source_schedule(tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) config = dict(prediction_type='epsilon', source_model='assets/source_model', source_weights='raw') metadata = make_initial_metadata(config, .18215, torch.nn.Linear(2, 2)) assert metadata['prediction_type'] == 'epsilon' assert metadata['validation_prediction_path'] == 'epsilon_to_x0' assert metadata['git_commit'] is None assert metadata['schedule'] == dict(name='linear', steps=1000, beta_sha256=hashlib.sha256(np.linspace(.0001, .02, 1000, dtype=np.float64).tobytes()).hexdigest()).gitattributes+8
.gitignoreAdded+12
LICENSEAdded+201
README.mdAdded+344
checkpoints/update-100000.pthAdded+3
configs/rfm.pyAdded+29
datasets/__init__.pyAdded+1
datasets/rfm_data.pyAdded+85
diffusion/__init__.pyAdded+1
diffusion/model/__init__.pyAdded+12
diffusion/model/builder.pyAdded+16
diffusion/model/nets/PixArt.pyAdded+277
diffusion/model/nets/PixArt_blocks.pyAdded+451
diffusion/model/nets/__init__.pyAdded+1
diffusion/model/t5.pyAdded+239
diffusion/model/utils.pyAdded+510
diffusion/rectified_flow.pyAdded+62
diffusion/utils/__init__.pyAdded
diffusion/utils/dist_utils.pyAdded+303
diffusion/utils/logger.pyAdded+94
diffusion/utils/rfm_checkpoint.pyAdded+46
diffusion/utils/theta_import.pyAdded+77
examples/inference_prompts.jsonAdded+22
examples/validation_prompts.jsonAdded+18
output/run-validation-100000/validation/update-100000/ema-0.pngAdded
Large File Pointer Details
- SHA256: 815663c51db574808167926d9c1e4efe410fbc4e1942c1d2fb736de385902e4e
- Pointer size: 131 Bytes
- Size of remote file: 371 kB
output/run-validation-100000/validation/update-100000/ema-1.pngAdded
Large File Pointer Details
- SHA256: f08a7f8149292e1232fd923109311288158e8640c6d6d3201c53fb48e4a05233
- Pointer size: 131 Bytes
- Size of remote file: 345 kB
output/run-validation-100000/validation/update-100000/ema-2.pngAdded
Large File Pointer Details
- SHA256: 1657493f7dda22f1f991c85fdfd04c6d53c15580aaa384bfcf386b8eea430b3f
- Pointer size: 131 Bytes
- Size of remote file: 363 kB
output/run-validation-100000/validation/update-100000/ema-3.pngAdded
Large File Pointer Details
- SHA256: 0634e4fa30754362a3477118d2cf6ac8a326eef02e55f33e0a56681c3b4e2e54
- Pointer size: 131 Bytes
- Size of remote file: 304 kB
output/run-validation-100000/validation/update-100000/ema.ptAdded+3
output/run-validation-100000/validation/update-100000/prompts.jsonAdded+6
output/run-validation-100000/validation/update-100000/raw-0.pngAdded
Large File Pointer Details
- SHA256: 2cff367bc66984d324e42c17d0ea0b0ba59675e4f6b71ce569b28b977166452f
- Pointer size: 131 Bytes
- Size of remote file: 348 kB
output/run-validation-100000/validation/update-100000/raw-1.pngAdded
Large File Pointer Details
- SHA256: 07e357768e0af9f5d71141a3bc877884218ba0777931eaa3177716c75e7a8d3f
- Pointer size: 131 Bytes
- Size of remote file: 370 kB
output/run-validation-100000/validation/update-100000/raw-2.pngAdded
Large File Pointer Details
- SHA256: c048b3b2bf6d1695f00827e70b6ced97e1a45f09a16ca8588b57e6f3d617eb5b
- Pointer size: 131 Bytes
- Size of remote file: 358 kB
output/run-validation-100000/validation/update-100000/raw-3.pngAdded
Large File Pointer Details
- SHA256: bf0966afb72fe6f849d6866486ee412cc771a10526310e77a8eb3c4c8d32255a
- Pointer size: 131 Bytes
- Size of remote file: 299 kB
output/run-validation-100000/validation/update-100000/raw.ptAdded+3
output/run-validation-100000/validation/update-100000/sampler.jsonAdded+24
output/run-validation-100000/validation_config.jsonAdded+69
requirements.txtAdded+22
run.shAdded+74
scripts/inference_rfm.pyAdded+146
scripts/preparation/__init__.pyAdded+1
scripts/preparation/cache_synthetic_dataset.pyAdded+152
scripts/preparation/encode_image_latents.pyAdded+219
scripts/preparation/prepare_theta_v.pyAdded+83
scripts/preparation/verify_rfm_smoke.pyAdded+176
scripts/train_rfm.pyAdded+490
scripts/validate_rfm.pyAdded+79
tests/test_bash_launcher.pyAdded+78
tests/test_rectified_flow.pyAdded+66
tests/test_rfm_checkpoint.pyAdded+80