-
Notifications
You must be signed in to change notification settings - Fork 7.4k
[TPU] TorchTPU backend integration - eager / torch.compile / tp #14039
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JingyaHuang
wants to merge
49
commits into
huggingface:main
Choose a base branch
from
JingyaHuang:add-torchtpu-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
49 commits
Select commit
Hold shift + click to select a range
38007b4
feat: add torchtpu
JingyaHuang 8ed15f9
feat:draft TorchTPU support
JingyaHuang e343c0a
fix: wan overflow issue + compile mode error on sdxl
JingyaHuang 84b4049
doc: enhance with TorchTPU doc
JingyaHuang bb3ec1e
doc: enhance with TorchTPU doc
JingyaHuang 339be41
Merge branch 'main' into add-torchtpu-support
JingyaHuang 92193a7
Merge branch 'main' into add-torchtpu-support
JingyaHuang 1a2369b
Merge branch 'main' into add-torchtpu-support
JingyaHuang 66254b4
style: remove unused imports flagged by ruff
JingyaHuang 7c241be
docs: remove Debug Eager and Fused Eager sections from tpu.md
JingyaHuang 05d56d5
Merge branch 'main' into add-torchtpu-support
JingyaHuang b7a8c0b
Merge branch 'main' into add-torchtpu-support
JingyaHuang b0c5595
Merge branch 'huggingface:main' into add-torchtpu-support
JingyaHuang 7c3df6c
Merge branch 'main' into add-torchtpu-support
JingyaHuang 7c1e379
feat: add TP for TPU
JingyaHuang f944c48
style: fix import sorting in TPU test scripts
JingyaHuang 82d20ab
style: ruff format TPU test scripts
JingyaHuang f6c17d2
fix: style
e8fe48c
fix: test for native 4 devices
JingyaHuang 9b62254
fix: propagate TPU device fixes to Flux/Flux2/Wan-family copies; regi…
JingyaHuang 744fa95
tests: cleanup
JingyaHuang bfc7d17
fix: fix compile mode
JingyaHuang 10d4ad1
Update docs/source/en/optimization/tpu.md
JingyaHuang a999a3d
Update docs/source/en/optimization/tpu.md
JingyaHuang cb2dcf3
Update docs/source/en/optimization/tpu.md
JingyaHuang 9f11d1e
Merge branch 'main' into add-torchtpu-support
JingyaHuang c48d41c
Update docs/source/en/optimization/tpu.md
JingyaHuang aa70a45
Update docs/source/en/optimization/tpu.md
JingyaHuang 6cb37d2
Update docs/source/en/optimization/tpu.md
JingyaHuang 3e06f71
Update docs/source/en/optimization/tpu.md
JingyaHuang 09d5ce2
Update docs/source/en/optimization/tpu.md
JingyaHuang 7b46e08
Update docs/source/en/optimization/tpu.md
JingyaHuang e82e795
Update docs/source/en/optimization/tpu.md
JingyaHuang d2bf529
Update docs/source/en/optimization/tpu.md
JingyaHuang 22d595a
test: remove flux2 e2e test
JingyaHuang 042a88a
doc: apply suggestions
JingyaHuang c6a4c80
doc: apply suggestions
JingyaHuang c82fce7
Merge branch 'add-torchtpu-support' of github.com:JingyaHuang/diffuse…
JingyaHuang cb314bd
review: remove monkey patch
JingyaHuang bf8934f
review: revert neuron-specific changes in the tests
JingyaHuang c35e23a
review: apply suggestions
JingyaHuang 419d657
Merge branch 'main' of https://github.com/huggingface/diffusers into …
JingyaHuang a2a770a
Update docs/source/en/optimization/tpu.md
JingyaHuang 7f73095
Merge branch 'main' into add-torchtpu-support
JingyaHuang 406ac74
doc: add tpu to tp doc
JingyaHuang 67a84d2
Merge branch 'add-torchtpu-support' of github.com:JingyaHuang/diffuse…
JingyaHuang a638798
Merge branch 'main' into add-torchtpu-support
JingyaHuang 2bf3619
review: remove unnecessary for tpu
JingyaHuang 5d6ad22
Merge branch 'main' into add-torchtpu-support
JingyaHuang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| <!--Copyright 2026 The HuggingFace Team. All rights reserved. | ||
|
|
||
| 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. | ||
| --> | ||
|
|
||
| # TorchTPU | ||
|
|
||
| [TorchTPU](https://github.com/google-pytorch/torch_tpu/) is a PyTorch backend for Google's Tensor Processing Units (TPUs), which lets you run Diffusers pipelines on Cloud TPUs (v6e, v5p, etc.) with minimal code changes. | ||
|
|
||
| Two execution modes are available: | ||
|
|
||
| | Mode | Constant | How to activate | Notes | | ||
| |---|---|---|---| | ||
| | Strict eager (default) | `EagerMode.DEFER_NEVER` | `import torch_tpu` | Operations dispatched one at a time, asynchronous | | ||
| | Compile | — | `torch.compile(module, backend="tpu")` | AOT compilation with `TpuBackend` | | ||
|
|
||
| Follow the [TorchTPU installation guide](https://github.com/google-pytorch/torch_tpu/). After installation, | ||
| `import torch_tpu` registers the `"tpu"` device automatically. | ||
|
|
||
| ## Eager mode | ||
|
|
||
| ```python | ||
| import gc | ||
| import torch | ||
| import torch_tpu # noqa: F401 | ||
|
|
||
| from diffusers import FluxPipeline | ||
|
|
||
| pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16) | ||
|
|
||
| # 1. Encode on TPU. | ||
| pipe.text_encoder.to("tpu") | ||
| pipe.text_encoder_2.to("tpu") | ||
| with torch.no_grad(): | ||
| prompt_embeds, pooled_prompt_embeds, _ = pipe.encode_prompt( | ||
| prompt="a golden retriever surfing a wave, photorealistic", | ||
| prompt_2="a golden retriever surfing a wave, photorealistic", | ||
| device=torch.device("tpu"), | ||
| max_sequence_length=512, | ||
| ) | ||
|
|
||
| # 2. Free the text encoders — nothing below needs them. | ||
| pipe.text_encoder = None | ||
| pipe.text_encoder_2 = None | ||
| gc.collect() | ||
|
|
||
| # 3. Move the transformer and VAE in, then denoise with the precomputed embeddings. | ||
| pipe.transformer.to("tpu") | ||
| pipe.vae.to("tpu") | ||
| image = pipe( | ||
| prompt_embeds=prompt_embeds, | ||
| pooled_prompt_embeds=pooled_prompt_embeds, | ||
| height=1024, | ||
| width=1024, | ||
| num_inference_steps=4, | ||
| guidance_scale=0.0, | ||
| ).images[0] | ||
|
|
||
| image.save("output.png") | ||
| ``` | ||
|
|
||
| If the text encoder alone is too large for a single chip(eg. FLUX.2-dev's Mistral-3-Small is ~45GB), | ||
| shard it across multiple chips with [`~diffusers.hooks.tensor_parallel.apply_tensor_parallel`], the | ||
| same mechanism [`~ModelMixin.enable_parallelism`] uses for the transformer (see [Tensor | ||
| parallelism](../training/distributed_inference#tensor-parallelism)). It only requires `model: | ||
| torch.nn.Module`, so it works directly on a `transformers.PreTrainedModel` text encoder too, not | ||
| just a diffusers `ModelMixin`. The text encoder doesn't define a `_tp_plan`, so supply one: pair | ||
| each attention/MLP projection that expands the hidden dimension (`"colwise"`) with the one that | ||
| contracts it back (`"rowwise"`), matching the `transformers` model's actual module names. | ||
|
|
||
| ## Compiled mode | ||
|
|
||
| `import torch_tpu` registers `"tpu"` as a `torch.compile` backend name (`TpuBackend` under the hood), so | ||
| components compile like any other `torch.compile` target — no diffusers-specific method needed. The first | ||
| call (warmup) is slow because it compiles; later calls with the same shapes reuse the compiled graph. | ||
|
|
||
| > [!IMPORTANT] | ||
| > TorchTPU requires **static shapes** — pass `dynamic=False`. Every time `height`, `width`, or | ||
| > `num_inference_steps` changes, the graph is recompiled from scratch. Keep these values constant | ||
| > across all calls after warmup, or run another warmup pass before changing them. | ||
|
|
||
| ```python | ||
| import torch | ||
| import torch_tpu # noqa: F401 — registers the "tpu" torch.compile backend | ||
|
|
||
| from diffusers import FluxPipeline | ||
|
|
||
| pipe = FluxPipeline.from_pretrained( | ||
| "black-forest-labs/FLUX.1-schnell", | ||
| torch_dtype=torch.bfloat16, | ||
| ) | ||
| pipe.transformer.to("tpu") | ||
| pipe.vae.to("tpu") | ||
|
|
||
| pipe.transformer = torch.compile(pipe.transformer, backend="tpu", fullgraph=True, dynamic=False) | ||
| pipe.vae = torch.compile(pipe.vae, backend="tpu", fullgraph=True, dynamic=False) | ||
|
|
||
| # Warmup — triggers static graph compilation. | ||
| with torch.no_grad(): | ||
| pipe( | ||
| prompt="warmup", | ||
| height=1024, | ||
| width=1024, | ||
| num_inference_steps=4, | ||
| guidance_scale=0.0, | ||
| ) | ||
|
|
||
| # Timed inference reuses the compiled graph. | ||
| image = pipe( | ||
| prompt="a golden retriever surfing a wave, photorealistic", | ||
| height=1024, | ||
| width=1024, | ||
| num_inference_steps=4, | ||
| guidance_scale=0.0, | ||
| ).images[0] | ||
|
|
||
| image.save("output.png") | ||
| ``` | ||
|
|
||
| ## Tensor parallelism | ||
|
|
||
| Shard a transformer too large for one chip across several with [`~ModelMixin.enable_parallelism`]. Pass a `TensorParallelConfig` with a TPU `DeviceMesh`. For general TP details, (`_tp_plan`, colwise/rowwise), see the [Tensor parallelism](../training/distributed_inference#tensor-parallelism) guide. Set `backend="tpu_dist"` and `DeviceMesh("tpu", ...)` here to enable tensor parallelism. | ||
|
|
||
| ```python | ||
| import torch | ||
| import torch.distributed as dist | ||
| import torch_tpu # noqa: F401 | ||
| from torch.distributed.device_mesh import DeviceMesh | ||
|
|
||
| from diffusers import DiffusionPipeline, TensorParallelConfig | ||
|
|
||
| dist.init_process_group(backend="tpu_dist") | ||
| tp_mesh = DeviceMesh("tpu", list(range(dist.get_world_size()))) | ||
|
|
||
| pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.2-dev", torch_dtype=torch.bfloat16) | ||
| pipe.transformer.enable_parallelism(config=TensorParallelConfig(mesh=tp_mesh)) | ||
| pipe.transformer.to("tpu") | ||
| ``` | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.