Skip to content

tensor: raise error when setting requires_grad=True on non-float tensors #10342

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

Conversation

kozuedoingregression
Copy link

fixes issue #9723

This PR adds a runtime check in the Tensor constructor to raise a RuntimeError when requires_grad=True is set on a non-floating point tensor.

from tinygrad import Tensor
print(Tensor([1.0, 2.0, 3.0], requires_grad=True).tolist())  
print(Tensor([1, 2, 3], requires_grad=False).tolist())       
print(Tensor([1, 2, 3], requires_grad=True).tolist())        

out:

[1.0, 2.0, 3.0]
[1, 2, 3]
Traceback (most recent call last):
  File "/mnt/z/work/tinygrad/tt.py", line 5, in <module>
    print(Tensor([1, 2, 3], requires_grad=True).tolist())
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/mnt/z/work/tinygrad/tinygrad/tensor.py", line 171, in __init__
    raise RuntimeError(f"Only Tensors of floating point dtype can require gradients")
RuntimeError: Only Tensors of floating point dtype can require gradients

Copy link
Contributor

Changes

Name                  Lines    Diff    Tokens/Line    Diff
------------------  -------  ------  -------------  ------
tinygrad/tensor.py     1352      +2           20.3    -0.0


total lines changes: +2

@kozuedoingregression kozuedoingregression marked this pull request as draft May 15, 2025 19:56
@chenyuxyz chenyuxyz closed this May 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants