From cf3ab8e79d3d61d05fce406afd61ef9b9c72300d Mon Sep 17 00:00:00 2001 From: Taksh Date: Wed, 24 Jun 2026 16:01:13 +0530 Subject: [PATCH] Fix Vocab.to_tokens crash on single-element index lists Use isinstance(list, tuple) instead of len(indices) > 1 so [15] is treated as a collection, not a scalar index. Co-authored-by: Cursor --- chapter_recurrent-neural-networks/text-sequence.md | 2 +- d2l/jax.py | 2 +- d2l/mxnet.py | 2 +- d2l/tensorflow.py | 2 +- d2l/torch.py | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/chapter_recurrent-neural-networks/text-sequence.md b/chapter_recurrent-neural-networks/text-sequence.md index 9b7b4c7cd7..224a917796 100644 --- a/chapter_recurrent-neural-networks/text-sequence.md +++ b/chapter_recurrent-neural-networks/text-sequence.md @@ -172,7 +172,7 @@ class Vocab: #@save return [self.__getitem__(token) for token in tokens] def to_tokens(self, indices): - if hasattr(indices, '__len__') and len(indices) > 1: + if isinstance(indices, (list, tuple)): return [self.idx_to_token[int(index)] for index in indices] return self.idx_to_token[indices] diff --git a/d2l/jax.py b/d2l/jax.py index b1210edc9c..67fd26bdf7 100644 --- a/d2l/jax.py +++ b/d2l/jax.py @@ -840,7 +840,7 @@ def __getitem__(self, tokens): return [self.__getitem__(token) for token in tokens] def to_tokens(self, indices): - if hasattr(indices, '__len__') and len(indices) > 1: + if isinstance(indices, (list, tuple)): return [self.idx_to_token[int(index)] for index in indices] return self.idx_to_token[indices] diff --git a/d2l/mxnet.py b/d2l/mxnet.py index 8e7d7673a3..8f34eb32cf 100644 --- a/d2l/mxnet.py +++ b/d2l/mxnet.py @@ -709,7 +709,7 @@ def __getitem__(self, tokens): return [self.__getitem__(token) for token in tokens] def to_tokens(self, indices): - if hasattr(indices, '__len__') and len(indices) > 1: + if isinstance(indices, (list, tuple)): return [self.idx_to_token[int(index)] for index in indices] return self.idx_to_token[indices] diff --git a/d2l/tensorflow.py b/d2l/tensorflow.py index fd9ca23fda..a443142ccc 100644 --- a/d2l/tensorflow.py +++ b/d2l/tensorflow.py @@ -658,7 +658,7 @@ def __getitem__(self, tokens): return [self.__getitem__(token) for token in tokens] def to_tokens(self, indices): - if hasattr(indices, '__len__') and len(indices) > 1: + if isinstance(indices, (list, tuple)): return [self.idx_to_token[int(index)] for index in indices] return self.idx_to_token[indices] diff --git a/d2l/torch.py b/d2l/torch.py index 84ce7da901..227b0c2bea 100644 --- a/d2l/torch.py +++ b/d2l/torch.py @@ -700,7 +700,7 @@ def __getitem__(self, tokens): return [self.__getitem__(token) for token in tokens] def to_tokens(self, indices): - if hasattr(indices, '__len__') and len(indices) > 1: + if isinstance(indices, (list, tuple)): return [self.idx_to_token[int(index)] for index in indices] return self.idx_to_token[indices]