Lovely Tensors
lovely-tensors is a Python library that provides "syntax sugar" for PyTorch tensors, enhancing their default `repr` for better readability, debugging, and development. It adds features like rich, colored, and pretty-printed output, automatic batching, and shape inference. As of version 0.1.22, it is actively maintained with frequent minor releases focusing on new features and improvements.
Common errors
-
ModuleNotFoundError: No module named 'lovely_tensors'
cause The `lovely-tensors` library is not installed in your current Python environment.fixRun `pip install lovely-tensors` to install the library. -
PyTorch tensors are not displaying with pretty colors or enhanced information, even after importing lovely_tensors.
cause The `monkey_patch()` function was not called, which is necessary to enable the global `__repr__` enhancement.fixAfter `import lovely_tensors as lt`, add `lt.monkey_patch()` to activate the desired behavior. -
AttributeError: 'Tensor' object has no attribute 'lovely'
cause You are trying to access `lovely` as a method directly on a `torch.Tensor` instance, but `lovely` is a function provided by the `lovely_tensors` module, not a tensor method.fixInstead of `my_tensor.lovely()`, use `lt.lovely(my_tensor)` to explicitly pretty-print the tensor.
Warnings
- gotcha To activate the enhanced `__repr__` for PyTorch tensors automatically, you must explicitly call `lovely_tensors.monkey_patch()` after importing the library. Simply importing `lovely_tensors` is not enough.
- gotcha lovely-tensors modifies the `__repr__` method of `torch.Tensor` instances. If you are using other debugging tools or libraries that also monkey-patch `torch.Tensor`'s `__repr__`, this might lead to conflicts or unexpected display behavior.
- deprecated Older versions of lovely-tensors used `lovely_tensors.init()` for activation. This method has been replaced by `lovely_tensors.monkey_patch()` for clarity and consistency.
Install
-
pip install lovely-tensors
Imports
- lovely_tensors
import lovely_tensors as lt
- monkey_patch
import lovely_tensors.monkey_patch # This doesn't activate it
import lovely_tensors as lt lt.monkey_patch()
- lovely
import lovely_tensors as lt lt.lovely(my_tensor)
Quickstart
import torch
import lovely_tensors as lt
# Enable beautiful tensor repr globally
lt.monkey_patch()
# Create some tensors
a = torch.randn(2, 3, 4)
b = torch.randint(0, 10, (1, 5), dtype=torch.int)
print(f"Tensor a:\n{a}")
print(f"Tensor b:\n{b}")
# You can also explicitly print lovely tensors without monkey-patching
# For demonstration, let's pretend monkey_patch wasn't called:
# import lovely_tensors as lt
# lt.lovely(torch.tensor([1,2,3]))