Skip to content

COH-32065 - Use numpy package to improve performance of Vector.normalize() api #230

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

Merged
merged 3 commits into from
Apr 7, 2025
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ pymitter = ">=0.4,<1.1"
typing-extensions = ">=4.11,<4.14"
types-protobuf = "5.29.1.20250403"
pympler = "1.1"
numpy = "2.0.2"

[tool.poetry.dev-dependencies]
pytest = "~8.3"
Expand Down
25 changes: 7 additions & 18 deletions src/coherence/ai.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
# Copyright (c) 2022, 2024, Oracle and/or its affiliates.
# Copyright (c) 2022, 2025, Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at
# https://oss.oracle.com/licenses/upl.

from __future__ import annotations

import base64
import math
from abc import ABC
from collections import OrderedDict
from typing import Any, Dict, List, Optional, TypeVar, Union, cast

import jsonpickle
import numpy as np

from coherence.aggregator import EntryAggregator
from coherence.extractor import ValueExtractor
Expand Down Expand Up @@ -342,19 +342,8 @@ class Vectors:
EPSILON = 1e-30 # Python automatically handles float precision

@staticmethod
def normalize(array: List[float]) -> List[float]:
norm = 0.0
c_dim = len(array)

# Calculate the norm (sum of squares)
for v in array:
norm += v * v

# Compute the normalization factor (inverse of the square root of the sum of squares)
norm = 1.0 / (math.sqrt(norm) + Vectors.EPSILON)

# Apply the normalization factor to each element in the array
for i in range(c_dim):
array[i] = array[i] * norm

return array
def normalize(array: list[float]) -> list[float]:
np_array = np.array(array, dtype=np.float64)
norm = np.linalg.norm(np_array) + Vectors.EPSILON
normalized_array = np_array / norm
return normalized_array.tolist()