快捷方式

merge_tensordicts

class tensordict.merge_tensordicts(*tensordicts: T, callback_exist: Optional[Union[Callable[[Any], Any], Dict[NestedKey, Callable[[Any], Any]]]] = None)

将 tensordict 合并在一起。

参数:

*tensordicts (TensorDict 序列等效) – 要合并在一起的 tensordict 列表。

关键字参数:

callback_exist (callableDict[str, callable], 可选) – 当每个 tensordict 中都存在条目时的可调用对象。如果条目存在于某些但并非所有 tensordict 中,或者如果未传递 callback_exist,则使用 update,并将使用 tensordict 序列中的第一个非 None 值。如果传递了可调用对象的字典,它将包含与传递给函数的 tensordict 中的某些嵌套键关联的回调函数。

示例

>>> from tensordict import merge_tensordicts, TensorDict
>>> td0 = TensorDict({"a": {"b0": 0}, "c": {"d": {"e": 0}}, "common": 0})
>>> td1 = TensorDict({"a": {"b1": 1}, "f": {"g": {"h": 1}}, "common": 1})
>>> td2 = TensorDict({"a": {"b2": 2}, "f": {"g": {"h": 2}}, "common": 2})
>>> td = merge_tensordicts(td0, td1, td2, callback_exist=lambda *v: torch.stack(list(v)))
>>> print(td)
TensorDict(
    fields={
        a: TensorDict(
            fields={
                b0: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False),
                b1: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False),
                b2: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)},
            batch_size=torch.Size([]),
            device=None,
            is_shared=False),
        c: TensorDict(
            fields={
                d: TensorDict(
                    fields={
                        e: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)},
                    batch_size=torch.Size([]),
                    device=None,
                    is_shared=False)},
            batch_size=torch.Size([]),
            device=None,
            is_shared=False),
        common: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.int64, is_shared=False),
        f: TensorDict(
            fields={
                g: TensorDict(
                    fields={
                        h: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)},
                    batch_size=torch.Size([]),
                    device=None,
                    is_shared=False)},
            batch_size=torch.Size([]),
            device=None,
            is_shared=False)},
    batch_size=torch.Size([]),
    device=None,
    is_shared=False)
>>> print(td["common"])
tensor([0, 1, 2])

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深度教程

查看教程

资源

查找开发资源并获得您的问题解答

查看资源