Shortcuts

设置TorchRec

在本节中,我们将:

  • 了解使用TorchRec的要求

  • 设置一个环境以集成TorchRec

  • 运行基本的TorchRec代码

系统要求

TorchRec 通常在 AWS Linux 上进行测试,并且应该在类似环境中工作。 下面展示了当前测试的兼容性矩阵:

Python 版本

3.9, 3.10, 3.11, 3.12

计算平台

CPU, CUDA 11.8, CUDA 12.1, CUDA 12.4

除了这些要求外,TorchRec的核心依赖是PyTorch和FBGEMM。 如果你的系统通常与这两个库兼容,那么它应该足以支持TorchRec。

版本兼容性

TorchRec 和 FBGEMM 具有匹配的版本号,在发布时会一起进行测试:

  • TorchRec 1.0 与 FBGEMM 1.0 兼容

  • TorchRec 0.8 与 FBGEMM 0.8 兼容

  • TorchRec 0.8 可能与 FBGEMM 0.7 不兼容

此外,TorchRec 和 FBGEMM 仅在发布新版本的 PyTorch 时才会发布。 因此,特定版本的 TorchRec 和 FBGEMM 应该对应特定版本的 PyTorch:

  • TorchRec 1.0 与 PyTorch 2.5 兼容

  • TorchRec 0.8 与 PyTorch 2.4 兼容

  • TorchRec 0.8 可能与 PyTorch 2.3 不兼容

安装

下面我们以CUDA 12.1的安装为例。对于CPU、CUDA 11.8或CUDA 12.4,分别将cu121替换为cpucu118cu124

pip install torch --index-url https://download.pytorch.org/whl/cu121
pip install fbgemm-gpu --index-url https://download.pytorch.org/whl/cu121
pip install torchmetrics==1.0.3
pip install torchrec --index-url https://download.pytorch.org/whl/cu121
pip install torch
pip install fbgemm-gpu
pip install torchrec
pip install torch --index-url https://download.pytorch.org/whl/nightly/cu121
pip install fbgemm-gpu --index-url https://download.pytorch.org/whl/nightly/cu121
pip install torchmetrics==1.0.3
pip install torchrec --index-url https://download.pytorch.org/whl/nightly/cu121

您还可以从源代码构建TorchRec,以便使用TorchRec的最新更改进行开发。要从源代码构建,请查看此参考

运行一个简单的TorchRec示例

现在我们已经正确设置了TorchRec,让我们运行一些TorchRec代码! 下面,我们将使用TorchRec数据类型运行一个简单的前向传递:KeyedJaggedTensorEmbeddingBagCollection

import torch

import torchrec
from torchrec.sparse.jagged_tensor import JaggedTensor, KeyedJaggedTensor

ebc = torchrec.EmbeddingBagCollection(
    device="cpu",
    tables=[
        torchrec.EmbeddingBagConfig(
            name="product_table",
            embedding_dim=16,
            num_embeddings=4096,
            feature_names=["product"],
            pooling=torchrec.PoolingType.SUM,
        ),
        torchrec.EmbeddingBagConfig(
            name="user_table",
            embedding_dim=16,
            num_embeddings=4096,
            feature_names=["user"],
            pooling=torchrec.PoolingType.SUM,
        )
    ]
)

product_jt = JaggedTensor(
    values=torch.tensor([1, 2, 1, 5]), lengths=torch.tensor([3, 1])
)
user_jt = JaggedTensor(values=torch.tensor([2, 3, 4, 1]), lengths=torch.tensor([2, 2]))

# Q1: How many batches are there, and which values are in the first batch for product_jt and user_jt?
kjt = KeyedJaggedTensor.from_jt_dict({"product": product_jt, "user": user_jt})

print("Call EmbeddingBagCollection Forward: ", ebc(kjt))

将上述代码保存到名为 torchrec_example.py 的文件中。然后,你应该能够从终端执行它:

python torchrec_example.py

你应该看到输出 KeyedTensor 以及生成的嵌入。 恭喜!你已经正确安装并运行了你的第一个 TorchRec 程序!