pymc-devs / pymc-devs/pytensor

support for `__len__`

Open
#2,151 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
Python
Stars
644
Forks
208
Avg merge
2d 14h
Merged PRs (30d)
16

Description

Len works on numpy

from numpy import array

vector = array([1, 2, 3])
len(vector)  # 3

matrix = array([    
    [1, 2], 
    [3, 2], 
    [5, 4],
])
len(matrix)  # 3

But not with pt.as_tensor_variable

from pytensor.tensor import as_tensor_variable as array

# Same as above

which results in:

[ins] In [100,000,000,000,000]: matrix
Out[100,000,000,000,000]: TensorConstant(TensorType(int64, shape=(3, 2)), data=array([[1, ... [5, 4]]))

[ins] In [100,000,000,000,001]: len(matrix)
----------------------------------------------------------------
TypeError                      Traceback (most recent call last)
Cell In[100,000,000,000,001], line 1
----> 1 len(matrix)

TypeError: object of type 'TensorConstant' has no len()

My usecase

import numpy as np

import pytensor.tensor as pt
import pymc as pm


def build_model(y) -> pm.Model:
    coords = {
        "idx": np.arange(len(y))
    }
    model = pm.Model(coords=coords)
    with model: 
        ...

    return model


model = build_model([1, 2, 3])
model = build_model(np.array([1, 2, 3]))
# Failure as above
model = build_model(pt.as_tensor_variable([1, 2, 3]))

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the pt.as_tensor_variable entry point and inspect how the resulting TensorConstant handles Python's len() operation. Use the issue's vector and matrix examples as checks, including the PyMC coords use case; done means len() works for tensor variables as it does for NumPy arrays.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, python
Domain
backend-api-design
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
50/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.