Repository navigation
[BugFix] Fix IncrementalTokenizer with unequal token lengths - #4722
KhushiKeswani wants to merge 3 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/rl/4722
Note: Links to docs will display an error until the docs builds have been completed.
|
|
| Prefix | Label Applied | Example |
|---|---|---|
[Algorithm] |
new algo | [Algorithm] Add new RL objective |
[BE] |
BE | [BE] Improve error messages |
[Benchmark] or [Benchmarks] |
Benchmarks | [Benchmark] Add collector benchmark |
[BugFix] |
BugFix | [BugFix] Fix memory leak in collector |
[Example] or [Examples] |
Examples | [Example] Add training script |
[Feature] |
Feature | [Feature] Add new optimizer |
[Doc] or [Docs] |
Documentation | [Doc] Update installation guide |
[Refactor] |
Refactoring | [Refactor] Clean up module imports |
[CI] |
CI | [CI] Fix workflow permissions |
[Test] or [Tests] |
Tests | [Tests] Add unit tests for buffer |
[Trainer] or [Trainers] |
Trainers | [Trainer] Add trainer config |
[Environment] or [Environments] |
Environments | [Environments] Add Gymnasium support |
[Data] |
Data | [Data] Fix replay buffer sampling |
[LLM] |
llm/ | [LLM] Add reward model integration |
[Minor] |
small change | [Minor] Fix typo in error message |
[Performance] or [Perf] |
Performance | [Performance] Optimize tensor ops |
[BC-Breaking] |
bc breaking | [BC-Breaking] Remove deprecated API |
[Deprecation] |
Deprecation | [Deprecation] Mark old function |
[Algorithm] or [Algorithms] |
new algo | [Algorithm] Add new objective |
[Quality] |
Quality | [Quality] Fix typos and add codespell |
[Versioning] |
versioning | [Versioning] Bump release version |
[WIP] |
WIP | [WIP] Draft implementation |
Note: Common variations like singular/plural are supported (e.g., [Doc] or [Docs]).
|
| Prefix | Label Applied | Example |
|---|---|---|
[Algorithm] |
new algo | [Algorithm] Add new RL objective |
[BE] |
BE | [BE] Improve error messages |
[Benchmark] or [Benchmarks] |
Benchmarks | [Benchmark] Add collector benchmark |
[BugFix] |
BugFix | [BugFix] Fix memory leak in collector |
[Example] or [Examples] |
Examples | [Example] Add training script |
[Feature] |
Feature | [Feature] Add new optimizer |
[Doc] or [Docs] |
Documentation | [Doc] Update installation guide |
[Refactor] |
Refactoring | [Refactor] Clean up module imports |
[CI] |
CI | [CI] Fix workflow permissions |
[Test] or [Tests] |
Tests | [Tests] Add unit tests for buffer |
[Trainer] or [Trainers] |
Trainers | [Trainer] Add trainer config |
[Environment] or [Environments] |
Environments | [Environments] Add Gymnasium support |
[Data] |
Data | [Data] Fix replay buffer sampling |
[LLM] |
llm/ | [LLM] Add reward model integration |
[Minor] |
small change | [Minor] Fix typo in error message |
[Performance] or [Perf] |
Performance | [Performance] Optimize tensor ops |
[BC-Breaking] |
bc breaking | [BC-Breaking] Remove deprecated API |
[Deprecation] |
Deprecation | [Deprecation] Mark old function |
[Algorithm] or [Algorithms] |
new algo | [Algorithm] Add new objective |
[Quality] |
Quality | [Quality] Fix typos and add codespell |
[Versioning] |
versioning | [Versioning] Bump release version |
[WIP] |
WIP | [WIP] Draft implementation |
Note: Common variations like singular/plural are supported (e.g., [Doc] or [Docs]).
coder-jayp
left a comment
There was a problem hiding this comment.
Thanks for the contribution
Left inline comments—the rollout from #4686 still raises RuntimeError during env.step() because only the child "tokens" is lazy-stacked while the root is a standard TensorDict.
| tokens_full_key = (*tokens_key[:-1], "full") | ||
| existing_tokens_full = tensordict.get(tokens_full_key, None) | ||
|
|
||
| if isinstance(tensordict, LazyStackedTensorDict): |
There was a problem hiding this comment.
In ChatEnv, the root action_td is a normal TensorDict and only the child "tokens" is lazy-stacked. The isinstance check evaluates to False, falls back to else:, and env.step(action_td) still crashes with RuntimeError.
Using as_list=True directly in tensordict.get() handles this without needing the isinstance check.
There was a problem hiding this comment.
With as_list=True, existing_tokens_full becomes a Python list. Setting it directly stores it as NonTensorData (which is why .data was needed in the test assertion). It should be converted back into a nested tensor with torch.nested.as_nested_tensor before being set on next_tensordict.
| batch_size=(2,), | ||
| ) | ||
|
|
||
| out = env.transform._step(td, next_td) |
There was a problem hiding this comment.
Could this test be updated to call the public env.step(action_td) directly on the output of env.reset()? Calling private _step() with a manual lazy_stack bypasses how ChatEnv actually packages tensordicts in real rollouts
|
@coder-jayp hey, can you please review it now and tell me if this bug is tackled now in right way or there are some issues yet to address. |
|
I checked the revised ebc8606 through the public I also strengthened the public-step test below to assert the output is an int64 nested tensor and each decoded row exactly equals its rendered next history. A second case supplies a stale first-row token prefix while the other row remains valid, covering fallback and incremental extension in the same unequal-length batch. Both cases pass on this revision; both fail with the previous This complements the prefix/length assertions: they alone would not catch missing text later in a reply or a mix-up between conversation rows. Ruff lint passes and the changed method is formatted. Windows/Python 3.12.14, torch 2.11 CPU, TensorDict nightly and the real GPT-2 tokenizer. Nested-tensor prototype, version and Additional test assertionsdiff --git a/test/llm/test_llm_transforms.py b/test/llm/test_llm_transforms.py
index 26821255..46141cf7 100644
--- a/test/llm/test_llm_transforms.py
+++ b/test/llm/test_llm_transforms.py
@@ -909,7 +909,10 @@ class TestIncrementalTokenizer:
assert result.is_nested
for actual, expected in zip(result.unbind(), tokens):
assert torch.equal(actual, expected)
- def test_step_tokens_full_unequal_lengths_with_history(self, tokenizer):
+ @pytest.mark.parametrize("stale_first_row", [False, True])
+ def test_step_tokens_full_unequal_lengths_with_history(
+ self, tokenizer, stale_first_row
+ ):
"""Handle unequal token lengths through the public env.step() API."""
env = ChatEnv.with_tokenizer(batch_size=(2,), tokenizer=tokenizer)
@@ -948,6 +951,11 @@ class TestIncrementalTokenizer:
for i in range(2)
]
+ if stale_first_row:
+ full_tokens[0] = torch.tensor(
+ tokenizer("unrelated stale text", add_special_tokens=False)["input_ids"]
+ )
+
# Build the nested tokens child that occurs in the real batched workflow.
tokens_td = lazy_stack(
[
@@ -966,12 +974,21 @@ class TestIncrementalTokenizer:
# Exercise the public environment step, not the transform's private method.
next_td = env.step(action_td)["next"]
- new_tokens = next_td.get(("tokens", "prompt"), as_list=True)
+ token_tensor = next_td.get(("tokens", "prompt"))
+ assert token_tensor.is_nested and token_tensor.dtype == torch.int64
+ new_tokens = token_tensor.unbind()
+ expected_texts = next_td.get(("history", "prompt")).apply_chat_template(
+ tokenizer=tokenizer, tokenize=False, add_generation_prompt=True
+ )
+ assert [
+ tokenizer.decode(row, skip_special_tokens=False) for row in new_tokens
+ ] == expected_texts
for old, new in zip(old_tokens, new_tokens):
- assert torch.equal(new[:old.numel()], old)
+ assert torch.equal(new[: old.numel()], old)
assert new.numel() > old.numel()
+
class TestTokenizer:
@pytest.mark.parametrize("tokenizer_cls", [Tokenizer, EnvTokenizer])
@pytest.mark.filterwarnings("error::DeprecationWarning")
|
|
@bsprenger i have raised PR fixing incremental token with unequal token length and wanted to follow up. can you please whenever free, review and tell me appropriate next step. |
coder-jayp
left a comment
There was a problem hiding this comment.
LGTM! Just fix the blank lines in test/llm/test_llm_transforms.py so flake8 passes on CI.
Description
IncrementalTokenizer._step()raising aRuntimeErrorwhen accessingtokens.fullfrom aLazyStackedTensorDictcontaining sequences of different lengths.get(..., as_list=True)forLazyStackedTensorDictto retrieve individual token sequences without attempting to stack tensors with incompatible shapes.TensorDictinstances.Motivation and Context
When processing a 1-D batch with variable-length token sequences,
LazyStackedTensorDict.get()attempts to stack the individual tensors. Since their lengths differ, this raises aRuntimeError.This change retrieves the sequences individually for lazy stacks while preserving the existing behavior for regular TensorDicts.
Fixes #4686.
Types of changes
Checklist