Skip to content

Conversation

@kinianlo
Copy link
Contributor

@kinianlo kinianlo commented Jul 3, 2025

Problem

tensor.Box.free_symbols very slow for large tensors. This is because a isinstance is called for each entry in the tensor.

Solution

This PR optimise the free_symbols method such that numerical arrays are not recursively searched for symbols.

import time

from lambeq import Symbol
from lambeq.backend.tensor import Box, Dim
import numpy as np

sym = Symbol('x')

d = 1000
box_with_sym = Box('box_sym', Dim(d), Dim(d))
box_without_sym = Box('box_no_sym', Dim(d), Dim(d))

box_with_sym.data = np.random.rand(d, d).astype(object)
box_without_sym.data = np.random.rand(d, d)
box_with_sym.data[0, 0] = sym

start = time.time()
symbols = box_with_sym.free_symbols
end = time.time()
print(f"Time taken: {end - start:.6f} seconds")

start = time.time()
symbols = box_without_sym.free_symbols
end = time.time()
print(f"Time taken: {end - start:.6f} seconds")

without this PR

(With symbol) Time taken: 0.563968 seconds
(Without symbol) Time taken: 0.555081 seconds

with this PR

(With symbol) Time taken: 0.559249 seconds
(Without symbol) Time taken: 0.000064 seconds

@kinianlo kinianlo marked this pull request as ready for review July 3, 2025 22:45
@dimkart
Copy link
Contributor

dimkart commented Jul 11, 2025

@kinianlo Thanks for the PR, looks ready to be merged as soon as CI passes.

@kinianlo
Copy link
Contributor Author

kinianlo commented Jul 11, 2025

@kinianlo Thanks for the PR, looks ready to be merged as soon as CI passes.

Thanks @dimkart. I was trying to look into the CI errors but they don't seem to be related to the file changed in this PR.

@neiljdo neiljdo self-requested a review July 12, 2025 13:56
Copy link
Collaborator

@neiljdo neiljdo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thank you @kinianlo for this.

@neiljdo neiljdo merged commit cdd579b into Quantinuum:main Jul 14, 2025
9 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.

3 participants