Skip to main content

tensor-toolkit

A lightweight PyTorch utility toolkit for tensor operations, validation, and model utilities.


Features and Function Descriptions

Tensor Utilities

  • to_device(tensor, device=None)
    Move a tensor to the specified device (CPU or GPU). Automatically selects GPU if available when no device is provided.

  • get_device(tensor)
    Returns the current device of the given tensor.

  • seed_all(seed=42)
    Set random seeds for PyTorch (CPU and GPU) and NumPy to ensure reproducible results.

  • count_params(model, trainable_only=True)
    Count the number of parameters in a PyTorch model. Optionally count only trainable parameters.

  • tensor_summary(tensor)
    Print a detailed summary of a tensor including shape, dtype, device, and statistics (min, max, mean, std).

  • one_hot(labels, num_classes)
    Convert a tensor of label indices into one-hot encoded format.

  • accuracy(outputs, targets)
    Compute classification accuracy by comparing model outputs (logits or probabilities) to target labels.


Tensor Checks

  • is_tensor(x)
    Check whether an object is a PyTorch tensor.

  • has_nan(x)
    Check if the tensor contains any NaN values.

  • has_inf(x)
    Check if the tensor contains any positive or negative infinity values.

  • check_tensor_validity(x, raise_error=False)
    Validate the tensor for correct type, and absence of NaN or Inf values. Raises exceptions if raise_error=True; otherwise, returns status messages.


Installation

pip install tensor-toolkit

Requirements

  • torch >=1.10.0
  • numpy >=1.21.0 (used for seeding and numerical utilities)

To install requirements:

pip install -r requirements.txt

Usage Example

import torch
import tensorkit as tk

def main():
    # Create a random tensor
    x = torch.randn(3, 3)
    print("Original tensor device:", tk.get_device(x))

    # Move tensor to device (GPU if available)
    x = tk.to_device(x)
    print("Tensor moved to device:", tk.get_device(x))

    # Set seed for reproducibility
    tk.seed_all(42)
    t1 = torch.randn(2, 2)
    tk.seed_all(42)
    t2 = torch.randn(2, 2)
    print("Seed reproducible two tensors equal:", torch.equal(t1, t2))

    # Count parameters of a model
    model = torch.nn.Linear(4, 2)
    print(f"Model trainable parameters: {tk.count_params(model)}")

    # Print tensor summary
    print("Tensor summary:")
    tk.tensor_summary(x)

    # One-hot encode labels
    labels = torch.tensor([0, 1, 2])
    one_hot_labels = tk.one_hot(labels, num_classes=3)
    print("One-hot encoded labels:\n", one_hot_labels)

    # Calculate accuracy given model outputs and targets
    outputs = torch.tensor([[0.8, 0.1, 0.1],
                            [0.2, 0.7, 0.1],
                            [0.1, 0.2, 0.7]])
    targets = torch.tensor([0, 1, 2])
    acc = tk.accuracy(outputs, targets)
    print(f"Accuracy: {acc:.2%}")

    # Check tensor validity
    print("Is tensor:", tk.is_tensor(x))
    print("Contains NaN:", tk.has_nan(x))
    print("Contains Inf:", tk.has_inf(x))
    print("Tensor validity:", tk.check_tensor_validity(x))

if __name__ == "__main__":
    main()

Project Structure

tensor-toolkit/             # Project root folder
├── examples/               # Example scripts
│ └── usage_example.py      # Usage demonstration
├── tensorkit/              # Main package folder
│ ├── init.py               # API exports
│ ├── tensor_utils.py       # Tensor utility functions
│ ├── tensor_checks.py      # Tensor validation functions
├── tests/                  # Unit tests
│ ├── init.py
│ ├── test_tensor_utils.py  # Tests for tensor_utils
│ └── test_tensor_checks.py # Tests for tensor_checks
├── LICENSE                 # MIT License
├── pyproject.toml          # Project configuration
├── README.md               # Project documentation
├── requirements.txt        # Package dependencies

Contact

Created by Suresh K — GitHub


License

This project is licensed under the MIT License. See the LICENSE file for details.

Metadata

Release files for tensor-toolkit 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tensor-toolkit 0.1.1
File Size Uploaded
tensor_toolkit-0.1.1.tar.gz 5.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for tensor-toolkit 0.1.1
File Interpreter ABI Platform
tensor_toolkit-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 11.2 kB

Release files / tensor_toolkit-0.1.1.tar.gz

Download URL tensor_toolkit-0.1.1.tar.gz
Size 5.7 kB
Tags Source
SHA-256 checksum
How to use checksums
467270bb5fe57a2a6fa61ca95271fffa421ae5df8fab3c2959fd861bb721bcac
BLAKE2b-256 checksum
How to use checksums
560496be0268704490442e2f8583a62575669efea3126f5e51d3ce4b85eb3f19
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.12

Release files / tensor_toolkit-0.1.1-py3-none-any.whl

Download URL tensor_toolkit-0.1.1-py3-none-any.whl
Size 5.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
af392c895b855eff5f5061ce0725b3118ddef1fa4f0ac59c9680452f32b29579
BLAKE2b-256 checksum
How to use checksums
6c5e82368eb17d653b776aab9c9b6ca1c58087805429b4c1076bf80b2136a2db
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.12

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page