torch_tpu README

README проекта с github.com/google-pytorch/torch_tpu. Одним файлом markdown: README.md.

TorchTPU: PyTorch backend for Google Cloud TPUs

Description

This project provides a PyTorch backend for Google's Tensor Processing Units (TPUs), enabling users to run PyTorch models and operations on TPU devices. It includes custom ATen kernels for various PyTorch operations, a compilation cache for optimizing execution, and examples for distributed training and model inference.

Features

User Guide and Interactive Notebooks

A user guide is available at https://torchtpu.readthedocs.io/. The markdown sources for this documentation are available in the docs/ directory. Jupyter notebook versions of these documents are available in the docs/notebooks/ folder.

The notebooks can be opened in Colab. You will need to be running this from a TPU VM, a v6e GCE instance is easiest.

Installation

The same instructions are available in the user guide linked above.

TorchTPU's Python version support policy matches PyTorch's Release Compatibility Matrix. Currently, Python 3.11–3.15 is supported (including free-threaded 3.14t and 3.15t builds, with Python 3.15 requiring PyTorch >= 2.15). See the Python Version Support Policy for more details.

First create a Python virtual environment:

python -m venv .venv
source .venv/bin/activate

or, with uv

uv venv .venv
source .venv/bin/activate

Install via pip

Install the latest public release from PyPI (for uv, prepend uv to all pip commands):

pip install torch_tpu --extra-index-url https://download.pytorch.org/whl/cpu

Build from source

Wheels can be built via:

bazel build --config=wheel_common //ci/wheel:torch_tpu_wheel

All OSS Bazel builds default to optimized mode (-c opt) automatically via .bazelrc. Unoptimized builds (-c fastbuild, -c dbg) can degrade performance and are not used for wheel builds. If you are developing or debugging C++ code and explicitly want an unoptimized wheel, pass --//:allow_unoptimized_wheel=True:

bazel build -c dbg --config=wheel_common //ci/wheel:torch_tpu_wheel \
    --//:allow_unoptimized_wheel=True

--config=wheel_common is required, and the build fails at build time without it. The config sets --//:wheel_build=True, which routes the shared XLA/MLIR backend through the torch_version-reset transition so that pywrap factors it into a single libxla_base.so; built without the flag, every per-version common ships its own copy of the backend and the resulting wheel aborts on import torch with duplicate static registrations.

wheel_common also turns on the Remote Build Execution (RBE) remote cache and remote executor. If you do not have RBE credentials, append --config=no_rbe to strip those flags back out:

bazel build --config=wheel_common //ci/wheel:torch_tpu_wheel --config=no_rbe

The order matters here: --config=no_rbe has to come after --config=wheel_common, because the later config is the one that wins for the remote-cache and remote-executor flags they both set.

Install wheel via:

cd <path_to_repo>
python -m venv .venv; source .venv/bin/activate
# The extra-index-url provides the CPU version of torch rather than the default CUDA build.
pip install ../bazel-bin/ci/wheel/*.whl --extra-index-url https://download.pytorch.org/whl/cpu

Note that installing without --extra-index-url https://download.pytorch.org/whl/cpu will install the CUDA version of torch; pass --extra-index-url as shown above or install the CPU build separately.

Getting Started

Some pointers to get you started:

Bazel setup

This project uses Bazel for building and dependency management.

To install Bazel, we actually install Bazelisk, which is a transparent wrapper that handles downloading and installing Bazel itself.

There are several ways to install Bazelisk. Here are some common ways:

See the Bazelisk README for more install instructions

However you install it, add it's location to PATH.

To verify the install, run bazel info in the repo's root directory:

bazel info

It should print information about the repo without errors.

VSCode clangd Setup

For C++ code navigation, it is recommended to use VSCode with clangd extension. Relying on a compilation database generated from Bazel action graph, clangd is able to enrich the editor with various smart features, including code completions, go-to definitions, etc.

  1. Generate the initial compile_commands.json:

    tools/setup_clangd.py
    

    If the VSCode code CLI is on PATH, the script also installs the clangd extension automatically. Otherwise, install the extension via the editor UI.

  2. Uninstall the Microsoft C++ extension, which interferes with clangd:

    code --uninstall-extension ms-vscode.cpptools
    

It may take a while (> 30 minutes) for the first run to make a full build, but reruns will be incremental and cheap. If you have run bazel build recently, generated files already exist so you can pass --no-build to skip waiting for heavy builds (note that on a fresh workspace, skipping the build may prevent clangd from resolving generated files). See more options in the tools/setup_clangd.py file-level comments.

Alternatively, you can invoke the script via nox (arguments after -- are forwarded):

nox -s refresh_compile_commands -- --no-build
nox -s refresh_compile_commands -- //src/torch_tpu/ops/...

Contributing

We welcome contributions to the PyTorch on TPU project! Please see our CONTRIBUTING.md for guidelines on how to contribute, including signing our Contributor License Agreement (CLA) and code review processes.

Star History

Star History Chart

License

This project is licensed under the Apache 2.0 License. See the LICENSE file for details.

torch_tpu (google-pytorch/torch_tpu)

Ищем в базе…

Что это?TorchTPU — это бэкенд PyTorch для тензорных процессоров Google (TPU), который позволяет запускать модели и операции PyTorch на аппаратуре TPU.
Это самостоятельный фреймворк или дополнение к существующему коду PyTorch?Это библиотека-бэкенд, а не отдельный фреймворк: вы продолжаете писать обычный код PyTorch, а TorchTPU предоставляет нужные пользовательские ядра ATen, кэш компиляции XLA и интеграцию с torch.compile, чтобы выполнять этот код на TPU.
Как установить TorchTPU?Установите опубликованный пакет wheel с PyPI (текущая версия 0.2.0) через pip или uv либо соберите wheel из исходников с помощью Bazel, если нужна пользовательская или неоптимизированная сборка.
Что нужно перед использованием?Python 3.11+ и доступ к реальному устройству TPU: в README рекомендуется работать на виртуальной машине TPU VM, а самым простым вариантом является экземпляр v6e GCE. Для сборки из исходников дополнительно требуется Bazel, установленный через Bazelisk.
Есть ли подводные камни при установке, о которых стоит знать?Если установить wheel без --extra-index-url, по умолчанию подтянется сборка torch с CUDA вместо совместимой с TPU, поэтому нужен правильный индекс или отдельная установка версии torch для CPU. При сборке из исходников также обязателен флаг --config=wheelcommon: без него итоговый wheel падает при импорте из-за дублирующихся статических регистраций.
Для каких моделей есть примеры кода?Примеры включены для Llama, Qwen, ResNet, DLRM, minGPT и UNet; они охватывают как распределённое обучение, так и сценарии инференса.
Поддерживает ли он распределённое обучение?Да, TorchTPU поддерживает параллелизм данных (Data Parallelism) и тензорный параллелизм (Tensor Parallelism) для распределённого обучения на нескольких устройствах TPU.
Интегрируется ли он с torch.compile?Да, он интегрируется с torch.compile(), что позволяет выполнять модели в графовом режиме на TPU.
Для чего используется кэш компиляции?Он хранит скомпилированные вычисления XLA, поэтому повторные запуски одного и того же графа выполняются быстрее, а не компилируются каждый раз заново.
Какие есть похожие проекты?open-r1, TensorRT-LLM, Meshy, PrismQuant, Intern-Decision, Agent-Reflex, airllm, DeepGEMM-Ascend
Автор
google-pytorch
Размер
2 GB
Звёзды
857
Обновлён
КоммитNov 18
Возраст
8 мес
Коммиты · 90 дней