Skip to content

Outsource tensor functionality into mixins - #27

Merged
mctigger merged 10 commits into
mainfrom
refactor-mixins
Sep 29, 2025
Merged

Outsource tensor functionality into mixins#27
mctigger merged 10 commits into
mainfrom
refactor-mixins

Conversation

@mctigger

Copy link
Copy Markdown
Owner

Refactor: Extract Common Tensor Operations to Mixins

Summary

Extract tensor operations into modular mixins - Decomposed TensorContainer's monolithic operation set into focused, reusable mixins for shape, math, type, and device
operations
Establish protocol-based mixin constraints - Introduced TensorContainerProtocol to ensure type safety and proper interface contracts for mixin usage
Improve code organization and maintainability - Operations are now grouped by functionality, making the codebase easier to understand and extend

Changes

Core Architecture Refactoring

  • New mixin system (src/tensorcontainer/mixins/) with four focused operation mixins:

    • TensorShapeOperationsMixin - Shape transformations (view, reshape, permute, etc.)
    • TensorMathOperationsMixin - Mathematical operations (add, sub, mul, sqrt, etc.)
    • TensorTypeOperationsMixin - Type conversions (float, int, double, etc.)
    • TensorDeviceOperationsMixin - Device/memory operations (to, cpu, cuda, clone, etc.)
  • Protocol-based type safety (src/tensorcontainer/protocols.py):

    • TensorContainerProtocol defines required interface for mixin compatibility
    • Runtime-checkable protocol prevents misuse of mixins
    • Ensures all mixins have access to required TensorContainer methods

Updated Container Implementations

  • TensorDataClass integration - Now inherits from all four operation mixins, gaining full tensor operation capabilities while maintaining dataclass functionality
  • Clean separation of concerns - Container classes focus on core logic while mixins handle operations

API Compatibility

  • Backward compatible - All existing TensorContainer operations continue to work unchanged
  • Enhanced modularity - Users can now compose custom containers with only needed operation sets
  • Type safety improvements - Better static typing support through protocol constraints

Tim Joseph added 10 commits September 18, 2025 09:31
Move tensor shape, math, type, and device operations from `TensorContainer` into dedicated mixin classes.

This refactoring reduces code duplication across `TensorContainer`, `TensorDataClass`, `TensorDict`, and `TensorDistribution` by centralizing common functionalities. It improves modularity and maintainability, making the codebase easier to extend and reason about.

`TensorContainer` now explicitly implements `TensorContainerProtocol` and its subclasses inherit these operations via the new mixins.
Replaced implicit pytree operations triggered by .copy() with an explicit
pytree.tree_flatten and pytree.tree_unflatten roundtrip.
Refactor and expand the test suite for `TensorAnnotated` subclassing.
This significantly improves coverage and robustness by:
- Introducing dedicated test fixtures and helper assertion functions.
- Restructuring positive and negative test cases for better clarity.
- Adding new tests for cross-device handling, method inheritance, and shape
  consistency.
- Covering complex edge cases like deep inheritance chains, diamond patterns,
  and empty base classes.
- Ensuring proper preservation of tensor identity and properties through
  PyTree operations.
- Validating correct exclusion of non-annotated attributes in mixed
  inheritance.
Removed outdated and redundant sections from the TensorContainer class
docstring, such as "Usage Patterns" and "Limitations". Consolidated and
rephrased core concepts like Shape Management, Device Management, PyTree
Integration, and Torch Function Override for clarity.

Added a new section explaining the concept of "Metadata" within the
container. Significantly improved the docstring for `unsafe_construction`
to provide a detailed explanation of its purpose and usage, including a
concrete example. Simplified the "Subclassing Guide" for better readability.
Adds detailed Google-style docstrings to the internal PyTree integration methods
(`_pytree_flatten`, `_pytree_flatten_with_keys_fn`, `_pytree_unflatten`,
`_tree_map`, `tree_map_with_path`) and validation methods
(`_is_shape_compatible`, `_is_device_compatible`, `_validate_shape`,
`_validate_device`, `_validate`).
Add comprehensive Google-style docstrings to the module, classes, and
methods within `TensorAnnotated` to enhance readability and maintainability.
…efault slots=True

The extensive docstrings for `TensorDataClass` and its methods have been
streamlined for improved readability and conciseness.
@mctigger
mctigger merged commit ca43392 into main Sep 29, 2025
5 checks passed
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.

1 participant