Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Free memory earlier by changing function scope #606

Merged
merged 1 commit into from
Nov 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions cubed/primitive/blockwise.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,8 @@ def apply_blockwise(out_coords: List[int], *, config: BlockwiseSpec) -> None:
# lithops needs params to be lists not tuples, so convert back
out_coords_tuple = tuple(out_coords)

# get array chunks for input keys, preserving any nested list structure
args = []
get_chunk_config = partial(get_chunk, config=config)
out_key = ("out",) + out_coords_tuple # array name is ignored by key_function
in_keys = config.key_function(out_key)
for in_key in in_keys:
arg = map_nested(get_chunk_config, in_key)
args.append(arg)
results = get_results_in_different_scope(out_coords, config=config)

results = config.function(*args)
# if blockwise function is a regular function (not a generator) that doesn't return multiple values then make it iterable
if not inspect.isgeneratorfunction(config.function) and not isinstance(
results, tuple
Expand All @@ -107,6 +99,24 @@ def apply_blockwise(out_coords: List[int], *, config: BlockwiseSpec) -> None:
config.writes_list[i].open()[out_chunk_key] = result


def get_results_in_different_scope(out_coords: List[int], *, config: BlockwiseSpec):
# wrap function call in a function so that args go out of scope (and free memory) as soon as results are returned

# lithops needs params to be lists not tuples, so convert back
out_coords_tuple = tuple(out_coords)

# get array chunks for input keys, preserving any nested list structure
args = []
get_chunk_config = partial(get_chunk, config=config)
out_key = ("out",) + out_coords_tuple # array name is ignored by key_function
in_keys = config.key_function(out_key)
for in_key in in_keys:
arg = map_nested(get_chunk_config, in_key)
args.append(arg)

return config.function(*args)


def key_to_slices(
key: Tuple[int, ...], arr: T_ZarrArray, chunks: Optional[T_Chunks] = None
) -> Tuple[slice, ...]:
Expand Down
Loading