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

[BUG] @tensorclass invalid indexing arguments #1200

Open
busFred opened this issue Feb 2, 2025 · 2 comments
Open

[BUG] @tensorclass invalid indexing arguments #1200

busFred opened this issue Feb 2, 2025 · 2 comments
Assignees
Labels
bug Something isn't working

Comments

@busFred
Copy link

busFred commented Feb 2, 2025

Describe the bug

I tried to decorate classes in dataclass fashion with tensorclass. From documentation, it says @tensorclass decorator helps you build custom classes that inherit the behaviour from TensorDict; it seems reasonable to assume classes decorated with tensorclass should also support indexing with key elements. However, this is not the case as shown below

To Reproduce

#%%
import tensordict as thd
import torch as th

#%%
@thd.tensorclass
class TC:
    a: th.Tensor
    b: th.Tensor

#%%
tc = TC(a=th.randn(512, 279), b=th.randn(512, 580), batch_size=(512, ))

#%%
# Cell Output 1
tc.keys()

#%%
# Cell Output 2
tc["a"]

#%%
# Cell Output 3
tc.a
  • Cell Output 1:
    _StringKeys(dict_keys(['a', 'b']))
    
  • Cell Output 2:
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    Cell In[16], [line 1](vscode-notebook-cell:?execution_count=16&line=1)
    ----> [1](vscode-notebook-cell:?execution_count=16&line=1) tc["a"]
    
    File ~/anaconda3/envs/bcb/lib/python3.11/site-packages/tensordict/tensorclass.py:1339, in _getitem(self, item)
       [1327](https://file+.vscode-resource.vscode-cdn.net/home/hungtien/Documents/research/bcb/~/anaconda3/envs/bcb/lib/python3.11/site-packages/tensordict/tensorclass.py:1327) """Retrieve the class object at the given index. Indexing will happen for nested tensors as well.
       [1328](https://file+.vscode-resource.vscode-cdn.net/home/hungtien/Documents/research/bcb/~/anaconda3/envs/bcb/lib/python3.11/site-packages/tensordict/tensorclass.py:1328) 
       [1329](https://file+.vscode-resource.vscode-cdn.net/home/hungtien/Documents/research/bcb/~/anaconda3/envs/bcb/lib/python3.11/site-packages/tensordict/tensorclass.py:1329) Args:
       (...)
       [1334](https://file+.vscode-resource.vscode-cdn.net/home/hungtien/Documents/research/bcb/~/anaconda3/envs/bcb/lib/python3.11/site-packages/tensordict/tensorclass.py:1334) 
       [1335](https://file+.vscode-resource.vscode-cdn.net/home/hungtien/Documents/research/bcb/~/anaconda3/envs/bcb/lib/python3.11/site-packages/tensordict/tensorclass.py:1335) """
       [1336](https://file+.vscode-resource.vscode-cdn.net/home/hungtien/Documents/research/bcb/~/anaconda3/envs/bcb/lib/python3.11/site-packages/tensordict/tensorclass.py:1336) if isinstance(item, str) or (
       [1337](https://file+.vscode-resource.vscode-cdn.net/home/hungtien/Documents/research/bcb/~/anaconda3/envs/bcb/lib/python3.11/site-packages/tensordict/tensorclass.py:1337)     isinstance(item, tuple) and all(isinstance(_item, str) for _item in item)
       [1338](https://file+.vscode-resource.vscode-cdn.net/home/hungtien/Documents/research/bcb/~/anaconda3/envs/bcb/lib/python3.11/site-packages/tensordict/tensorclass.py:1338) ):
    -> [1339](https://file+.vscode-resource.vscode-cdn.net/home/hungtien/Documents/research/bcb/~/anaconda3/envs/bcb/lib/python3.11/site-packages/tensordict/tensorclass.py:1339)     raise ValueError(f"Invalid indexing arguments: {item}.")
       [1340](https://file+.vscode-resource.vscode-cdn.net/home/hungtien/Documents/research/bcb/~/anaconda3/envs/bcb/lib/python3.11/site-packages/tensordict/tensorclass.py:1340) # tensor_res = super(type(self), self).__getattribute__("_tensordict")[item]
       [1341](https://file+.vscode-resource.vscode-cdn.net/home/hungtien/Documents/research/bcb/~/anaconda3/envs/bcb/lib/python3.11/site-packages/tensordict/tensorclass.py:1341) tensor_res = self.__dict__["_tensordict"][item]
    
    ValueError: Invalid indexing arguments: a.
    
  • Cell Output 3:
    tensor([[ 0.3309,  1.5588, -0.0955,  ..., -1.9812, -1.7319, -1.2441],
            [ 0.5179,  0.5649,  0.2708,  ..., -1.0906,  1.3735,  0.8244],
            [ 0.6232, -1.7976, -0.2683,  ...,  0.9437,  1.1947,  0.0095],
            ...,
            [ 0.3935, -1.0154, -1.2501,  ..., -0.0397, -1.1755,  0.3174],
            [ 0.1379,  0.3185,  0.3044,  ...,  0.9972,  0.2331, -0.1271],
            [-0.4836,  0.3843,  1.0005,  ..., -0.0945, -0.7485, -0.4110]])
    

Expected behavior

tc.[a"] should have same behavior as tc.a

Screenshots

n/a

System info

tensordict.__version__=="0.6.2"

2025-02-02 17:16:29 (28.1 MB/s) - ‘collect_env.py’ saved [24353/24353]

Collecting environment information...
PyTorch version: 2.5.1+cu124
Is debug build: False
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A

OS: Linux Mint 22 (x86_64)
GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.39

Python version: 3.11.11 (main, Dec 11 2024, 16:28:39) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.8.0-52-generic-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce MX150
Nvidia driver version: 550.120
cuDNN version: Could not collect
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Address sizes:                        39 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               8
On-line CPU(s) list:                  0-7
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz
CPU family:                           6
Model:                                142
Thread(s) per core:                   2
Core(s) per socket:                   4
Socket(s):                            1
Stepping:                             10
CPU(s) scaling MHz:                   88%
CPU max MHz:                          4200.0000
CPU min MHz:                          400.0000
BogoMIPS:                             4199.88
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb pti ssbd ibrs ibpb stibp tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust sgx bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp vnmi md_clear flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            128 KiB (4 instances)
L1i cache:                            128 KiB (4 instances)
L2 cache:                             1 MiB (4 instances)
L3 cache:                             8 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-7
Vulnerability Gather data sampling:   Mitigation; Microcode
Vulnerability Itlb multihit:          KVM: Mitigation: VMX disabled
Vulnerability L1tf:                   Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds:                    Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown:               Mitigation; PTI
Vulnerability Mmio stale data:        Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Mitigation; IBRS
Vulnerability Spec rstack overflow:   Not affected
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; IBRS; IBPB conditional; STIBP conditional; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                  Mitigation; Microcode
Vulnerability Tsx async abort:        Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] gpytorch==1.13
[pip3] numpy==1.26.4
[pip3] nvidia-cublas-cu12==12.4.5.8
[pip3] nvidia-cuda-cupti-cu12==12.4.127
[pip3] nvidia-cuda-nvrtc-cu12==12.4.127
[pip3] nvidia-cuda-runtime-cu12==12.4.127
[pip3] nvidia-cudnn-cu12==9.1.0.70
[pip3] nvidia-cufft-cu12==11.2.1.3
[pip3] nvidia-curand-cu12==10.3.5.147
[pip3] nvidia-cusolver-cu12==11.6.1.9
[pip3] nvidia-cusparse-cu12==12.3.1.170
[pip3] nvidia-nccl-cu12==2.21.5
[pip3] nvidia-nvjitlink-cu12==12.4.127
[pip3] nvidia-nvtx-cu12==12.4.127
[pip3] pytorch-lightning==2.5.0.post0
[pip3] pytorch-metric-learning==2.8.1
[pip3] torch==2.5.1
[pip3] torchmetrics==1.6.0
[pip3] triton==3.1.0
[conda] gpytorch                  1.13                     pypi_0    pypi
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] nvidia-cublas-cu12        12.4.5.8                 pypi_0    pypi
[conda] nvidia-cuda-cupti-cu12    12.4.127                 pypi_0    pypi
[conda] nvidia-cuda-nvrtc-cu12    12.4.127                 pypi_0    pypi
[conda] nvidia-cuda-runtime-cu12  12.4.127                 pypi_0    pypi
[conda] nvidia-cudnn-cu12         9.1.0.70                 pypi_0    pypi
[conda] nvidia-cufft-cu12         11.2.1.3                 pypi_0    pypi
[conda] nvidia-curand-cu12        10.3.5.147               pypi_0    pypi
[conda] nvidia-cusolver-cu12      11.6.1.9                 pypi_0    pypi
[conda] nvidia-cusparse-cu12      12.3.1.170               pypi_0    pypi
[conda] nvidia-nccl-cu12          2.21.5                   pypi_0    pypi
[conda] nvidia-nvjitlink-cu12     12.4.127                 pypi_0    pypi
[conda] nvidia-nvtx-cu12          12.4.127                 pypi_0    pypi
[conda] pytorch-lightning         2.5.0.post0              pypi_0    pypi
[conda] pytorch-metric-learning   2.8.1                    pypi_0    pypi
[conda] torch                     2.5.1                    pypi_0    pypi
[conda] torchmetrics              1.6.0                    pypi_0    pypi
[conda] triton                    3.1.0                    pypi_0    pypi

Additional context

n/a

Reason and Possible fixes

n/a

Checklist

  • [* ] I have checked that there is no similar issue in the repo (required)
  • [* ] I have read the documentation (required)
  • [* ] I have provided a minimal working example to reproduce the bug (required)
@busFred busFred added the bug Something isn't working label Feb 2, 2025
@busFred
Copy link
Author

busFred commented Feb 2, 2025

btw, after operation such as th.cat, instances of classes decorated with @tensorclass seems to become vanilla thd.TensorDict, which makes it only supports indexing operation but not 'dot' operation.

@vmoens
Copy link
Contributor

vmoens commented Feb 6, 2025

Hello!
Wrt to this

btw, after operation such as th.cat, instances of classes decorated with @Tensorclass seems to become vanilla thd.TensorDict, which makes it only supports indexing operation but not 'dot' operation.

I'm happy to say that it has been fixed in the new release!

To the main issue, it's a matter of design: in tensorclass we differentiate more clearly the __getitem__ along the shape dimension and the __getattr__ on the key dimension (whereas with TensorDict these two are blended together).

The .get() function still works:

tc.get("a") is tc.a

should work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants