Skip to content
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

[Feature] Tokenizer for LLMEnv #2852

Merged
merged 5 commits into from
Mar 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 74 additions & 38 deletions test/test_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import re
import string
from collections import defaultdict
from contextlib import nullcontext
from functools import partial
from sys import platform
from typing import Any, Optional
Expand All @@ -33,7 +34,7 @@
TensorDictBase,
)
from tensordict.nn import TensorDictModuleBase
from tensordict.tensorclass import NonTensorStack, TensorClass
from tensordict.tensorclass import NonTensorData, NonTensorStack, TensorClass
from tensordict.utils import _unravel_key_to_tuple
from torch import nn

Expand Down Expand Up @@ -4630,6 +4631,7 @@ def __next__(self):
else:
return tensors

@pytest.mark.skipif(not _has_transformers, reason="test requires transformers")
@pytest.mark.parametrize(
"str2str,stack_method",
[
Expand Down Expand Up @@ -4674,22 +4676,36 @@ def test_llm_env(self, str2str, batched, stack_method, device, batch_size):
else:
env.check_env_specs(break_when_any_done="both")

@pytest.mark.skipif(not _has_transformers, reason="test requires transformers")
@pytest.mark.parametrize("tokenizer", [True, False])
@pytest.mark.parametrize(
"str2str,stack_method",
"str2str,no_stack,stack_method",
[
[True, None],
[False, "as_padded_tensor"],
# TODO: a bit experimental, fails with check_env_specs
# [False, "as_nested_tensor"],
[False, None],
[True, True, None],
[True, False, None],
[False, False, "as_padded_tensor"],
[False, False, None],
],
)
@pytest.mark.parametrize("batched", [True, False])
@pytest.mark.parametrize("device", [None, "cpu"])
@pytest.mark.parametrize("batch_size", [0, 4])
def test_llm_from_dataloader(
self, str2str, batched, stack_method, device, batch_size
self,
str2str,
batched,
stack_method,
device,
batch_size,
tokenizer,
no_stack,
):
from transformers import AutoTokenizer

if tokenizer:
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
else:
tokenizer = None
if str2str:
kwargs = {
"dataloader": self.DummyDataLoader(batch_size=batch_size),
Expand All @@ -4712,7 +4728,8 @@ def test_llm_from_dataloader(
"str2str": str2str,
"device": device,
"has_attention": False,
"no_stack": False,
"no_stack": no_stack,
"tokenizer": tokenizer,
}
)
env = LLMEnv.from_dataloader(**kwargs)
Expand All @@ -4725,12 +4742,17 @@ def test_llm_from_dataloader(
if batch_size > 0:

def policy(td):
if str2str:
if str2str and tokenizer is None:
if not td.shape:
td[LLMEnv._DEFAULT_ACTION_STR_KEY] = "<nothing>"
td[LLMEnv._DEFAULT_ACTION_STR_KEY] = NonTensorData(
"<nothing>", device=device
)
else:
td[LLMEnv._DEFAULT_ACTION_STR_KEY] = NonTensorStack(
*["<nothing>" for _ in range(td.shape[0])]
*[
NonTensorData("<nothing>", device=device)
for _ in range(td.shape[0])
]
)
else:
td[LLMEnv._DEFAULT_ACTION_TOKENS_KEY] = torch.ones(
Expand All @@ -4742,34 +4764,48 @@ def policy(td):
# Tell the env that we want 3 sub-envs
r = env.rollout(10, policy, tensordict=TensorDict(batch_size=[3]))
assert r.ndim == 2
if str2str:
if str2str and tokenizer is None:
assert isinstance(r[0, 0][LLMEnv._DEFAULT_STR_KEY], str)
assert isinstance(r[0, 1][LLMEnv._DEFAULT_STR_KEY], str)
assert (
r[0, 0][LLMEnv._DEFAULT_STR_KEY]
== r[0, 1][LLMEnv._DEFAULT_STR_KEY][
: -len(r[0, 0][LLMEnv._DEFAULT_ACTION_STR_KEY])
]
)
assert (
r[0, 1][LLMEnv._DEFAULT_STR_KEY]
== r[0, 2][LLMEnv._DEFAULT_STR_KEY][
: -len(r[0, 1][LLMEnv._DEFAULT_ACTION_STR_KEY])
]
)
assert (
r[-1, 0][LLMEnv._DEFAULT_STR_KEY]
== r[-1, 1][LLMEnv._DEFAULT_STR_KEY][
: -len(r[-1, 0][LLMEnv._DEFAULT_ACTION_STR_KEY])
]
)
assert (
r[-1, 1][LLMEnv._DEFAULT_STR_KEY]
== r[-1, 2][LLMEnv._DEFAULT_STR_KEY][
: -len(r[-1, 1][LLMEnv._DEFAULT_ACTION_STR_KEY])
]
)
else:
should_fail = no_stack
if should_fail:
ctx = pytest.raises(AssertionError)
else:
ctx = nullcontext()
with ctx:
assert (
r[0, 0][LLMEnv._DEFAULT_STR_KEY]
== r[0, 1][LLMEnv._DEFAULT_STR_KEY][
: -len(r[0, 0][LLMEnv._DEFAULT_ACTION_STR_KEY])
]
), (
r[0, 0][LLMEnv._DEFAULT_STR_KEY],
r[0, 0][LLMEnv._DEFAULT_ACTION_STR_KEY],
r[0, 0]["next", LLMEnv._DEFAULT_STR_KEY],
r[0, 1][LLMEnv._DEFAULT_STR_KEY],
)
with ctx:
assert (
r[0, 1][LLMEnv._DEFAULT_STR_KEY]
== r[0, 2][LLMEnv._DEFAULT_STR_KEY][
: -len(r[0, 1][LLMEnv._DEFAULT_ACTION_STR_KEY])
]
)
with ctx:
assert (
r[-1, 0][LLMEnv._DEFAULT_STR_KEY]
== r[-1, 1][LLMEnv._DEFAULT_STR_KEY][
: -len(r[-1, 0][LLMEnv._DEFAULT_ACTION_STR_KEY])
]
)
with ctx:
assert (
r[-1, 1][LLMEnv._DEFAULT_STR_KEY]
== r[-1, 2][LLMEnv._DEFAULT_STR_KEY][
: -len(r[-1, 1][LLMEnv._DEFAULT_ACTION_STR_KEY])
]
)
elif tokenizer is None:
assert (
r[0, 0][LLMEnv._DEFAULT_TOKEN_KEY]
== r[0, 1][LLMEnv._DEFAULT_TOKEN_KEY][:-1]
Expand Down
Loading
Loading