python_code
stringlengths 0
108k
|
---|
#!/usr/bin/env python3
"""Setup script"""
from pathlib import Path
import re
import os
import setuptools
if __name__ == "__main__":
# Read metadata from version.py
with Path("autofaiss/version.py").open(encoding="utf-8") as file:
metadata = dict(re.findall(r'__([a-z]+)__\s*=\s*"([^"]+)"', file.read()))
# Read description from README
with Path(Path(__file__).parent, "README.md").open(encoding="utf-8") as file:
long_description = file.read()
def _read_reqs(relpath):
fullpath = os.path.join(os.path.dirname(__file__), relpath)
with open(fullpath) as f:
return [s.strip() for s in f.readlines() if (s.strip() and not s.startswith("#"))]
_INSTALL_REQUIRES = _read_reqs("requirements.txt")
_TEST_REQUIRE = ["pytest"]
# Run setup
setuptools.setup(
name="autofaiss",
version=metadata["version"],
classifiers=[
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Intended Audience :: Developers",
],
long_description=long_description,
long_description_content_type="text/markdown",
description=long_description.split("\n")[0],
author=metadata["author"],
install_requires=_INSTALL_REQUIRES,
tests_require=_TEST_REQUIRE,
dependency_links=[],
entry_points={"console_scripts": ["autofaiss = autofaiss.external.quantize:main"]},
data_files=[(".", ["requirements.txt", "README.md"])],
packages=setuptools.find_packages(),
url="https://github.com/criteo/autofaiss",
)
|
"""Check version and git tag script."""
from pathlib import Path
import re
import sys
import subprocess
if __name__ == "__main__":
# Read package version
with Path("autofaiss/version.py").open(encoding="utf-8") as file:
metadata = dict(re.findall(r'__([a-z]+)__\s*=\s*"([^"]+)"', file.read()))
version = metadata["version"]
# Read git tag
with subprocess.Popen(["git", "describe", "--tags"], stdout=subprocess.PIPE) as process:
tagged_version = process.communicate()[0].strip().decode(encoding="utf-8")
# Exit depending on version and tagged_version
if version == tagged_version:
print(f"Tag and version are the same ({version}) !")
sys.exit(0)
else:
print(f"Tag {tagged_version} and version {version} are not the same !")
sys.exit(1)
|
"""Test version."""
from autofaiss import version
def test_version():
"""Test version."""
assert len(version.__version__.split(".")) == 3
assert isinstance(version.__author__, str)
|
""" test utils functions """
# pylint: disable= invalid-name
import numpy as np
import pytest
from autofaiss.utils.array_functions import multi_array_split
def test_multi_array_split():
"""test multi_array_split fct number 1"""
assert len(list(multi_array_split([np.zeros((123, 2)), np.zeros((123, 5))], 41))) == 41
@pytest.mark.parametrize("seed", list(range(1, 10)))
def test_multi_array_split_2(seed):
"""test multi_array_split fct number 2"""
np.random.seed(seed)
length = np.random.randint(1, 100)
nb_chunk = np.random.randint(1, length + 1)
dim1 = np.random.randint(10)
dim2 = np.random.randint(10)
a = np.random.randint(0, 10000, (length, dim1))
b = np.random.randint(0, 10000, (length, dim2))
c = list(multi_array_split([a, b], nb_chunk))
a2 = np.concatenate([x[0] for x in c])
b2 = np.concatenate([x[1] for x in c])
assert np.all(a == a2)
assert np.all(b == b2)
|
import numpy as np
from autofaiss import build_index, tune_index, score_index
def test_scoring_tuning():
embs = np.ones((100, 512), "float32")
index, index_infos = build_index(embs, save_on_disk=False)
index = tune_index(index, index_infos["index_key"], save_on_disk=False)
infos = score_index(index, embs, save_on_disk=False)
|
import logging
import faiss
import numpy as np
import pytest
from autofaiss.external.optimize import (
get_min_param_value_for_best_neighbors_coverage,
get_optimal_hyperparameters,
get_optimal_index_keys_v2,
)
from autofaiss.external.quantize import build_index
from autofaiss.indices.index_factory import index_factory
from autofaiss.indices.index_utils import set_search_hyperparameters, speed_test_ms_per_query
LOGGER = logging.getLogger(__name__)
@pytest.mark.parametrize("nb_vectors", [10, 900, 9_000, 90_000, 900_000, 9_000_000])
@pytest.mark.parametrize("dim_vector", [10, 100])
@pytest.mark.parametrize("max_index_memory_usage", ["1K", "1M", "1G"])
def test_get_optimal_index_keys_v2(nb_vectors: int, dim_vector: int, max_index_memory_usage: str) -> None:
# Check that should_be_memory_mappable returns only ivf indices
for index_key in get_optimal_index_keys_v2(
nb_vectors, dim_vector, max_index_memory_usage, should_be_memory_mappable=True
):
# LOGGER.debug(f"nb_vectors={nb_vectors}, max_mem={max_index_memory_usage} -> {index_key}")
assert "IVF" in index_key
@pytest.mark.parametrize(
"nb_vectors, use_gpu, expected",
[
(999_999, False, "IVF4096,Flat"),
(1_000_000, False, "OPQ256_768,IVF16384_HNSW32,PQ256x8"),
(1_000_000, True, "IVF16384,Flat"),
],
)
def test_get_optimal_index_keys_v2_with_large_nb_vectors(nb_vectors: int, use_gpu, expected: str):
assert (
get_optimal_index_keys_v2(
nb_vectors=nb_vectors,
dim_vector=512,
max_index_memory_usage="50G",
should_be_memory_mappable=True,
ivf_flat_threshold=1_000_000,
use_gpu=use_gpu,
)[0]
== expected
)
def test_get_min_param_value_for_best_neighbors_coverage() -> None:
"""
Check that get_min_param_value_for_best_neighbors_coverage works as expected.
"""
# We only test on hnsw because this index is fast to build
embeddings = np.float32(np.random.rand(30001, 512))
hyperparameter_str_from_param = lambda ef_search: f"efSearch={ef_search}"
parameter_range = list(range(16, 2 ** 14))
index, _ = build_index(embeddings, save_on_disk=False, index_key="HNSW15")
embeddings = np.float32(np.random.rand(66, 512))
for targeted_nb_neighbors_to_query in [10, 3000, 31000]:
for targeted_coverage in [0.99, 0.5]:
# Compute max coverage ratio
param_str = hyperparameter_str_from_param(parameter_range[-1])
set_search_hyperparameters(index, param_str)
ind = index.search(embeddings, targeted_nb_neighbors_to_query)[1]
max_coverage = 1 - np.sum(ind == -1) / ind.size
# Compute optimal param value
param = get_min_param_value_for_best_neighbors_coverage(
index, parameter_range, hyperparameter_str_from_param, targeted_nb_neighbors_to_query
)
set_search_hyperparameters(index, hyperparameter_str_from_param(param))
# Compute coverage for optimal param value
ind = index.search(embeddings, targeted_nb_neighbors_to_query)[1]
coverage = 1 - np.sum(ind == -1) / ind.size
epsilon = 0.02
# Check that the coverage is close to the targeted coverage
if max_coverage == 1:
assert coverage >= targeted_coverage - epsilon
else:
assert coverage >= 0.95 * max_coverage - epsilon
@pytest.mark.skip(reason="This test takes too long to run (11m)")
@pytest.mark.parametrize(
"index_key", ["OPQ64_128,IVF1024_HNSW32,PQ64x8", "OPQ64_128,IVF1024,PQ64x8", "IVF256,Flat", "HNSW15"]
)
@pytest.mark.parametrize("d", [100])
def test_get_optimal_hyperparameters(index_key: str, d: int) -> None:
"""
Check that get_optimal_hyperparameters returns an hyperparameter string that
match with the speed constraint of the index.
"""
# commented out because slow to run
# nb_vectors_list = [1000, 100000]
# target_speed_ms_list = [0.5, 1, 10, 50]
nb_vectors_list = [10000]
target_speed_ms_list = [0.5]
min_ef_search = 32
use_gpu = False
embeddings = np.float32(np.random.rand(max(nb_vectors_list), d))
index = index_factory(d, index_key, faiss.METRIC_INNER_PRODUCT)
index.train(embeddings[:10000])
for nb_vec_in, target_nb_vec in zip([0] + nb_vectors_list, nb_vectors_list):
index.add(embeddings[nb_vec_in:target_nb_vec])
assert index.ntotal == target_nb_vec
for target_speed_ms in target_speed_ms_list:
hyperparameters_str = get_optimal_hyperparameters(
index, index_key, target_speed_ms, use_gpu, max_timeout_per_iteration_s=1.0, min_ef_search=min_ef_search
)
set_search_hyperparameters(index, hyperparameters_str, use_gpu)
avg_query_time_ms = speed_test_ms_per_query(index)
LOGGER.debug(
f"nb_vectors={target_nb_vec}, max_mem={index_key}, target_speed_ms {target_speed_ms} -> avg_query_time_ms: {avg_query_time_ms}, {hyperparameters_str}"
)
if (
"nprobe=1" == hyperparameters_str
or "nprobe=1," in hyperparameters_str
or "efSearch=1" == hyperparameters_str
or "efSearch=1," in hyperparameters_str
or f"efSearch={min_ef_search}," in hyperparameters_str
or f"efSearch={min_ef_search}" == hyperparameters_str
):
# Target_speed is too constraining
assert avg_query_time_ms >= target_speed_ms * 0.90 - 0.25
continue
assert avg_query_time_ms <= 1.05 * target_speed_ms + 0.25 # ms
|
import logging
import os
import py
import random
from tempfile import TemporaryDirectory, NamedTemporaryFile
from typing import Tuple, List
import faiss
import numpy as np
import pandas as pd
import pyarrow.parquet as pq
import pytest
from numpy.testing import assert_array_equal
LOGGER = logging.getLogger(__name__)
from autofaiss import build_index, build_partitioned_indexes
logging.basicConfig(level=logging.DEBUG)
# hide py4j DEBUG from pyspark, otherwise, there will be too many useless debugging output
# https://stackoverflow.com/questions/37252527/how-to-hide-py4j-java-gatewayreceived-command-c-on-object-id-p0
logging.getLogger("py4j").setLevel(logging.ERROR)
def build_test_collection_numpy(
tmpdir: py.path, min_size=2, max_size=10000, dim=512, nb_files=5, tmpdir_name: str = "autofaiss_numpy"
):
tmp_path = tmpdir.mkdir(tmpdir_name)
sizes = [random.randint(min_size, max_size) for _ in range(nb_files)]
all_arrays = []
file_paths = []
for i, size in enumerate(sizes):
arr = np.random.rand(size, dim).astype("float32")
all_arrays.append(arr)
file_path = os.path.join(tmp_path, f"{str(i)}.npy")
file_paths.append(file_path)
np.save(file_path, arr)
all_arrays = np.vstack(all_arrays)
return str(tmp_path), sizes, dim, all_arrays, file_paths
def build_test_collection_parquet(
tmpdir: py.path,
min_size=2,
max_size=10000,
dim=512,
nb_files=5,
tmpdir_name: str = "autofaiss_parquet",
consecutive_ids=False,
):
tmp_path = tmpdir.mkdir(tmpdir_name)
sizes = [random.randint(min_size, max_size) for _ in range(nb_files)]
dim = dim
all_dfs = []
file_paths = []
n = 0
for i, size in enumerate(sizes):
arr = np.random.rand(size, dim).astype("float32")
if consecutive_ids:
# ids would be consecutive from 0 to N-1
ids = list(range(n, n + size))
else:
ids = np.random.randint(max_size * nb_files * 10, size=size)
df = pd.DataFrame({"embedding": list(arr), "id": ids})
all_dfs.append(df)
file_path = os.path.join(tmp_path, f"{str(i)}.parquet")
df.to_parquet(file_path)
file_paths.append(file_path)
n += len(df)
all_dfs = pd.concat(all_dfs)
return str(tmp_path), sizes, dim, all_dfs, file_paths
def test_quantize(tmpdir):
min_size = random.randint(1, 100)
max_size = random.randint(min_size, 10240)
dim = random.randint(1, 100)
nb_files = random.randint(1, 5)
tmp_dir, sizes, dim, expected_array, _ = build_test_collection_numpy(
tmpdir, min_size=min_size, max_size=max_size, dim=dim, nb_files=nb_files
)
output_numpy_index = os.path.join(tmpdir.strpath, "numpy_knn.index")
output_numpy_index_infos = os.path.join(tmpdir.strpath, "numpy_knn_infos.json")
build_index(
embeddings=tmp_dir,
file_format="npy",
index_path=output_numpy_index,
index_infos_path=output_numpy_index_infos,
max_index_query_time_ms=10.0,
max_index_memory_usage="1G",
current_memory_available="2G",
)
output_numpy_index_faiss = faiss.read_index(output_numpy_index)
assert output_numpy_index_faiss.ntotal == len(expected_array)
tmp_dir, sizes, dim, expected_df, _ = build_test_collection_parquet(
tmpdir, min_size=min_size, max_size=max_size, dim=dim, nb_files=nb_files
)
index_path = os.path.join(tmpdir.strpath, "parquet_knn.index")
index_infos_path = os.path.join(tmpdir.strpath, "infos.json")
build_index(
embeddings=tmp_dir,
file_format="parquet",
embedding_column_name="embedding",
index_path=index_path,
index_infos_path=index_infos_path,
max_index_query_time_ms=10.0,
max_index_memory_usage="1G",
current_memory_available="2G",
)
output_parquet_index_faiss = faiss.read_index(index_path)
assert output_parquet_index_faiss.ntotal == len(expected_df)
def test_quantize_with_ids(tmpdir):
min_size = random.randint(1, 100)
max_size = random.randint(min_size, 10240)
dim = random.randint(1, 100)
nb_files = random.randint(1, 5)
tmp_dir, sizes, dim, expected_df, _ = build_test_collection_parquet(
tmpdir, min_size=min_size, max_size=max_size, dim=dim, nb_files=nb_files
)
index_path = os.path.join(tmpdir.strpath, "parquet_knn.index")
index_infos_path = os.path.join(tmpdir.strpath, "infos.json")
ids_path = os.path.join(tmpdir.strpath, "ids")
build_index(
embeddings=tmp_dir,
file_format="parquet",
embedding_column_name="embedding",
index_path=index_path,
index_infos_path=index_infos_path,
ids_path=ids_path,
max_index_query_time_ms=10.0,
max_index_memory_usage="1G",
current_memory_available="2G",
id_columns=["id"],
)
output_parquet_index_faiss = faiss.read_index(index_path)
output_parquet_ids = pq.read_table(ids_path).to_pandas()
assert output_parquet_index_faiss.ntotal == len(expected_df)
expected_df["i"] = np.arange(start=0, stop=len(expected_df))
pd.testing.assert_frame_equal(
output_parquet_ids.reset_index(drop=True), expected_df[["id", "i"]].reset_index(drop=True)
)
def test_quantize_with_pyspark(tmpdir):
min_size = random.randint(1, 100)
max_size = random.randint(min_size, 10240)
dim = random.randint(1, 100)
nb_files = random.randint(1, 5)
tmp_dir, _, _, expected_df, _ = build_test_collection_parquet(
tmpdir, min_size=min_size, max_size=max_size, dim=dim, nb_files=nb_files
)
index_parquet_path = os.path.join(tmpdir.strpath, "parquet_knn.index")
output_parquet_index_infos = os.path.join(tmpdir.strpath, "infos.json")
ids_path = os.path.join(tmpdir.strpath, "ids")
temporary_indices_folder = os.path.join(tmpdir.strpath, "distributed_autofaiss_indices")
build_index(
embeddings=tmp_dir,
distributed="pyspark",
file_format="parquet",
temporary_indices_folder=temporary_indices_folder,
index_infos_path=output_parquet_index_infos,
ids_path=ids_path,
max_index_memory_usage="1G",
current_memory_available="2G",
id_columns=["id"],
embedding_column_name="embedding",
index_path=index_parquet_path,
)
output_parquet_index_faiss = faiss.read_index(index_parquet_path)
output_parquet_ids = pq.read_table(ids_path).to_pandas()
assert output_parquet_index_faiss.ntotal == len(expected_df)
pd.testing.assert_frame_equal(
output_parquet_ids[["id"]].reset_index(drop=True), expected_df[["id"]].reset_index(drop=True)
)
tmp_dir, _, _, expected_array, _ = build_test_collection_numpy(
tmpdir, min_size=min_size, max_size=max_size, dim=dim, nb_files=nb_files
)
output_numpy_index = os.path.join(tmpdir.strpath, "numpy_knn.index")
output_numpy_index_infos = os.path.join(tmpdir.strpath, "numpy_knn_infos.json")
build_index(
embeddings=tmp_dir,
distributed="pyspark",
file_format="npy",
temporary_indices_folder=temporary_indices_folder,
index_infos_path=output_numpy_index_infos,
max_index_memory_usage="1G",
current_memory_available="2G",
embedding_column_name="embedding",
index_path=output_numpy_index,
)
output_numpy_index_faiss = faiss.read_index(output_numpy_index)
assert output_numpy_index_faiss.ntotal == len(expected_array)
def test_quantize_with_multiple_inputs(tmpdir):
min_size = random.randint(1, 100)
max_size = random.randint(min_size, 10240)
dim = random.randint(1, 100)
nb_files = random.randint(1, 5)
tmp_dir1, _, _, expected_df1, _ = build_test_collection_parquet(
tmpdir, min_size=min_size, max_size=max_size, dim=dim, nb_files=nb_files, tmpdir_name="autofaiss_parquet1"
)
tmp_dir2, _, _, expected_df2, _ = build_test_collection_parquet(
tmpdir, min_size=min_size, max_size=max_size, dim=dim, nb_files=nb_files, tmpdir_name="autofaiss_parquet2"
)
expected_df = pd.concat([expected_df1, expected_df2])
index_parquet_path = os.path.join(tmpdir.strpath, "parquet_knn.index")
output_parquet_index_infos = os.path.join(tmpdir.strpath, "infos.json")
build_index(
embeddings=[tmp_dir1, tmp_dir2],
file_format="parquet",
embedding_column_name="embedding",
index_path=index_parquet_path,
index_infos_path=output_parquet_index_infos,
max_index_query_time_ms=10.0,
max_index_memory_usage="1G",
current_memory_available="2G",
)
output_parquet_index_faiss = faiss.read_index(index_parquet_path)
assert output_parquet_index_faiss.ntotal == len(expected_df)
def test_quantize_with_empty_file():
with TemporaryDirectory() as tmp_dir:
with NamedTemporaryFile() as tmp_file:
df = pd.DataFrame({"embedding": [], "id": []})
df.to_parquet(os.path.join(tmp_dir, tmp_file.name))
with pytest.raises(ValueError):
build_index(embeddings=tmp_dir, file_format="parquet", embedding_column_name="embedding")
def test_quantize_with_empty_and_non_empty_files(tmpdir):
with TemporaryDirectory() as tmp_empty_dir:
with NamedTemporaryFile() as tmp_file:
df = pd.DataFrame({"embedding": [], "id": []})
df.to_parquet(os.path.join(tmp_empty_dir, tmp_file.name))
min_size = random.randint(1, 100)
max_size = random.randint(min_size, 10240)
dim = random.randint(1, 100)
nb_files = random.randint(1, 5)
tmp_non_empty_dir, _, _, expected_df, _ = build_test_collection_parquet(
tmpdir,
min_size=min_size,
max_size=max_size,
dim=dim,
nb_files=nb_files,
tmpdir_name="autofaiss_parquet1",
)
index_parquet_path = os.path.join(tmpdir.strpath, "parquet_knn.index")
output_parquet_index_infos = os.path.join(tmpdir.strpath, "infos.json")
build_index(
embeddings=[tmp_empty_dir, tmp_non_empty_dir],
file_format="parquet",
embedding_column_name="embedding",
index_path=index_parquet_path,
index_infos_path=output_parquet_index_infos,
max_index_query_time_ms=10.0,
max_index_memory_usage="1G",
current_memory_available="2G",
)
output_parquet_index_faiss = faiss.read_index(index_parquet_path)
assert output_parquet_index_faiss.ntotal == len(expected_df)
def test_index_correctness_in_distributed_mode(tmpdir):
min_size = 8000
max_size = 10240
dim = 512
nb_files = 5
# parquet
tmp_dir, _, _, expected_df, _ = build_test_collection_parquet(
tmpdir, min_size=min_size, max_size=max_size, dim=dim, nb_files=nb_files, consecutive_ids=True
)
temporary_indices_folder = os.path.join(tmpdir.strpath, "distributed_autofaiss_indices")
ids_path = os.path.join(tmpdir.strpath, "ids")
index, _ = build_index(
embeddings=tmp_dir,
distributed="pyspark",
file_format="parquet",
temporary_indices_folder=temporary_indices_folder,
max_index_memory_usage="600MB",
current_memory_available="700MB",
embedding_column_name="embedding",
index_key="IVF1,Flat",
should_be_memory_mappable=True,
metric_type="l2",
ids_path=ids_path,
save_on_disk=True,
id_columns=["id"],
)
query = faiss.rand((1, dim))
distances, ids = index.search(query, k=9)
ground_truth_index = faiss.index_factory(dim, "IVF1,Flat")
expected_array = np.stack(expected_df["embedding"])
ground_truth_index.train(expected_array)
ground_truth_index.add(expected_array)
ground_truth_distances, ground_truth_ids = ground_truth_index.search(query, k=9)
ids_mappings = pd.read_parquet(ids_path)["id"]
assert len(ids_mappings) == len(expected_df)
assert_array_equal(ids_mappings.iloc[ids[0, :]].to_numpy(), ids[0, :])
assert_array_equal(ids, ground_truth_ids)
# numpy
tmp_dir, _, _, expected_array, _ = build_test_collection_numpy(
tmpdir, min_size=min_size, max_size=max_size, dim=dim, nb_files=nb_files
)
index, _ = build_index(
embeddings=tmp_dir,
distributed="pyspark",
file_format="npy",
temporary_indices_folder=temporary_indices_folder,
max_index_memory_usage="400MB",
current_memory_available="500MB",
embedding_column_name="embedding",
index_key="IVF1,Flat",
should_be_memory_mappable=True,
metric_type="l2",
)
query = faiss.rand((1, dim))
distances, ids = index.search(query, k=9)
ground_truth_index = faiss.index_factory(dim, "IVF1,Flat")
ground_truth_index.train(expected_array)
ground_truth_index.add(expected_array)
ground_truth_distances, ground_truth_ids = ground_truth_index.search(query, k=9)
assert_array_equal(ids, ground_truth_ids)
def _search_from_multiple_indices(index_paths, query, k):
all_distances, all_ids, NB_QUERIES = [], [], 1
for rest_index_file in index_paths:
index = faiss.read_index(rest_index_file)
distances, ids = index.search(query, k=k)
all_distances.append(distances)
all_ids.append(ids)
dists_arr = np.stack(all_distances, axis=1).reshape(NB_QUERIES, -1)
knn_ids_arr = np.stack(all_ids, axis=1).reshape(NB_QUERIES, -1)
sorted_k_indices = np.argsort(-dists_arr)[:, :k]
sorted_k_dists = np.take_along_axis(dists_arr, sorted_k_indices, axis=1)
sorted_k_ids = np.take_along_axis(knn_ids_arr, sorted_k_indices, axis=1)
return sorted_k_dists, sorted_k_ids
def _merge_indices(index_paths):
merged = faiss.read_index(index_paths[0])
for rest_index_file in index_paths[1:]:
index = faiss.read_index(rest_index_file)
faiss.merge_into(merged, index, shift_ids=False)
return merged
def test_index_correctness_in_distributed_mode_with_multiple_indices(tmpdir):
min_size = 20000
max_size = 40000
dim = 512
nb_files = 5
# parquet
tmp_dir, _, _, expected_df, _ = build_test_collection_parquet(
tmpdir, min_size=min_size, max_size=max_size, dim=dim, nb_files=nb_files, consecutive_ids=True
)
temporary_indices_folder = os.path.join(tmpdir.strpath, "distributed_autofaiss_indices")
ids_path = os.path.join(tmpdir.strpath, "ids")
_, index_path2_metric_infos = build_index(
embeddings=tmp_dir,
distributed="pyspark",
file_format="parquet",
temporary_indices_folder=temporary_indices_folder,
max_index_memory_usage="2GB",
current_memory_available="500MB",
embedding_column_name="embedding",
index_key="IVF1,Flat",
should_be_memory_mappable=True,
ids_path=ids_path,
nb_indices_to_keep=2,
save_on_disk=True,
id_columns=["id"],
)
index_paths = sorted(index_path2_metric_infos.keys())
K, NB_QUERIES = 5, 1
query = faiss.rand((NB_QUERIES, dim))
ground_truth_index = faiss.index_factory(dim, "IVF1,Flat", faiss.METRIC_INNER_PRODUCT)
expected_array = np.stack(expected_df["embedding"])
ground_truth_index.train(expected_array)
ground_truth_index.add(expected_array)
_, ground_truth_ids = ground_truth_index.search(query, k=K)
ids_mappings = pd.read_parquet(ids_path)["id"]
assert len(ids_mappings) == len(expected_df)
assert_array_equal(ids_mappings.iloc[ground_truth_ids[0, :]].to_numpy(), ground_truth_ids[0, :])
_, sorted_k_ids = _search_from_multiple_indices(index_paths=index_paths, query=query, k=K)
merged = _merge_indices(index_paths)
_, ids = merged.search(query, k=K)
assert_array_equal(ids, ground_truth_ids)
assert_array_equal(sorted_k_ids, ground_truth_ids)
# numpy
tmp_dir, _, _, expected_array, _ = build_test_collection_numpy(
tmpdir, min_size=min_size, max_size=max_size, dim=dim, nb_files=nb_files
)
temporary_indices_folder = os.path.join(tmpdir.strpath, "distributed_autofaiss_indices")
_, index_path2_metric_infos = build_index(
embeddings=tmp_dir,
distributed="pyspark",
file_format="npy",
temporary_indices_folder=temporary_indices_folder,
max_index_memory_usage="2GB",
current_memory_available="500MB",
embedding_column_name="embedding",
index_key="IVF1,Flat",
should_be_memory_mappable=True,
nb_indices_to_keep=2,
)
ground_truth_index = faiss.index_factory(dim, "IVF1,Flat", faiss.METRIC_INNER_PRODUCT)
ground_truth_index.train(expected_array)
ground_truth_index.add(expected_array)
_, ground_truth_ids = ground_truth_index.search(query, k=K)
index_paths = sorted(index_path2_metric_infos.keys())
_, sorted_k_ids = _search_from_multiple_indices(index_paths=index_paths, query=query, k=K)
merged = _merge_indices(index_paths)
_, ids = merged.search(query, k=K)
assert_array_equal(ids, ground_truth_ids)
assert_array_equal(sorted_k_ids, ground_truth_ids)
def test_build_partitioned_indexes(tmpdir):
embedding_root_dir = tmpdir.mkdir("embeddings")
output_root_dir = tmpdir.mkdir("outputs")
temp_root_dir = tmpdir.strpath
small_partitions = [("partnerId=123", 1), ("partnerId=44", 2)]
big_partitions = [("partnerId=22", 3)]
all_partitions = small_partitions + big_partitions
expected_embeddings, partitions = _create_partitioned_parquet_embedding_dataset(
embedding_root_dir, all_partitions, n_dimensions=3
)
nb_splits_per_big_index = 2
metrics = build_partitioned_indexes(
partitions=partitions,
output_root_dir=str(output_root_dir),
embedding_column_name="embedding",
id_columns=["id"],
temp_root_dir=str(temp_root_dir),
nb_splits_per_big_index=nb_splits_per_big_index,
big_index_threshold=3,
should_be_memory_mappable=True,
)
assert len(all_partitions) == len(metrics)
all_ids = []
for partition_name, partition_size in small_partitions:
index_path = os.path.join(output_root_dir, partition_name, "knn.index")
index = faiss.read_index(index_path)
assert partition_size == index.ntotal
ids_path = os.path.join(output_root_dir, partition_name, "ids")
ids = pq.read_table(ids_path).to_pandas()
all_ids.append(ids)
for partition_name, partition_size in big_partitions:
n_embeddings = 0
for i in range(nb_splits_per_big_index):
index_path = os.path.join(output_root_dir, partition_name, f"knn.index{i}")
index = faiss.read_index(index_path)
n_embeddings += index.ntotal
assert partition_size == n_embeddings
ids_path = os.path.join(output_root_dir, partition_name, "ids")
ids = pq.read_table(ids_path).to_pandas()
all_ids.append(ids)
all_ids = pd.concat(all_ids)
pd.testing.assert_frame_equal(
all_ids[["id"]].reset_index(drop=True), expected_embeddings[["id"]].reset_index(drop=True)
)
def _create_partitioned_parquet_embedding_dataset(
embedding_root_dir: str, partition_sizes: List[Tuple[str, int]], n_dimensions: int = 512
):
partition_embeddings = []
partitions = []
n = 0
for i, (partition_name, partition_size) in enumerate(partition_sizes):
embeddings = np.random.rand(partition_size, n_dimensions).astype("float32")
ids = list(range(n, n + partition_size))
df = pd.DataFrame({"embedding": list(embeddings), "id": ids})
partition_embeddings.append(df)
partition_dir = os.path.join(embedding_root_dir, partition_name)
os.mkdir(partition_dir)
partitions.append(partition_dir)
file_path = os.path.join(partition_dir, f"{str(i)}.parquet")
df.to_parquet(file_path)
n += len(df)
all_embeddings = pd.concat(partition_embeddings)
return all_embeddings, partitions
|
import numpy as np
from autofaiss import build_index
def test_np_quantize():
embs = np.ones((100, 512), "float32")
index, _ = build_index(embs, save_on_disk=False)
_, I = index.search(embs, 1)
assert I[0][0] == 0
|
from autofaiss.external.build import estimate_memory_required_for_index_creation
#
# def test_estimate_memory_required_for_index_creation():
# needed_memory, _ = estimate_memory_required_for_index_creation(
# nb_vectors=4_000_000_000,
# vec_dim=512,
# index_key="OPQ4_28,IVF131072_HNSW32,PQ4x8",
# max_index_memory_usage="50G",
# )
# assert needed_memory == 100
|
""" Test that the memory efficient flat index give same results as the faiss flat index """
import time
import faiss
import numpy as np
import pytest
from autofaiss.indices.memory_efficient_flat_index import MemEfficientFlatIndex
@pytest.fixture(name="prod_emb")
def fixture_prod_emb():
"""generate random database vectors"""
np.random.seed(15)
return np.random.rand(5003, 99).astype(np.float32)
@pytest.fixture(name="user_emb")
def fixture_user_emb():
"""generate random query vectors"""
np.random.seed(17)
return np.random.rand(501, 99).astype(np.float32)
# pylint: disable too-many-arguments redefined-outer-name
@pytest.mark.parametrize("dataset_size", [1, 10, 3000, 5003])
@pytest.mark.parametrize("batch_size", [1000, 10000])
@pytest.mark.parametrize("nb_query_vectors", [1, 10, 100])
@pytest.mark.parametrize("k", [1, 10, 101])
def test_memory_efficient_flat_index(prod_emb, user_emb, dataset_size, batch_size, nb_query_vectors, k):
"""Test our flat index vs. FAISS flat index"""
dim = prod_emb.shape[-1] # vectors dim
# Test our flat index with faiss batches
start_time = time.time()
flat_index = MemEfficientFlatIndex(dim, "IP")
flat_index.add(prod_emb[:dataset_size])
D_our, I_our = flat_index.search(user_emb[:nb_query_vectors], k, batch_size=batch_size)
print(f"Our flat index: {time.time()-start_time:.2f} (bias if all the dataset is already in RAM)")
# Test our flat index with numpy batches
start_time = time.time()
flat_index = MemEfficientFlatIndex(dim, "IP")
flat_index.add(prod_emb[:dataset_size])
D_our_numpy, I_our_numpy = flat_index.search_numpy(user_emb[:nb_query_vectors], k, batch_size=batch_size)
print(f"Our numpy flat index: {time.time()-start_time:.2f} (bias if all the dataset is already in RAM)")
# Test FAISS flat index
start_time = time.time()
brute = faiss.IndexFlatIP(dim)
# pylint: disable=no-value-for-parameter
brute.add(prod_emb[:dataset_size])
D_faiss, I_faiss = brute.search(user_emb[:nb_query_vectors], k)
print(f"Faiss flat index: {time.time()-start_time:.2f} (no bias since all the dataset is already in RAM)")
# Check that the vectors we can't retrive are the same
assert np.all((I_faiss == -1) == (I_our == -1))
assert np.all((I_faiss == -1) == (I_our_numpy == -1))
mask = I_faiss == -1
# Check that all the distances are equal and in the same order
assert np.all((np.abs(D_our - D_faiss) <= 2 ** -13) | mask)
assert np.all((np.abs(D_our_numpy - D_faiss) <= 2 ** -13) | mask)
# Check the order is the same as Faiss -> it is not, but no big dead
# since the computation always give the same results (repetability works)
assert np.all(I_our == I_faiss) or True
assert np.all(I_our_numpy == I_faiss) or True
|
from autofaiss.indices.distributed import _batch_loader
def test_batch_loader():
for input_size in range(2, 500):
for output_size in range(1, input_size):
batches = list(_batch_loader(nb_batches=output_size, total_size=input_size))
# test output size is expected
assert len(batches) == output_size
# test no empty batch
assert all(batch[1] <= input_size - 1 for batch in batches)
# test on continuous between batches
assert all(prev_end == next_start for (_, _, prev_end), (_, next_start, _) in zip(batches, batches[1:]))
# test last element is covered
assert batches[-1][2] >= input_size
# test range sum
assert sum(end - start for _, start, end in batches) == input_size
|
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath(".."))
# -- Project information -----------------------------------------------------
project = "autofaiss"
copyright = "2020, Criteo"
author = "Criteo reco team"
# The full version, including alpha/beta/rc tags
release = "1.0.0"
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.intersphinx",
"sphinxcontrib.napoleon",
"sphinx.ext.viewcode",
"sphinx_autodoc_typehints",
"sphinx.ext.doctest",
"nbsphinx",
]
nbsphinx_execute = "never"
intersphinx_mapping = {
"python": ("https://docs.python.org/3/", None),
"numpy": ("https://docs.scipy.org/doc/numpy/", None),
"scipy": ("https://docs.scipy.org/doc/scipy/reference/", None),
"deepr": ("https://criteo.github.io/deepr/", None),
}
autosummary_generate = True
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build/**", ".env/**"]
pygments_style = "sphinx"
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "sphinx_rtd_theme"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
source_suffix = [".rst"]
# -- Extension configuration -------------------------------------------------
|
"""
An example of running autofaiss by pyspark to produce N indices.
You need to install pyspark before using the following example.
"""
from typing import Dict
import faiss
import numpy as np
from autofaiss import build_index
# You'd better create a spark session before calling build_index,
# otherwise, a spark session would be created by autofaiss with the least configuration.
_, index_path2_metric_infos = build_index(
embeddings="hdfs://root/path/to/your/embeddings/folder",
distributed="pyspark",
file_format="parquet",
temporary_indices_folder="hdfs://root/tmp/distributed_autofaiss_indices",
current_memory_available="10G",
max_index_memory_usage="100G",
nb_indices_to_keep=10,
)
index_paths = sorted(index_path2_metric_infos.keys())
###########################################
# Use case 1: merging 10 indices into one #
###########################################
merged = faiss.read_index(index_paths[0])
for rest_index_file in index_paths[1:]:
index = faiss.read_index(rest_index_file)
faiss.merge_into(merged, index, shift_ids=False)
with open("merged-knn.index", "wb") as f:
faiss.write_index(merged, faiss.PyCallbackIOWriter(f.write))
########################################
# Use case 2: searching from N indices #
########################################
K, DIM, all_distances, all_ids, NB_QUERIES = 5, 512, [], [], 2
queries = faiss.rand((NB_QUERIES, DIM))
for rest_index_file in index_paths:
index = faiss.read_index(rest_index_file)
distances, ids = index.search(queries, k=K)
all_distances.append(distances)
all_ids.append(ids)
dists_arr = np.stack(all_distances, axis=1).reshape(NB_QUERIES, -1)
knn_ids_arr = np.stack(all_ids, axis=1).reshape(NB_QUERIES, -1)
sorted_k_indices = np.argsort(-dists_arr)[:, :K]
sorted_k_dists = np.take_along_axis(dists_arr, sorted_k_indices, axis=1)
sorted_k_ids = np.take_along_axis(knn_ids_arr, sorted_k_indices, axis=1)
print(f"{K} nearest distances: {sorted_k_dists}")
print(f"{K} nearest ids: {sorted_k_ids}")
############################################
# Use case 3: on disk merging of N indices #
############################################
# using faiss.merge_ondisk (https://github.com/facebookresearch/faiss/blob/30abcd6a865afef7cf86df7e8b839a41b5161505/contrib/ondisk.py )
# https://github.com/facebookresearch/faiss/blob/151e3d7be54aec844b6328dc3e7dd0b83fcfa5bc/demos/demo_ondisk_ivf.py
# to merge indices on disk without using memory
# this is useful in particular to use a very large index with almost no memory usage.
from faiss.contrib.ondisk import merge_ondisk
import faiss
block_fnames = index_paths
empty_index = faiss.read_index(block_fnames[0], faiss.IO_FLAG_MMAP)
empty_index.ntotal = 0
merge_ondisk(empty_index, block_fnames, "merged_index.ivfdata")
faiss.write_index(empty_index, "populated.index")
pop = faiss.read_index("populated.index", faiss.IO_FLAG_ONDISK_SAME_DIR)
########################################################
# Use case 4: use N indices using HStackInvertedLists #
########################################################
# This allows using N indices as a single combined index
# without changing anything on disk or loading anything to memory
# it works well but it's slower than first using merge_ondisk
# because it requires explore N pieces of inverted list for each
# list to explore
import os
class CombinedIndex:
"""
combines a set of inverted lists into a hstack
adds these inverted lists to an empty index that contains
the info on how to perform searches
"""
def __init__(self, invlist_fnames):
ilv = faiss.InvertedListsPtrVector()
for fname in invlist_fnames:
if os.path.exists(fname):
index = faiss.read_index(fname, faiss.IO_FLAG_MMAP)
index_ivf = faiss.extract_index_ivf(index)
il = index_ivf.invlists
index_ivf.own_invlists = False
else:
raise FileNotFoundError
ilv.push_back(il)
self.big_il = faiss.HStackInvertedLists(ilv.size(), ilv.data())
ntotal = self.big_il.compute_ntotal()
self.index = faiss.read_index(invlist_fnames[0], faiss.IO_FLAG_MMAP)
index_ivf = faiss.extract_index_ivf(self.index)
index_ivf.replace_invlists(self.big_il, True)
index_ivf.ntotal = self.index.ntotal = ntotal
def search(self, x, k):
D, I = self.index.search(x, k)
return D, I
index = CombinedIndex(index_paths)
index.search(queries, K)
|
"""
Given a partitioned dataset of embeddings, create an index per partition
"""
import os
from autofaiss import build_partitioned_indexes
from pyspark.sql import SparkSession # pylint: disable=import-outside-toplevel
def create_spark_session():
# PEX file packaging your Python environment and accessible on yarn by all executors
os.environ["PYSPARK_PYTHON"] = "/home/ubuntu/autofaiss.pex"
spark = (
SparkSession.builder.config("spark.submit.deployMode", "client")
.config("spark.executorEnv.PEX_ROOT", "./.pex")
.config("spark.task.cpus", "32")
.config("spark.driver.port", "5678")
.config("spark.driver.blockManager.port", "6678")
.config("spark.driver.host", "172.31.35.188")
.config("spark.driver.bindAddress", "172.31.35.188")
.config("spark.executor.memory", "18G") # make sure to increase this if you're using more cores per executor
.config(
"spark.executor.memoryOverhead", "8G"
) # Memory overhead is needed for Faiss as indexes are built outside of the JVM/Java heap
.config(
"spark.executor.cores", "32"
) # Faiss is multi-threaded so increasing the number of cores will speed up index creation
.config("spark.task.maxFailures", "100")
.appName("Partitioned indexes")
.getOrCreate()
)
return spark
spark = create_spark_session()
partitions = [
"/root/directory/to/partitions/A",
"/root/directory/to/partitions/B",
"/root/directory/to/partitions/C",
"/root/directory/to/partitions/D",
...,
]
# Parameter `big_index_threshold` is used to to define the minimum size of a big index.
# Partitions with >= `big_index_threshold` embeddings will be created in a distributed
# way and resulting index will be split into `nb_splits_per_big_index` smaller indexes.
# Partitions with less than `big_index_threshold` embeddings will not be created in a
# distributed way and resulting index will be composed of only one index.
index_metrics = build_partitioned_indexes(
partitions=partitions,
output_root_dir="/output/root/directory",
embedding_column_name="embedding",
nb_splits_per_big_index=2,
big_index_threshold=5_000_000,
)
|
import faiss
import numpy as np
from autofaiss import build_index
embeddings = np.float32(np.random.rand(5000, 100))
# Example on how to build a memory-mapped index and load it from disk
_, index_infos = build_index(
embeddings,
save_on_disk=True,
should_be_memory_mappable=True,
index_path="my_index_folder/knn.index",
max_index_memory_usage="4G",
max_index_query_time_ms=50,
)
index = faiss.read_index("my_index_folder/knn.index", faiss.IO_FLAG_MMAP | faiss.IO_FLAG_READ_ONLY)
|
from autofaiss import build_index
import numpy as np
embeddings = np.float32(np.random.rand(100, 512))
index, index_infos = build_index(embeddings, save_on_disk=False)
_, I = index.search(embeddings, 1)
print(I)
|
import numpy as np
from autofaiss import build_index, tune_index, score_index
embs = np.float32(np.random.rand(100, 512))
index, index_infos = build_index(embs, save_on_disk=False)
index = tune_index(index, index_infos["index_key"], save_on_disk=False)
infos = score_index(index, embs, save_on_disk=False)
|
"""
An example of running autofaiss by pyspark.
You need to install pyspark before using the following example.
"""
from autofaiss import build_index
# You'd better create a spark session before calling build_index,
# otherwise, a spark session would be created by autofaiss with the least configuration.
index, index_infos = build_index(
embeddings="hdfs://root/path/to/your/embeddings/folder",
distributed="pyspark",
file_format="parquet",
temporary_indices_folder="hdfs://root/tmp/distributed_autofaiss_indices",
)
|
from autofaiss import build_index
build_index(
embeddings="embeddings",
index_path="knn.index",
index_infos_path="infos.json",
max_index_memory_usage="4G",
current_memory_available="5G",
)
|
# pylint: disable=all
__version__ = "2.15.5"
__author__ = "Criteo"
MAJOR = __version__.split(".")[0]
MINOR = __version__.split(".")[1]
PATCH = __version__.split(".")[2]
|
# pylint: disable=unused-import,missing-docstring
from autofaiss.external.quantize import build_index, score_index, tune_index, build_partitioned_indexes
from autofaiss.version import __author__, __version__
|
""" function to compute different kind of recalls """
from typing import List, Optional
import faiss
import numpy as np
def r_recall_at_r_single(
query: np.ndarray,
ground_truth: np.ndarray,
other_index: faiss.Index,
r_max: int = 40,
eval_item_ids: Optional[np.ndarray] = None,
) -> List[int]:
"""Compute an R-recall@R array for each R in range [1, R_max]"""
# O(r_max)
_, inds = other_index.search(np.expand_dims(query, 0), r_max)
res = inds[0]
recall_count = []
s_true = set()
s_pred = set()
tot = 0
for p_true, p_pred in zip(ground_truth[:r_max], res):
if eval_item_ids is not None and p_pred != -1:
p_pred = eval_item_ids[p_pred]
if p_true == p_pred and p_true != -1:
tot += 1
else:
if p_true in s_pred and p_true != -1:
tot += 1
if p_pred in s_true and p_pred != -1:
tot += 1
s_true.add(p_true)
s_pred.add(p_pred)
recall_count.append(tot)
return recall_count
def r_recall_at_r(
query: np.ndarray,
ground_truth: np.ndarray,
other_index: faiss.Index,
r_max: int = 40,
eval_item_ids: Optional[np.ndarray] = None,
) -> np.ndarray:
"""Compute an R-recall@R array for each R in range [1, R_max] for
a single query.
"""
# O(r_max)
r_lim = min(r_max, other_index.ntotal)
if r_lim <= 0:
return np.ones((max(r_max, 0),))
total = np.zeros((r_max,))
for i in range(query.shape[0]):
# If the ground truth contains -1 (missing elements), the recall definition must change.
# We should divide by the number of elements possible to retrieve, not r_lim
r_lim_fix = min(r_lim, np.min(np.where(ground_truth[i] == -1)[0])) if -1 in ground_truth[i] else r_lim
res_for_one = r_recall_at_r_single(
query[i], ground_truth[i], other_index, r_max, eval_item_ids
) / np.concatenate((np.arange(1, r_lim_fix + 1, 1), np.full(r_max - r_lim_fix, r_lim_fix)))
total += np.array(res_for_one)
return total / query.shape[0]
def one_recall_at_r_single(
query: np.ndarray,
ground_truth: np.ndarray,
other_index: faiss.Index,
r_max: int = 40,
eval_item_ids: Optional[np.ndarray] = None,
) -> List[int]:
"""
Compute an 1-recall@R array for each R in range [1, r_max] for
a single query.
"""
# O(r_max)
_, inds = other_index.search(np.expand_dims(query, 0), 1)
first = inds[0][0]
if eval_item_ids is not None and first != -1:
first = eval_item_ids[first]
# return empty array if no product is found by other_index
if first == -1:
return [0 for _ in ground_truth[:r_max]]
recall_count = []
seen = False
for p_true in ground_truth[:r_max]:
if p_true == first:
seen = True
recall_count.append(1 if seen else 0)
return recall_count
def one_recall_at_r(
query: np.ndarray,
ground_truth: np.ndarray,
other_index: faiss.Index,
r_max: int = 40,
eval_item_ids: Optional[np.ndarray] = None,
) -> np.ndarray:
"""Compute an 1-recall@R array for each R in range [1, r_max]"""
# O(r_max)
if r_max <= 0:
return np.zeros((0,))
_, first = other_index.search(query, 1)
if eval_item_ids is not None:
first = np.vectorize(lambda e: eval_item_ids[e] if e != -1 else -1)(first) # type: ignore
recall_array = np.cumsum((ground_truth[:, :r_max] == first) & (first != -1), axis=-1)
avg_recall = np.mean(recall_array, axis=0)
return avg_recall
|
""" function to compute the reconstruction error """
from typing import Optional
import numpy as np
import faiss
def reconstruction_error(before, after, avg_norm_before: Optional[float] = None) -> float:
"""Computes the average reconstruction error"""
diff = np.mean(np.linalg.norm(after - before, axis=1))
if avg_norm_before is None:
avg_norm_before = np.mean(np.linalg.norm(before, axis=1))
return diff / avg_norm_before
def quantize_vec_without_modifying_index(index: faiss.Index, vecs: np.ndarray) -> np.ndarray:
"""Quantizes a batch of vectors if the index given uses quantization"""
try:
return index.sa_decode(index.sa_encode(vecs))
except (TypeError, RuntimeError): # error if the index doesn't use quantization
return vecs
|
""" functions to compare different indices """
import time
import numpy as np
from matplotlib import pyplot as plt
from tqdm import tqdm as tq
from autofaiss.indices.index_utils import format_speed_ms_per_query, get_index_size, speed_test_ms_per_query
from autofaiss.metrics.recalls import r_recall_at_r_single, one_recall_at_r_single
from autofaiss.utils.cast import cast_bytes_to_memory_string
def avg_speed_dict_ms_per_query(indices_dict, vectors, k_closest: int = 40, timeout_s: float = 5):
"""compute the average query speed of a dictionary of indices"""
speed_dict = {}
for index_key in indices_dict:
speed = speed_test_ms_per_query(indices_dict[index_key], vectors, k_closest, timeout_s)
speed_dict[index_key] = speed
return speed_dict
def index_sizes_in_bytes_dict(indices_dict):
"""compute sizes of indices in a dictionary of indices"""
size_dict = {}
for index_key in indices_dict:
size_dict[index_key] = get_index_size(indices_dict[index_key])
return size_dict
def benchmark_index(
indices_dict, gt_test, test_points, vectors_size_in_bytes, save_path=None, speed_dict=None, size_dict=None
):
"""
Compute recall curves for the indices.
"""
perfect_index_label = "perfect index"
if perfect_index_label not in indices_dict:
indices_dict[perfect_index_label] = None
if speed_dict:
speed_dict[perfect_index_label] = vectors_size_in_bytes
k_max = gt_test.shape[1]
plt.figure(figsize=(16, 8))
k_values = np.arange(0, k_max + 1)
avg_one_recall_at_r = {}
avg_r_recall_at_r = {}
timout_s = 5.0
comp_size = vectors_size_in_bytes
for index_key in tq(list(sorted(indices_dict.keys()))):
if index_key not in indices_dict:
continue
index = indices_dict[index_key]
if index_key == "Flat" or (index is None):
y_r_recall_at_r = np.arange(1, k_max + 1)
y_one_recall_at_r = np.ones(k_max)
tot = 1
else:
y_r_recall_at_r = np.zeros(k_max)
y_one_recall_at_r = np.zeros(k_max)
tot = 0
start_time = time.time()
for i, item in enumerate(test_points):
y_r_recall_at_r += np.array(r_recall_at_r_single(item, gt_test[i], index, k_max))
y_one_recall_at_r += np.array(one_recall_at_r_single(item, gt_test[i], index, k_max))
tot += 1
if time.time() - start_time > timout_s and tot > 150:
break
avg_r_recall_at_r[index_key] = y_r_recall_at_r / tot
avg_one_recall_at_r[index_key] = y_one_recall_at_r / tot
info_string = {index_key: "" for index_key in indices_dict}
initial_size_string = cast_bytes_to_memory_string(comp_size)
for index_key in indices_dict:
if index_key in speed_dict:
info_string[index_key] += f"avg speed: {format_speed_ms_per_query(speed_dict[index_key])}, "
if index_key in size_dict:
info_string[index_key] += (
f"(Size: {cast_bytes_to_memory_string(size_dict[index_key])} "
f"({(100*size_dict[index_key]/comp_size):.1f}% of {initial_size_string})"
)
plt.subplot(121)
for index_key in sorted(indices_dict.keys()):
if index_key not in indices_dict:
continue
label = f"{index_key:<30} Index, {info_string[index_key]}"
plt.plot(k_values, np.concatenate(([0], avg_r_recall_at_r[index_key])), label=label)
plt.xlabel("k, number of nearests items")
plt.ylabel("k-recall@k")
plt.vlines(40, 0, k_max)
plt.legend()
plt.tight_layout()
plt.subplot(122)
for index_key in sorted(indices_dict.keys()):
if index_key not in indices_dict:
continue
label = f"{index_key:<30} Index, {info_string[index_key]}"
plt.plot(k_values, np.concatenate(([0], 100 * avg_one_recall_at_r[index_key])), label=label)
plt.xlabel("k, number of nearests items")
plt.ylabel("1-Recall@k")
plt.vlines(100, 0, k_max)
plt.legend()
plt.tight_layout()
if save_path:
plt.savefig(save_path)
plt.show()
|
# pylint: disable=unused-import,missing-docstring
|
""" Common functions to build an index """
import logging
from typing import Dict, Optional, Tuple, Union, Callable, Any
import uuid
import re
import os
import tempfile
import fsspec
import faiss
import pandas as pd
from embedding_reader import EmbeddingReader
from autofaiss.external.optimize import optimize_and_measure_index, get_optimal_batch_size
from autofaiss.indices.index_utils import set_search_hyperparameters, initialize_direct_map, load_index
from autofaiss.utils.path import make_path_absolute
from autofaiss.utils.cast import cast_bytes_to_memory_string
logger = logging.getLogger("autofaiss")
def get_write_ids_df_to_parquet_fn(ids_root_dir: str) -> Callable[[pd.DataFrame, int], None]:
"""Create function to write ids from Pandas dataframe to parquet"""
def _write_ids_df_to_parquet_fn(ids: pd.DataFrame, batch_id: int):
filename = f"part-{batch_id:08d}-{uuid.uuid1()}.parquet"
output_file = os.path.join(ids_root_dir, filename) # type: ignore
with fsspec.open(output_file, "wb") as f:
logger.debug(f"Writing id DataFrame to file {output_file}")
ids.to_parquet(f, index=False)
return _write_ids_df_to_parquet_fn
def get_optimize_index_fn(
embedding_reader: EmbeddingReader,
index_key: str,
index_path: Optional[str],
index_infos_path: Optional[str],
use_gpu: bool,
save_on_disk: bool,
max_index_query_time_ms: float,
min_nearest_neighbors_to_retrieve: int,
make_direct_map: bool,
index_param: Optional[str],
) -> Callable[[faiss.Index, str], Dict]:
"""Create function to optimize index by choosing best hyperparameters and calculating metrics"""
def _optimize_index_fn(index: faiss.Index, index_suffix: str):
if make_direct_map:
initialize_direct_map(index)
cur_index_path = make_path_absolute(index_path) + index_suffix if index_path else None
cur_index_infos_path = make_path_absolute(index_infos_path) + index_suffix if index_infos_path else None
if any(re.findall(r"OPQ\d+_\d+,IVF\d+_HNSW\d+,PQ\d+", index_key)):
set_search_hyperparameters(index, f"nprobe={64},efSearch={128},ht={2048}", use_gpu)
metric_infos = optimize_and_measure_index(
embedding_reader,
index,
cur_index_infos_path,
index_key,
index_param,
cur_index_path,
max_index_query_time_ms=max_index_query_time_ms,
min_nearest_neighbors_to_retrieve=min_nearest_neighbors_to_retrieve,
save_on_disk=save_on_disk,
use_gpu=use_gpu,
)
return metric_infos
return _optimize_index_fn
def add_embeddings_to_index_local(
embedding_reader: EmbeddingReader,
trained_index_or_path: Union[faiss.Index, str],
memory_available_for_adding: str,
embedding_ids_df_handler: Optional[Callable[[pd.DataFrame, int], Any]] = None,
index_optimizer: Callable = None,
add_embeddings_with_ids: bool = False,
) -> Tuple[Optional[faiss.Index], Optional[Dict[str, str]]]:
"""Add embeddings to index from driver"""
vec_dim = embedding_reader.dimension
batch_size = get_optimal_batch_size(vec_dim, memory_available_for_adding)
logger.info(
f"Using a batch size of {batch_size} (memory overhead {cast_bytes_to_memory_string(batch_size * vec_dim * 4)})"
)
with tempfile.TemporaryDirectory() as tmp_dir:
if isinstance(trained_index_or_path, str):
local_index_path = os.path.join(tmp_dir, "index")
trained_index = load_index(trained_index_or_path, local_index_path)
else:
trained_index = trained_index_or_path
for batch_id, (vec_batch, ids_batch) in enumerate(embedding_reader(batch_size=batch_size)):
if add_embeddings_with_ids:
trained_index.add_with_ids(vec_batch, ids_batch["i"].to_numpy())
else:
trained_index.add(vec_batch)
if embedding_ids_df_handler:
embedding_ids_df_handler(ids_batch, batch_id)
metric_infos = index_optimizer(trained_index, "") if index_optimizer else None # type: ignore
return trained_index, metric_infos
|
""" functions that fixe faiss index_factory function """
# pylint: disable=invalid-name
import re
from typing import Optional
import faiss
def index_factory(d: int, index_key: str, metric_type: int, ef_construction: Optional[int] = None):
"""
custom index_factory that fix some issues of
faiss.index_factory with inner product metrics.
"""
if metric_type == faiss.METRIC_INNER_PRODUCT:
# make the index described by the key
if any(re.findall(r"OPQ\d+_\d+,IVF\d+,PQ\d+", index_key)):
params = [int(x) for x in re.findall(r"\d+", index_key)]
cs = params[3] # code size (in Bytes if nbits=8)
nbits = params[4] if len(params) == 5 else 8 # default value
ncentroids = params[2]
out_d = params[1]
M_OPQ = params[0]
quantizer = faiss.index_factory(out_d, "Flat", metric_type)
assert quantizer.metric_type == metric_type
index_ivfpq = faiss.IndexIVFPQ(quantizer, out_d, ncentroids, cs, nbits, metric_type)
assert index_ivfpq.metric_type == metric_type
index_ivfpq.own_fields = True
quantizer.this.disown() # pylint: disable = no-member
opq_matrix = faiss.OPQMatrix(d, M=M_OPQ, d2=out_d)
# opq_matrix.niter = 50 # Same as default value
index = faiss.IndexPreTransform(opq_matrix, index_ivfpq)
elif any(re.findall(r"OPQ\d+_\d+,IVF\d+_HNSW\d+,PQ\d+", index_key)):
params = [int(x) for x in re.findall(r"\d+", index_key)]
M_HNSW = params[3]
cs = params[4] # code size (in Bytes if nbits=8)
nbits = params[5] if len(params) == 6 else 8 # default value
ncentroids = params[2]
out_d = params[1]
M_OPQ = params[0]
quantizer = faiss.IndexHNSWFlat(out_d, M_HNSW, metric_type)
if ef_construction is not None and ef_construction >= 1:
quantizer.hnsw.efConstruction = ef_construction
assert quantizer.metric_type == metric_type
index_ivfpq = faiss.IndexIVFPQ(quantizer, out_d, ncentroids, cs, nbits, metric_type)
assert index_ivfpq.metric_type == metric_type
index_ivfpq.own_fields = True
quantizer.this.disown() # pylint: disable = no-member
opq_matrix = faiss.OPQMatrix(d, M=M_OPQ, d2=out_d)
# opq_matrix.niter = 50 # Same as default value
index = faiss.IndexPreTransform(opq_matrix, index_ivfpq)
elif any(re.findall(r"Pad\d+,IVF\d+_HNSW\d+,PQ\d+", index_key)):
params = [int(x) for x in re.findall(r"\d+", index_key)]
out_d = params[0]
M_HNSW = params[2]
cs = params[3] # code size (in Bytes if nbits=8)
nbits = params[4] if len(params) == 5 else 8 # default value
ncentroids = params[1]
remapper = faiss.RemapDimensionsTransform(d, out_d, True)
quantizer = faiss.IndexHNSWFlat(out_d, M_HNSW, metric_type)
if ef_construction is not None and ef_construction >= 1:
quantizer.hnsw.efConstruction = ef_construction
index_ivfpq = faiss.IndexIVFPQ(quantizer, out_d, ncentroids, cs, nbits, metric_type)
index_ivfpq.own_fields = True
quantizer.this.disown() # pylint: disable = no-member
index = faiss.IndexPreTransform(remapper, index_ivfpq)
elif any(re.findall(r"HNSW\d+", index_key)):
params = [int(x) for x in re.findall(r"\d+", index_key)]
M_HNSW = params[0]
index = faiss.IndexHNSWFlat(d, M_HNSW, metric_type)
assert index.metric_type == metric_type
elif index_key == "Flat" or any(re.findall(r"IVF\d+,Flat", index_key)):
index = faiss.index_factory(d, index_key, metric_type)
else:
index = faiss.index_factory(d, index_key, metric_type)
raise ValueError(
(
"Be careful, faiss might not create what you expect when using the "
"inner product similarity metric, remove this line to try it anyway. "
"Happened with index_key: " + str(index_key)
)
)
else:
index = faiss.index_factory(d, index_key, metric_type)
return index
|
""" useful functions to apply on an index """
import os
import time
from functools import partial
from itertools import chain, repeat
from multiprocessing.pool import ThreadPool
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Dict, Optional, Union, List, Tuple
import logging
from faiss import extract_index_ivf
import faiss
import fsspec
import numpy as np
logger = logging.getLogger("autofaiss")
def get_index_size(index: faiss.Index) -> int:
"""Returns the size in RAM of a given index"""
with NamedTemporaryFile() as tmp_file:
faiss.write_index(index, tmp_file.name)
size_in_bytes = Path(tmp_file.name).stat().st_size
return size_in_bytes
def speed_test_ms_per_query(
index: faiss.Index, query: Optional[np.ndarray] = None, ksearch: int = 40, timout_s: Union[float, int] = 5.0
) -> float:
"""Evaluate the average speed in milliseconds of the index without using batch"""
nb_samples = 2_000
if query is None:
query = np.random.rand(nb_samples, index.d).astype("float32")
count = 0
nb_repeat = 1 + (nb_samples - 1) // query.shape[0]
start_time = time.perf_counter()
for one_query in chain.from_iterable(repeat(query, nb_repeat)):
_, _ = index.search(np.expand_dims(one_query, 0), ksearch)
count += 1
if time.perf_counter() - start_time > timout_s:
break
return (time.perf_counter() - start_time) / count * 1000.0
def search_speed_test(
index: faiss.Index, query: Optional[np.ndarray] = None, ksearch: int = 40, timout_s: Union[float, int] = 10.0
) -> Dict[str, float]:
"""return the average and 99p search speed"""
nb_samples = 2_000
if query is None:
query = np.random.rand(nb_samples, index.d).astype("float32")
test_start_time_s = time.perf_counter()
speed_list_ms = [] # in milliseconds
nb_repeat = 1 + (nb_samples - 1) // query.shape[0]
for one_query in chain.from_iterable(repeat(query, nb_repeat)):
start_time_s = time.perf_counter() # high precision
_, _ = index.search(np.expand_dims(one_query, 0), ksearch)
end_time_s = time.perf_counter()
search_time_ms = 1000.0 * (end_time_s - start_time_s)
speed_list_ms.append(search_time_ms)
if time.perf_counter() - test_start_time_s > timout_s:
break
speed_list_ms2 = np.array(speed_list_ms)
# avg2 = 1000 * (time.perf_counter() - test_start_time_s) / len(speed_list_ms)
speed_infos = {
"avg_search_speed_ms": np.average(speed_list_ms2),
"99p_search_speed_ms": np.quantile(speed_list_ms2, 0.99),
}
return speed_infos
def format_speed_ms_per_query(speed: float) -> str:
"""format the speed (ms/query) into a nice string"""
return f"{speed:.2f} ms/query"
def quantize_vec_without_modifying_index(index: faiss.Index, vecs: np.ndarray) -> np.ndarray:
"""qantize a batch of vectors"""
quantized_vecs = index.sa_decode(index.sa_encode(vecs))
return quantized_vecs
def set_search_hyperparameters(index: faiss.Index, param_str: str, use_gpu: bool = False) -> None:
"""set hyperparameters to an index"""
# depends on installed faiss version # pylint: disable=no-member
params = faiss.ParameterSpace() if not use_gpu else faiss.GpuParameterSpace()
params.set_index_parameters(index, param_str)
def get_index_from_bytes(index_bytes: Union[bytearray, bytes]) -> faiss.Index:
"""Transforms a bytearray containing a faiss index into the corresponding object."""
with NamedTemporaryFile(delete=False) as output_file:
output_file.write(index_bytes)
tmp_name = output_file.name
b = faiss.read_index(tmp_name)
os.remove(tmp_name)
return b
def get_bytes_from_index(index: faiss.Index) -> bytearray:
"""Transforms a faiss index into a bytearray."""
with NamedTemporaryFile(delete=False) as output_file:
faiss.write_index(index, output_file.name)
tmp_name = output_file.name
with open(tmp_name, "rb") as index_file:
b = index_file.read()
os.remove(tmp_name)
return bytearray(b)
def parallel_download_indices_from_remote(
fs: fsspec.AbstractFileSystem, indices_file_paths: List[str], dst_folder: str
):
"""Download small indices in parallel."""
def _download_one(src_dst_path: Tuple[str, str], fs: fsspec.AbstractFileSystem):
src_path, dst_path = src_dst_path
try:
fs.get(src_path, dst_path)
except Exception as e:
raise Exception(f"Failed to download {src_path} to {dst_path}") from e
if len(indices_file_paths) == 0:
return
os.makedirs(dst_folder, exist_ok=True)
dst_paths = [os.path.join(dst_folder, os.path.split(p)[-1]) for p in indices_file_paths]
src_dest_paths = zip(indices_file_paths, dst_paths)
with ThreadPool(min(16, len(indices_file_paths))) as pool:
for _ in pool.imap_unordered(partial(_download_one, fs=fs), src_dest_paths):
pass
def initialize_direct_map(index: faiss.Index) -> None:
nested_index = extract_index_ivf(index) if isinstance(index, faiss.swigfaiss.IndexPreTransform) else index
# Make direct map is only implemented for IndexIVF and IndexBinaryIVF, see built file faiss/swigfaiss.py
if isinstance(nested_index, (faiss.swigfaiss.IndexIVF, faiss.swigfaiss.IndexBinaryIVF)):
nested_index.make_direct_map()
def save_index(index: faiss.Index, root_dir: str, index_filename: str) -> str:
"""Save index"""
fs = fsspec.core.url_to_fs(root_dir, use_listings_cache=False)[0]
fs.mkdirs(root_dir, exist_ok=True)
output_index_path = os.path.join(root_dir, index_filename)
with fsspec.open(output_index_path, "wb").open() as f:
faiss.write_index(index, faiss.PyCallbackIOWriter(f.write))
return output_index_path
def load_index(index_src_path: str, index_dst_path: str) -> faiss.Index:
fs = fsspec.core.url_to_fs(index_src_path, use_listings_cache=False)[0]
try:
fs.get(index_src_path, index_dst_path)
except Exception as e:
raise Exception(f"Failed to download index from {index_src_path} to {index_dst_path}") from e
return faiss.read_index(index_dst_path)
|
# pylint: disable=unused-import,missing-docstring
|
"""
Building the index with pyspark.
"""
import math
import multiprocessing
import os
import logging
from tempfile import TemporaryDirectory
import tempfile
from typing import Dict, Optional, Iterator, Tuple, Callable, Any, Union, List
from functools import partial
from multiprocessing.pool import ThreadPool
import faiss
import fsspec
import pandas as pd
from embedding_reader import EmbeddingReader
from tqdm import tqdm
from autofaiss.external.metadata import IndexMetadata
from autofaiss.external.optimize import get_optimal_batch_size
from autofaiss.indices.build import get_write_ids_df_to_parquet_fn, get_optimize_index_fn, add_embeddings_to_index_local
from autofaiss.indices.index_utils import (
get_index_from_bytes,
get_bytes_from_index,
parallel_download_indices_from_remote,
load_index,
save_index,
)
from autofaiss.utils.path import make_path_absolute, extract_partition_name_from_path
from autofaiss.utils.cast import cast_memory_to_bytes, cast_bytes_to_memory_string
from autofaiss.utils.decorators import Timeit
from autofaiss.indices.training import create_and_train_index_from_embedding_dir, TrainedIndex
logger = logging.getLogger("autofaiss")
def _generate_suffix(batch_id: int, nb_batches: int) -> str:
suffix_width = int(math.log10(nb_batches)) + 1
return str(batch_id).zfill(suffix_width)
def _generate_small_index_file_name(batch_id: int, nb_batches: int) -> str:
return "index_" + _generate_suffix(batch_id, nb_batches)
def _add_index(
start: int,
end: int,
broadcasted_trained_index_or_path,
memory_available_for_adding: str,
embedding_reader: EmbeddingReader,
batch_id: int,
small_indices_folder: str,
nb_batches: int,
num_cores: Optional[int] = None,
embedding_ids_df_handler: Optional[Callable[[pd.DataFrame, int], Any]] = None,
):
"""
Add a batch of embeddings on trained index and save this index.
Parameters
----------
start: int
Start position of this batch
end: int
End position of this batch
broadcasted_trained_index_or_path: pyspark.Broadcast or str
Broadcasted trained index or path to a trained index
memory_available_for_adding: str
Memory available for adding embeddings
embedding_reader: EmbeddingReader
Embedding reader
batch_id: int
Batch id
small_indices_folder: str
The folder where we save all the small indices
num_cores: int
Number of CPU cores (not Vcores)
embedding_ids_df_handler: Optional[Callable[[pd.DataFrame, int], Any]]
The function that handles the embeddings Ids when id_columns is given
"""
if num_cores is None:
num_cores = multiprocessing.cpu_count()
faiss.omp_set_num_threads(num_cores)
with tempfile.TemporaryDirectory() as tmp_dir:
# load empty trained index
if isinstance(broadcasted_trained_index_or_path, str):
local_index_path = os.path.join(tmp_dir, "index")
empty_index = load_index(broadcasted_trained_index_or_path, local_index_path)
else:
empty_index = get_index_from_bytes(broadcasted_trained_index_or_path.value)
batch_size = get_optimal_batch_size(embedding_reader.dimension, memory_available_for_adding)
ids_total = []
for (vec_batch, ids_batch) in embedding_reader(batch_size=batch_size, start=start, end=end):
consecutive_ids = ids_batch["i"].to_numpy()
# using add_with_ids makes it possible to have consecutive and unique ids over all the N indices
empty_index.add_with_ids(vec_batch, consecutive_ids)
if embedding_ids_df_handler:
ids_total.append(ids_batch)
if embedding_ids_df_handler:
embedding_ids_df_handler(pd.concat(ids_total), batch_id)
save_index(empty_index, small_indices_folder, _generate_small_index_file_name(batch_id, nb_batches))
def _get_pyspark_active_session():
"""Reproduce SparkSession.getActiveSession() available since pyspark 3.0."""
import pyspark # pylint: disable=import-outside-toplevel
# pylint: disable=protected-access
ss: Optional[pyspark.sql.SparkSession] = pyspark.sql.SparkSession._instantiatedSession # mypy: ignore
if ss is None:
logger.info("No pyspark session found, creating a new one!")
ss = (
pyspark.sql.SparkSession.builder.config("spark.driver.memory", "16G")
.master("local[1]")
.appName("Distributed autofaiss")
.config("spark.submit.deployMode", "client")
.getOrCreate()
)
return ss
def _batch_loader(nb_batches: int, total_size: int) -> Iterator[Tuple[int, int, int]]:
"""Yield [batch id, batch start position, batch end position (excluded)]"""
# Thanks to https://stackoverflow.com/a/2135920
batch_size, mod = divmod(total_size, nb_batches)
for batch_id in range(nb_batches):
start = batch_size * batch_id + min(batch_id, mod)
end = batch_size * (batch_id + 1) + min(batch_id + 1, mod)
yield batch_id, start, end
def _merge_index(
small_indices_folder: str,
nb_batches: int,
batch_id: Optional[int] = None,
start: Optional[int] = None,
end: Optional[int] = None,
max_size_on_disk: str = "50GB",
tmp_output_folder: Optional[str] = None,
index_optimizer: Callable = None,
) -> Tuple[faiss.Index, Dict[str, str]]:
"""
Merge all the indices in `small_indices_folder` into single one.
Also run optimization when `index_optimizer` is given.
Returns the merged index and the metric
"""
fs = _get_file_system(small_indices_folder)
small_indices_files = sorted(fs.ls(small_indices_folder, detail=False))
small_indices_files = small_indices_files[start:end]
if len(small_indices_files) == 0:
raise ValueError(f"No small index is saved in {small_indices_folder}")
def _merge_from_local(merged: Optional[faiss.Index] = None) -> faiss.Index:
local_file_paths = [
os.path.join(local_indices_folder, filename) for filename in sorted(os.listdir(local_indices_folder))
]
if merged is None:
merged = faiss.read_index(local_file_paths[0])
start_index = 1
else:
start_index = 0
for rest_index_file in tqdm(local_file_paths[start_index:]):
# if master and executor are the same machine, rest_index_file could be the folder for stage2
# so, we have to check whether it is file or not
if os.path.isfile(rest_index_file):
index = faiss.read_index(rest_index_file)
faiss.merge_into(merged, index, shift_ids=False)
return merged
# estimate index size by taking the first index
first_index_file = small_indices_files[0]
first_index_size = fs.size(first_index_file)
max_sizes_in_bytes = cast_memory_to_bytes(max_size_on_disk)
nb_files_each_time = max(1, int(max_sizes_in_bytes / first_index_size))
merged_index = None
n = len(small_indices_files)
nb_iterations = max(math.ceil(n / nb_files_each_time), 1)
with Timeit("-> Merging small indices", indent=4):
with tqdm(total=nb_iterations) as pbar:
for i in range(nb_iterations):
to_downloads = small_indices_files[i * nb_files_each_time : min(n, (i + 1) * nb_files_each_time)]
with TemporaryDirectory() as local_indices_folder:
parallel_download_indices_from_remote(
fs=fs, indices_file_paths=to_downloads, dst_folder=local_indices_folder
)
merged_index = _merge_from_local(merged_index)
pbar.update(1)
if batch_id is not None and tmp_output_folder is not None:
if index_optimizer is not None:
metric_infos = index_optimizer(merged_index, index_suffix=_generate_suffix(batch_id, nb_batches))
else:
metric_infos = None
save_index(merged_index, tmp_output_folder, _generate_small_index_file_name(batch_id, nb_batches))
else:
metric_infos = None
return merged_index, metric_infos
def _get_file_system(path: str) -> fsspec.AbstractFileSystem:
return fsspec.core.url_to_fs(path, use_listings_cache=False)[0]
def _merge_to_n_indices(spark_session, n: int, src_folder: str, dst_folder: str, index_optimizer: Callable = None):
"""Merge all the indices from src_folder into n indices, and return the folder for the next stage, as well as the metrics"""
fs = _get_file_system(src_folder)
nb_indices_on_src_folder = len(fs.ls(src_folder, detail=False))
if nb_indices_on_src_folder <= n and index_optimizer is None:
# no need to merge
return src_folder, None
merge_batches = _batch_loader(nb_batches=n, total_size=nb_indices_on_src_folder)
rdd = spark_session.sparkContext.parallelize(merge_batches, n)
def merge(x):
_, metrics = _merge_index(
small_indices_folder=src_folder,
nb_batches=n,
batch_id=x[0],
start=x[1],
end=x[2],
tmp_output_folder=dst_folder,
index_optimizer=index_optimizer,
) # type: ignore
return metrics
metrics_rdd = rdd.map(merge)
metrics = list(metrics_rdd.collect())
if index_optimizer is not None:
metrics_dict = {metric_info["index_path"]: metric_info for metric_info in metrics} # type: ignore
else:
metrics_dict = None # type: ignore
for file in fs.ls(src_folder, detail=False):
if fs.isfile(file):
fs.rm(file)
return dst_folder, metrics_dict
def add_embeddings_to_index_distributed(
trained_index_or_path: Union[faiss.Index, str],
embedding_reader: EmbeddingReader,
memory_available_for_adding: str,
nb_cores: Optional[int] = None,
temporary_indices_folder="hdfs://root/tmp/distributed_autofaiss_indices",
embedding_ids_df_handler: Optional[Callable[[pd.DataFrame, int], Any]] = None,
nb_indices_to_keep: int = 1,
index_optimizer: Optional[Callable] = None,
) -> Tuple[Optional[faiss.Index], Optional[Dict[str, str]]]:
"""
Create indices by pyspark.
Parameters
----------
trained_index_or_path: trained faiss.Index or path to a trained faiss index
Trained faiss index
embedding_reader: EmbeddingReader
Embedding reader.
memory_available_for_adding: str
Memory available for adding embeddings.
nb_cores: int
Number of CPU cores per executor
temporary_indices_folder: str
Folder to save the temporary small indices
embedding_ids_df_handler: Optional[Callable[[pd.DataFrame, int], Any]]
The function that handles the embeddings Ids when id_columns is given
nb_indices_to_keep: int
Number of indices to keep at most after the merging step
index_optimizer: Optional[Callable]
The function that optimizes the index
"""
temporary_indices_folder = make_path_absolute(temporary_indices_folder)
fs = _get_file_system(temporary_indices_folder)
if fs.exists(temporary_indices_folder):
fs.rm(temporary_indices_folder, recursive=True)
stage1_folder = temporary_indices_folder.rstrip("/") + "/stage-1"
ss = _get_pyspark_active_session()
# Broadcast index
broadcasted_trained_index_or_path = (
trained_index_or_path
if isinstance(trained_index_or_path, str)
else ss.sparkContext.broadcast(get_bytes_from_index(trained_index_or_path))
)
sc = ss._jsc.sc() # pylint: disable=protected-access
n_workers = len(sc.statusTracker().getExecutorInfos()) - 1
# maximum between the number of spark workers, 10M embeddings per task and the number of indices to keep
n_batches = min(
embedding_reader.count, max(n_workers, math.ceil(embedding_reader.count / (10 ** 7)), nb_indices_to_keep)
)
nb_indices_to_keep = min(nb_indices_to_keep, n_batches)
batches = _batch_loader(total_size=embedding_reader.count, nb_batches=n_batches)
rdd = ss.sparkContext.parallelize(batches, n_batches)
with Timeit("-> Adding indices", indent=2):
rdd.foreach(
lambda x: _add_index(
batch_id=x[0],
start=x[1],
end=x[2],
memory_available_for_adding=memory_available_for_adding,
broadcasted_trained_index_or_path=broadcasted_trained_index_or_path,
embedding_reader=embedding_reader,
small_indices_folder=stage1_folder,
num_cores=nb_cores,
embedding_ids_df_handler=embedding_ids_df_handler,
nb_batches=n_batches,
)
)
with Timeit("-> Merging indices", indent=2):
stage2_folder = temporary_indices_folder.rstrip("/") + "/stage-2"
next_stage_folder, _ = _merge_to_n_indices(
spark_session=ss, n=100, src_folder=stage1_folder, dst_folder=stage2_folder, index_optimizer=None
)
if nb_indices_to_keep == 1:
merged_index, _ = _merge_index(small_indices_folder=next_stage_folder, nb_batches=1)
if fs.exists(temporary_indices_folder):
fs.rm(temporary_indices_folder, recursive=True)
metrics = index_optimizer(merged_index, "") # type: ignore
return merged_index, metrics
else:
final_folder = temporary_indices_folder.rstrip("/") + "/final"
next_stage_folder, metrics = _merge_to_n_indices(
spark_session=ss,
n=nb_indices_to_keep,
src_folder=next_stage_folder,
dst_folder=final_folder,
index_optimizer=index_optimizer,
)
if fs.exists(temporary_indices_folder):
fs.rm(temporary_indices_folder, recursive=True)
return None, metrics
def _add_embeddings_to_index(
add_embeddings_fn: Callable,
embedding_reader: EmbeddingReader,
output_root_dir: str,
index_key: str,
current_memory_available: str,
id_columns: Optional[List[str]],
max_index_query_time_ms: float,
min_nearest_neighbors_to_retrieve: int,
use_gpu: bool,
make_direct_map: bool,
) -> Tuple[Optional[faiss.Index], Optional[Dict[str, str]]]:
"""Add embeddings to index"""
# Define output folders
partition = extract_partition_name_from_path(embedding_reader.embeddings_folder)
output_dir = os.path.join(output_root_dir, partition)
index_dest_path = os.path.join(output_dir, "knn.index")
ids_dest_dir = os.path.join(output_dir, "ids")
index_infos_dest_path = os.path.join(output_dir, "index_infos.json")
# Compute memory available for adding embeddings to index
metadata = IndexMetadata(index_key, embedding_reader.count, embedding_reader.dimension, make_direct_map)
index_size = metadata.estimated_index_size_in_bytes()
memory_available_for_adding = cast_bytes_to_memory_string(
cast_memory_to_bytes(current_memory_available) - index_size
)
write_ids_df_to_parquet_fn = get_write_ids_df_to_parquet_fn(ids_root_dir=ids_dest_dir) if id_columns else None
optimize_index_fn = get_optimize_index_fn(
embedding_reader=embedding_reader,
index_key=index_key,
index_path=index_dest_path,
index_infos_path=index_infos_dest_path,
use_gpu=use_gpu,
save_on_disk=True,
max_index_query_time_ms=max_index_query_time_ms,
min_nearest_neighbors_to_retrieve=min_nearest_neighbors_to_retrieve,
make_direct_map=make_direct_map,
index_param=None,
)
# Add embeddings to index
return add_embeddings_fn(
embedding_reader=embedding_reader,
memory_available_for_adding=memory_available_for_adding,
embedding_ids_df_handler=write_ids_df_to_parquet_fn,
index_optimizer=optimize_index_fn,
)
def _add_embeddings_from_dir_to_index(
add_embeddings_fn: Callable,
embedding_root_dir: str,
output_root_dir: str,
index_key: str,
embedding_column_name: str,
current_memory_available: str,
id_columns: Optional[List[str]],
max_index_query_time_ms: float,
min_nearest_neighbors_to_retrieve: int,
use_gpu: bool,
make_direct_map: bool,
) -> Tuple[Optional[faiss.Index], Optional[Dict[str, str]]]:
"""Add embeddings from directory to index"""
# Read embeddings
with Timeit("-> Reading embeddings", indent=2):
embedding_reader = EmbeddingReader(
embedding_root_dir, file_format="parquet", embedding_column=embedding_column_name, meta_columns=id_columns
)
# Add embeddings to index
return _add_embeddings_to_index(
add_embeddings_fn=add_embeddings_fn,
embedding_reader=embedding_reader,
output_root_dir=output_root_dir,
index_key=index_key,
current_memory_available=current_memory_available,
id_columns=id_columns,
max_index_query_time_ms=max_index_query_time_ms,
min_nearest_neighbors_to_retrieve=min_nearest_neighbors_to_retrieve,
use_gpu=use_gpu,
make_direct_map=make_direct_map,
)
def create_big_index(
embedding_root_dir: str,
ss,
output_root_dir: str,
id_columns: Optional[List[str]],
should_be_memory_mappable: bool,
max_index_query_time_ms: float,
max_index_memory_usage: str,
min_nearest_neighbors_to_retrieve: int,
embedding_column_name: str,
index_key: str,
index_path: Optional[str],
current_memory_available: str,
nb_cores: Optional[int],
use_gpu: bool,
metric_type: str,
nb_splits_per_big_index: int,
make_direct_map: bool,
temp_root_dir: str,
) -> Optional[Dict[str, str]]:
"""
Create a big index
"""
def _create_and_train_index_from_embedding_dir() -> TrainedIndex:
trained_index = create_and_train_index_from_embedding_dir(
embedding_root_dir=embedding_root_dir,
embedding_column_name=embedding_column_name,
index_key=index_key,
max_index_memory_usage=max_index_memory_usage,
make_direct_map=make_direct_map,
should_be_memory_mappable=should_be_memory_mappable,
use_gpu=use_gpu,
metric_type=metric_type,
nb_cores=nb_cores,
current_memory_available=current_memory_available,
id_columns=id_columns,
)
index_output_root_dir = os.path.join(temp_root_dir, "training", partition)
output_index_path = save_index(trained_index.index_or_path, index_output_root_dir, "trained_index")
return TrainedIndex(output_index_path, trained_index.index_key, embedding_root_dir)
partition = extract_partition_name_from_path(embedding_root_dir)
if not index_path:
# Train index
rdd = ss.sparkContext.parallelize([embedding_root_dir], 1)
trained_index_path, trained_index_key, _, = rdd.map(
lambda _: _create_and_train_index_from_embedding_dir()
).collect()[0]
else:
assert index_key, "index key of the input index must be provided because you provided an index_path"
trained_index_path = index_path
trained_index_key = index_key
# Add embeddings to index and compute metrics
partition_temp_root_dir = os.path.join(temp_root_dir, "add_embeddings", partition)
index, metrics = _add_embeddings_from_dir_to_index(
add_embeddings_fn=partial(
add_embeddings_to_index_distributed,
trained_index_or_path=trained_index_path,
nb_cores=nb_cores,
temporary_indices_folder=partition_temp_root_dir,
nb_indices_to_keep=nb_splits_per_big_index,
),
embedding_root_dir=embedding_root_dir,
output_root_dir=output_root_dir,
index_key=trained_index_key,
embedding_column_name=embedding_column_name,
current_memory_available=current_memory_available,
id_columns=id_columns,
max_index_query_time_ms=max_index_query_time_ms,
min_nearest_neighbors_to_retrieve=min_nearest_neighbors_to_retrieve,
use_gpu=use_gpu,
make_direct_map=make_direct_map,
)
# Only metrics are returned to save memory on driver
if index:
del index
return metrics
def create_small_index(
embedding_root_dir: str,
output_root_dir: str,
id_columns: Optional[List[str]] = None,
should_be_memory_mappable: bool = False,
max_index_query_time_ms: float = 10.0,
max_index_memory_usage: str = "16G",
min_nearest_neighbors_to_retrieve: int = 20,
embedding_column_name: str = "embedding",
index_key: Optional[str] = None,
index_path: Optional[str] = None,
current_memory_available: str = "32G",
use_gpu: bool = False,
metric_type: str = "ip",
nb_cores: Optional[int] = None,
make_direct_map: bool = False,
) -> Tuple[Optional[faiss.Index], Optional[Dict[str, str]]]:
"""
Create a small index
"""
if not index_path:
trained_index = create_and_train_index_from_embedding_dir(
embedding_root_dir=embedding_root_dir,
embedding_column_name=embedding_column_name,
index_key=index_key,
max_index_memory_usage=max_index_memory_usage,
make_direct_map=make_direct_map,
should_be_memory_mappable=should_be_memory_mappable,
use_gpu=use_gpu,
metric_type=metric_type,
nb_cores=nb_cores,
current_memory_available=current_memory_available,
id_columns=id_columns,
)
else:
assert index_key, "index key of the input index must be provided because you provided an index_path"
with tempfile.TemporaryDirectory() as tmp_dir:
embedding_reader = EmbeddingReader(
embedding_root_dir,
file_format="parquet",
embedding_column=embedding_column_name,
meta_columns=id_columns,
)
index = load_index(index_path, os.path.join(tmp_dir, "index"))
trained_index = TrainedIndex(index, index_key, embedding_reader)
# Add embeddings to index and compute metrics
return _add_embeddings_to_index(
add_embeddings_fn=partial(
add_embeddings_to_index_local,
trained_index_or_path=trained_index.index_or_path,
add_embeddings_with_ids=True,
),
embedding_reader=trained_index.embedding_reader_or_path,
output_root_dir=output_root_dir,
index_key=trained_index.index_key,
current_memory_available=current_memory_available,
id_columns=id_columns,
max_index_query_time_ms=max_index_query_time_ms,
min_nearest_neighbors_to_retrieve=min_nearest_neighbors_to_retrieve,
use_gpu=use_gpu,
make_direct_map=make_direct_map,
)
def create_partitioned_indexes(
partitions: List[str],
big_index_threshold: int,
output_root_dir: str,
nb_cores: Optional[int],
nb_splits_per_big_index: int,
id_columns: Optional[List[str]] = None,
max_index_query_time_ms: float = 10.0,
min_nearest_neighbors_to_retrieve: int = 20,
embedding_column_name: str = "embedding",
index_key: Optional[str] = None,
index_path: Optional[str] = None,
max_index_memory_usage: str = "16G",
current_memory_available: str = "32G",
use_gpu: bool = False,
metric_type: str = "ip",
make_direct_map: bool = False,
should_be_memory_mappable: bool = False,
temp_root_dir: str = "hdfs://root/tmp/distributed_autofaiss_indices",
maximum_nb_threads: int = 256,
) -> List[Optional[Dict[str, str]]]:
"""
Create partitioned indexes from a list of parquet partitions,
i.e. create and train one index per parquet partition
"""
def _create_small_indexes(embedding_root_dirs: List[str]) -> List[Optional[Dict[str, str]]]:
rdd = ss.sparkContext.parallelize(embedding_root_dirs, len(embedding_root_dirs))
return rdd.map(
lambda embedding_root_dir: create_small_index(
embedding_root_dir=embedding_root_dir,
output_root_dir=output_root_dir,
id_columns=id_columns,
should_be_memory_mappable=should_be_memory_mappable,
max_index_query_time_ms=max_index_query_time_ms,
max_index_memory_usage=max_index_memory_usage,
min_nearest_neighbors_to_retrieve=min_nearest_neighbors_to_retrieve,
embedding_column_name=embedding_column_name,
index_key=index_key,
index_path=index_path,
current_memory_available=current_memory_available,
use_gpu=use_gpu,
metric_type=metric_type,
nb_cores=nb_cores,
make_direct_map=make_direct_map,
)[1]
).collect()
ss = _get_pyspark_active_session()
create_big_index_fn = partial(
create_big_index,
ss=ss,
output_root_dir=output_root_dir,
id_columns=id_columns,
should_be_memory_mappable=should_be_memory_mappable,
max_index_query_time_ms=max_index_query_time_ms,
max_index_memory_usage=max_index_memory_usage,
min_nearest_neighbors_to_retrieve=min_nearest_neighbors_to_retrieve,
embedding_column_name=embedding_column_name,
index_key=index_key,
index_path=index_path,
current_memory_available=current_memory_available,
nb_cores=nb_cores,
use_gpu=use_gpu,
metric_type=metric_type,
nb_splits_per_big_index=nb_splits_per_big_index,
make_direct_map=make_direct_map,
temp_root_dir=temp_root_dir,
)
# Compute number of embeddings for each partition
rdd = ss.sparkContext.parallelize(partitions, len(partitions))
partition_sizes = rdd.map(
lambda partition: (
partition,
EmbeddingReader(partition, file_format="parquet", embedding_column=embedding_column_name).count,
)
).collect()
# Group partitions in two categories, small and big indexes
small_partitions = []
big_partitions = []
for partition, size in partition_sizes:
if size < big_index_threshold:
small_partitions.append(partition)
else:
big_partitions.append(partition)
# Create small and big indexes
all_metrics = []
n_threads = min(maximum_nb_threads, len(big_partitions) + int(len(small_partitions) > 0))
with ThreadPool(n_threads) as p:
small_index_metrics_future = (
p.apply_async(_create_small_indexes, (small_partitions,)) if small_partitions else None
)
for metrics in p.starmap(create_big_index_fn, [(p,) for p in big_partitions]):
all_metrics.append(metrics)
if small_index_metrics_future:
all_metrics.extend(small_index_metrics_future.get())
return all_metrics
|
""" function related to search on indices """
from typing import Iterable, Tuple
import numpy as np
def knn_query(index, query, ksearch: int) -> Iterable[Tuple[Tuple[int, int], float]]:
"""Do a knn search and return a list of the closest items and the associated distance"""
dist, ind = index.search(np.expand_dims(query, 0), ksearch)
distances = dist[0]
item_dist = list(zip(ind[0], distances))
return item_dist
|
""" This file contain a class describing a memory efficient flat index """
import heapq
from typing import List, Optional, Tuple
from embedding_reader import EmbeddingReader
import faiss
import numpy as np
from tqdm import trange
from autofaiss.indices.faiss_index_wrapper import FaissIndexWrapper
class MemEfficientFlatIndex(FaissIndexWrapper):
"""
Faiss-like Flat index that can support any size of vectors
without memory issues.
Two search functions are available to use either batch of smaller faiss
flat index or rely fully on numpy.
"""
def __init__(self, d: int, metric_type: int):
"""
__init__ function for MemEfficientFlatIndex
Parameters:
-----------
d : int
dimension of the vectors, named d to keep Faiss notation
metric_type : int
similarity metric used in the vector space, using faiss
enumerate values (faiss.METRIC_INNER_PRODUCT and faiss.METRIC_L2)
"""
super().__init__(d, metric_type)
self.dim = d
self.prod_emb = np.zeros((0, self.dim))
self.embedding_reader: Optional[EmbeddingReader] = None
def delete_vectors(self):
"""delete the vectors of the index"""
self.prod_emb = np.zeros((0, self.dim))
# pylint: disable=missing-function-docstring, invalid-name
def add(self, x: np.ndarray):
if self.prod_emb.shape[0] == 0:
self.prod_emb = x.astype(np.float32)
else:
raise NotImplementedError("You can add vectors only once, delete them first with delete_vectors")
def add_all(self, filename: str, nb_items: int):
"""
Function that adds vectors to the index from a memmory-mapped array
Parameters
----------
filename : string
path of the 2D numpy array of shape (nb_items, vector_dim)
on the disk
nb_items : int
number of vectors in the 2D array (the dim is already known)
"""
if self.prod_emb.shape[0] == 0:
self.prod_emb = np.memmap(filename, dtype="float32", mode="r", shape=(nb_items, self.dim))
else:
raise NotImplementedError("You can add vectors only once, delete them first")
def add_files(self, embedding_reader: EmbeddingReader):
if self.embedding_reader is None:
self.embedding_reader = embedding_reader
else:
raise NotImplementedError("You can add vectors only once, delete them first with delete_vectors")
# pylint: disable too_many_locals
def search_numpy(self, xq: np.ndarray, k: int, batch_size: int = 4_000_000):
"""
Function that search the k nearest neighbours of a batch of vectors.
This implementation is based on vectorized numpy function, it is slower than
the search function based on batches of faiss flat indices.
We keep this implementation because we can build new functions using this code.
Moreover, the distance computation is more precise in numpy than the faiss implementation
that optimizes speed over precision.
Parameters
----------
xq : 2D numpy.array of floats
Batch of vectors of shape (batch_size, vector_dim)
k : int
Number of neighbours to retrieve for every vector
batch_size : int
Size of the batch of vectors that are explored.
A bigger value is prefered to avoid multiple loadings
of the vectors from the disk.
Returns
-------
D : 2D numpy.array of floats
Distances numpy array of shape (batch_size, k).
Contains the distances computed by the index of the k nearest neighbours.
I : 2D numpy.array of ints
Labels numpy array of shape (batch_size, k).
Contains the vectors' labels of the k nearest neighbours.
"""
assert self.metric_type == faiss.METRIC_INNER_PRODUCT
# Instanciate several heaps, (is there a way to have vectorized heaps?)
h: List[List[Tuple[float, int]]] = [[] for _ in range(xq.shape[0])]
# reshape input for vectorized distance computation
xq_reshaped = np.expand_dims(xq, 1)
# initialize index offset
offset = 0
# For each batch
for i in trange(0, self.prod_emb.shape[0], batch_size):
# compute distances in one tensor product
dist_arr = np.sum((xq_reshaped * np.expand_dims(self.prod_emb[i : i + batch_size], 0)), axis=-1)
# get index of the k biggest
# pylint: disable=unsubscriptable-object # pylint/issues/3139
max_k = min(k, dist_arr.shape[1])
ind_k_max = np.argpartition(dist_arr, -max_k)[:, -max_k:]
assert ind_k_max.shape == (xq.shape[0], max_k)
# to be vectorized if it is indeed the bottleneck, (it's not for batch_size >> 10000)
for j, inds in enumerate(ind_k_max):
for ind, distance in zip(inds, dist_arr[j, inds]):
true_ind = offset + ind if ind != -1 else -1
if len(h[j]) < k:
heapq.heappush(h[j], (distance, true_ind))
else:
heapq.heappushpop(h[j], (distance, true_ind))
offset += batch_size
# Fill distance and indice matrix
D = np.zeros((xq.shape[0], k), dtype=np.float32)
I = np.full((xq.shape[0], k), fill_value=-1, dtype=np.int32)
for i in range(xq.shape[0]):
# case where we couldn't find enough vectors
max_k = min(k, len(h[i]))
for j in range(max_k):
x = heapq.heappop(h[i])
D[i][max_k - 1 - j] = x[0]
I[i][max_k - 1 - j] = x[1]
return D, I
# pylint: disable=too-many-locals, arguments-differ
def search(self, x: np.ndarray, k: int, batch_size: int = 4_000_000):
"""
Function that search the k nearest neighbours of a batch of vectors
Parameters
----------
x : 2D numpy.array of floats
Batch of vectors of shape (batch_size, vector_dim)
k : int
Number of neighbours to retrieve for every vector
batch_size : int
Size of the batch of vectors that are explored.
A bigger value is prefered to avoid multiple loadings
of the vectors from the disk.
Returns
-------
D : 2D numpy.array of floats
Distances numpy array of shape (batch_size, k).
Contains the distances computed by the index of the k nearest neighbours.
I : 2D numpy.array of ints
Labels numpy array of shape (batch_size, k).
Contains the vectors' labels of the k nearest neighbours.
"""
if self.prod_emb is None:
raise ValueError("The index is empty")
# Cast in the right format for Faiss
if x.dtype != np.float32:
x = x.astype(np.float32)
# xq for x query, a better name than x which is Faiss convention
xq = x
# Instanciate several heaps, (is there a way to have vectorized heaps?)
h: List[List[Tuple[float, int]]] = [[] for _ in range(xq.shape[0])]
# initialize index offset
offset = 0
# For each batch
for i in trange(0, self.prod_emb.shape[0], batch_size):
# instanciate a Flat index
brute = faiss.IndexFlatIP(self.dim)
# pylint: disable=no-value-for-parameter
brute.add(self.prod_emb[i : i + batch_size])
D_tmp, I_tmp = brute.search(xq, k)
# to be vectorized if it is indeed the bottleneck, (it's not for batch_size >> 10000)
for j, (distances, inds) in enumerate(zip(D_tmp, I_tmp)):
for distance, ind in zip(distances, inds):
true_ind: int = offset + ind if ind != -1 else -1
if len(h[j]) < k:
heapq.heappush(h[j], (distance, true_ind))
else:
heapq.heappushpop(h[j], (distance, true_ind))
offset += batch_size
# Fill distance and indice matrix
D = np.zeros((xq.shape[0], k), dtype=np.float32)
I = np.full((xq.shape[0], k), fill_value=-1, dtype=np.int32)
for i in range(xq.shape[0]):
# case where we couldn't find enough vectors
max_k = min(k, len(h[i]))
for j in range(max_k):
x = heapq.heappop(h[i])
D[i][max_k - 1 - j] = x[0]
I[i][max_k - 1 - j] = x[1]
return D, I
def search_files(self, x: np.ndarray, k: int, batch_size: int):
if self.embedding_reader is None:
raise ValueError("The index is empty")
# Cast in the right format for Faiss
if x.dtype != np.float32:
x = x.astype(np.float32)
# xq for x query, a better name than x which is Faiss convention
xq = x
# Instanciate several heaps, (is there a way to have vectorized heaps?)
h: List[List[Tuple[float, int]]] = [[] for _ in range(xq.shape[0])]
# initialize index offset
offset = 0
# For each batch
for emb_array, _ in self.embedding_reader(batch_size):
# for i in trange(0, self.prod_emb.shape[0], batch_size):
# instanciate a Flat index
brute = faiss.IndexFlatIP(self.dim)
# pylint: disable=no-value-for-parameter
brute.add(emb_array)
D_tmp, I_tmp = brute.search(xq, k)
# to be vectorized if it is indeed the bottleneck, (it's not for batch_size >> 10000)
for j, (distances, inds) in enumerate(zip(D_tmp, I_tmp)):
for distance, ind in zip(distances, inds):
true_ind: int = offset + ind if ind != -1 else -1
if len(h[j]) < k:
heapq.heappush(h[j], (distance, true_ind))
else:
heapq.heappushpop(h[j], (distance, true_ind))
offset += emb_array.shape[0]
# Fill distance and indice matrix
D = np.zeros((xq.shape[0], k), dtype=np.float32)
I = np.full((xq.shape[0], k), fill_value=-1, dtype=np.int32)
for i in range(xq.shape[0]):
# case where we couldn't find enough vectors
max_k = min(k, len(h[i]))
for j in range(max_k):
x = heapq.heappop(h[i]) # type: ignore
D[i][max_k - 1 - j] = x[0]
I[i][max_k - 1 - j] = x[1]
return D, I
|
""" This file contains a wrapper class to create Faiss-like indices """
from abc import ABC, abstractmethod
import faiss
import numpy as np
class FaissIndexWrapper(ABC):
"""
This abstract class is describing a Faiss-like index
It is useful to use this wrapper to use benchmarking functions written for
faiss in this library
"""
# pylint: disable=invalid-name
def __init__(self, d: int, metric_type: int):
"""
__init__ function for FaissIndexWrapper
Parameters:
-----------
d : int
dimension of the vectors, named d to keep Faiss notation
metric_type : int
similarity metric used in the vector space, using faiss
enumerate values (faiss.METRIC_INNER_PRODUCT and faiss.METRIC_L2)
"""
self.d = d
if metric_type in [faiss.METRIC_INNER_PRODUCT, "IP", "ip"]:
self.metric_type = faiss.METRIC_INNER_PRODUCT
elif metric_type in [faiss.METRIC_L2, "L2", "l2"]:
self.metric_type = faiss.METRIC_L2
else:
raise NotImplementedError
# pylint: disable=invalid-name
@abstractmethod
def search(self, x: np.ndarray, k: int):
"""
Function that search the k nearest neighbours of a batch of vectors
Parameters
----------
x : 2D numpy.array of floats
Batch of vectors of shape (batch_size, vector_dim)
k : int
Number of neighbours to retrieve for every vector
Returns
-------
D : 2D numpy.array of floats
Distances numpy array of shape (batch_size, k).
Contains the distances computed by the index of the k nearest neighbours.
I : 2D numpy.array of ints
Labels numpy array of shape (batch_size, k).
Contains the vectors' labels of the k nearest neighbours.
"""
raise NotImplementedError
# pylint: disable=invalid-name
@abstractmethod
def add(self, x: np.ndarray):
"""
Function that adds vectors to the index
Parameters
----------
x : 2D numpy.array of floats
Batch of vectors of shape (batch_size, vector_dim)
"""
raise NotImplementedError
|
"""Index training"""
from typing import Union, NamedTuple, Optional, List
import logging
import multiprocessing
import faiss
from embedding_reader import EmbeddingReader
from autofaiss.external.metadata import IndexMetadata
from autofaiss.external.optimize import check_if_index_needs_training, get_optimal_train_size
from autofaiss.indices.index_factory import index_factory
from autofaiss.utils.cast import cast_bytes_to_memory_string, cast_memory_to_bytes, to_faiss_metric_type
from autofaiss.utils.decorators import Timeit
from autofaiss.external.optimize import get_optimal_index_keys_v2
logger = logging.getLogger("autofaiss")
class TrainedIndex(NamedTuple):
index_or_path: Union[faiss.Index, str]
index_key: str
embedding_reader_or_path: Union[EmbeddingReader, str]
def create_empty_index(vec_dim: int, index_key: str, metric_type: Union[str, int]) -> faiss.Index:
"""Create empty index"""
with Timeit(f"-> Instanciate the index {index_key}", indent=2):
# Convert metric_type to faiss type
metric_type = to_faiss_metric_type(metric_type)
# Instanciate the index
return index_factory(vec_dim, index_key, metric_type)
def _train_index(
embedding_reader: EmbeddingReader,
index_key: str,
index: faiss.Index,
metadata: IndexMetadata,
current_memory_available: str,
use_gpu: bool,
) -> faiss.Index:
"""Train index"""
logger.info(
f"The index size will be approximately {cast_bytes_to_memory_string(metadata.estimated_index_size_in_bytes())}"
)
# Extract training vectors
with Timeit("-> Extract training vectors", indent=2):
memory_available_for_training = cast_bytes_to_memory_string(cast_memory_to_bytes(current_memory_available))
# Determine the number of vectors necessary to train the index
train_size = get_optimal_train_size(
embedding_reader.count, index_key, memory_available_for_training, embedding_reader.dimension
)
memory_needed_for_training = metadata.compute_memory_necessary_for_training(train_size)
logger.info(
f"Will use {train_size} vectors to train the index, "
f"that will use {cast_bytes_to_memory_string(memory_needed_for_training)} of memory"
)
# Extract training vectors
train_vectors, _ = next(embedding_reader(batch_size=train_size, start=0, end=train_size))
# Instanciate the index and train it
# pylint: disable=no-member
if use_gpu:
# if this fails, it means that the GPU version was not comp.
assert (
faiss.StandardGpuResources
), "FAISS was not compiled with GPU support, or loading _swigfaiss_gpu.so failed"
res = faiss.StandardGpuResources()
dev_no = 0
# transfer to GPU (may be partial).
index = faiss.index_cpu_to_gpu(res, dev_no, index)
with Timeit(
f"-> Training the index with {train_vectors.shape[0]} vectors of dim {train_vectors.shape[1]}", indent=2
):
index.train(train_vectors)
del train_vectors
return index
def create_and_train_new_index(
embedding_reader: EmbeddingReader,
index_key: str,
metadata: IndexMetadata,
metric_type: Union[str, int],
current_memory_available: str,
use_gpu: bool = False,
) -> faiss.Index:
"""Create and train new index"""
# Instanciate the index
index = create_empty_index(embedding_reader.dimension, index_key, metric_type)
# Train index if needed
if check_if_index_needs_training(index_key):
index = _train_index(embedding_reader, index_key, index, metadata, current_memory_available, use_gpu)
return index
def create_and_train_index_from_embedding_dir(
embedding_root_dir: str,
embedding_column_name: str,
max_index_memory_usage: str,
make_direct_map: bool,
should_be_memory_mappable: bool,
current_memory_available: str,
use_gpu: bool = False,
index_key: Optional[str] = None,
id_columns: Optional[List[str]] = None,
metric_type: str = "ip",
nb_cores: Optional[int] = None,
) -> TrainedIndex:
"""
Create and train index from embedding directory
"""
nb_cores = nb_cores if nb_cores else multiprocessing.cpu_count()
faiss.omp_set_num_threads(nb_cores)
# Read embeddings
with Timeit("-> Reading embeddings", indent=2):
embedding_reader = EmbeddingReader(
embedding_root_dir, file_format="parquet", embedding_column=embedding_column_name, meta_columns=id_columns
)
# Define index key
if index_key is None:
best_index_keys = get_optimal_index_keys_v2(
embedding_reader.count,
embedding_reader.dimension,
max_index_memory_usage,
make_direct_map=make_direct_map,
should_be_memory_mappable=should_be_memory_mappable,
use_gpu=use_gpu,
)
if not best_index_keys:
raise RuntimeError(f"Unable to find optimal index key from embedding directory {embedding_root_dir}")
index_key = best_index_keys[0]
# Create metadata
with Timeit("-> Reading metadata", indent=2):
metadata = IndexMetadata(index_key, embedding_reader.count, embedding_reader.dimension, make_direct_map)
# Create and train index
index = create_and_train_new_index(
embedding_reader, index_key, metadata, metric_type, current_memory_available, use_gpu
)
return TrainedIndex(index, index_key, embedding_reader)
|
""" function to cast variables in others """
import re
from math import floor
from typing import Union
import faiss
def cast_memory_to_bytes(memory_string: str) -> float:
"""
Parse a memory string and returns the number of bytes
>>> cast_memory_to_bytes("16B")
16
>>> cast_memory_to_bytes("16G") == 16*1024*1024*1024
True
"""
conversion = {unit: (2 ** 10) ** i for i, unit in enumerate("BKMGTPEZ")}
number_match = r"([0-9]*\.[0-9]+|[0-9]+)"
unit_match = "("
for unit in conversion:
if unit != "B":
unit_match += unit + "B|"
for unit in conversion:
unit_match += unit + "|"
unit_match = unit_match[:-1] + ")"
matching_groups = re.findall(number_match + unit_match, memory_string, re.IGNORECASE)
if matching_groups and len(matching_groups) == 1 and "".join(matching_groups[0]) == memory_string:
group = matching_groups[0]
return float(group[0]) * conversion[group[1][0].upper()]
raise ValueError(f"Unknown format for memory string: {memory_string}")
def cast_bytes_to_memory_string(num_bytes: float) -> str:
"""
Cast a number of bytes to a readable string
>>> from autofaiss.utils.cast import cast_bytes_to_memory_string
>>> cast_bytes_to_memory_string(16.*1024*1024*1024) == "16.0GB"
True
"""
suffix = "B"
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if abs(num_bytes) < 1024.0:
return "%3.1f%s%s" % (num_bytes, unit, suffix)
num_bytes /= 1024.0
return "%.1f%s%s" % (num_bytes, "Y", suffix)
def to_faiss_metric_type(metric_type: Union[str, int]) -> int:
"""convert metric_type string/enum to faiss enum of the distance metric"""
if metric_type in ["ip", "IP", faiss.METRIC_INNER_PRODUCT]:
return faiss.METRIC_INNER_PRODUCT
elif metric_type in ["l2", "L2", faiss.METRIC_L2]:
return faiss.METRIC_L2
else:
raise ValueError("Metric currently not supported")
def to_readable_time(seconds: float, rounding: bool = False) -> str:
"""cast time in seconds to readable string"""
initial_seconds = seconds
hours = int(floor(seconds // 3600))
seconds -= 3600 * hours
minutes = int(floor(seconds // 60))
seconds -= 60 * minutes
if rounding:
if hours:
return f"{initial_seconds/3600:3.1f} hours"
if minutes:
return f"{initial_seconds/60:3.1f} minutes"
return f"{initial_seconds:3.1f} seconds"
time_str = ""
if hours:
time_str += f"{hours:d} hours "
if hours or minutes:
time_str += f"{minutes:d} minutes "
time_str += f"{seconds:.2f} seconds"
return time_str
|
""" Various optimization algorithms """
from typing import Callable
# pylint: disable=invalid-name
def discrete_binary_search(is_ok: Callable[[int], bool], n: int) -> int:
"""
Binary search in a function domain
Parameters
----------
is_ok : bool
Boolean monotone function defined on range(n)
n : int
length of the search scope
Returns
-------
i : int
first index i such that is_ok(i) or returns n if is_ok is all False
:complexity: O(log(n))
"""
lo = 0
hi = n
while lo < hi:
mid = lo + (hi - lo) // 2
if mid >= n or is_ok(mid):
hi = mid
else:
lo = mid + 1
return lo
|
# pylint: disable=unused-import,missing-docstring
|
""" useful functions t apply on numpy arrays """
import numpy as np
def sanitize(x):
return np.ascontiguousarray(x, dtype="float32")
def multi_array_split(array_list, nb_chunk):
total_length = len(array_list[0])
chunk_size = (total_length - 1) // nb_chunk + 1
assert all(len(x) == total_length for x in array_list)
for i in range(0, total_length, chunk_size):
yield tuple(x[i : i + chunk_size] for x in array_list)
|
"""path"""
import os
import fsspec
def make_path_absolute(path: str) -> str:
fs, p = fsspec.core.url_to_fs(path, use_listings_cache=False)
if fs.protocol == "file":
return os.path.abspath(p)
return path
def extract_partition_name_from_path(path: str) -> str:
"""Extract partition name from path"""
return path.rstrip("/").split("/")[-1]
|
""" Useful decorators for fast debuging """
import functools
import time
import logging
from contextlib import ContextDecorator
from datetime import datetime
from typing import Optional
logger = logging.getLogger("autofaiss")
class Timeit(ContextDecorator):
"""Timing class, used as a context manager"""
def __init__(self, comment: Optional[str] = None, indent: int = 0, verbose: bool = True):
self.start_time = 0
self.comment = comment
self.indent = indent
self.verbose = verbose
def __enter__(self):
if self.verbose:
if self.comment is not None:
space = "\t" * self.indent
start_date = datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
logger.info(f"{space}{self.comment} {start_date}")
# flush to make sure we display log in stdout before entering in the wrapped function
for h in logger.handlers:
h.flush()
self.start_time = time.perf_counter()
def __exit__(self, *exc):
if self.verbose:
end_time = time.perf_counter()
run_time = end_time - self.start_time
space = "\t" * self.indent
logger.info(f'{space}>>> Finished "{self.comment}" in {run_time:.4f} secs')
timeit = Timeit()
def timer(func):
"""Print the runtime of the decorated function"""
@functools.wraps(func)
def wrapper_timer(*args, **kwargs):
start_time = time.perf_counter()
value = func(*args, **kwargs)
end_time = time.perf_counter()
run_time = end_time - start_time
logger.info(f"Finished {func.__name__!r} in {run_time:.4f} secs")
return value
return wrapper_timer
def should_run_once(func):
"""
Decorator to force a function to run only once.
The fonction raises a ValueError otherwise.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
if wrapper.has_run:
raise ValueError("Can't call this function twice")
wrapper.has_run = True
return func(*args, **kwargs)
wrapper.has_run = False
return wrapper
|
""" gather functions necessary to build an index """
import logging
from typing import Dict, Optional, Tuple, Union, Callable, Any, List
import faiss
import pandas as pd
from embedding_reader import EmbeddingReader
from autofaiss.external.metadata import IndexMetadata
from autofaiss.external.optimize import check_if_index_needs_training, get_optimal_index_keys_v2, get_optimal_train_size
from autofaiss.utils.cast import cast_bytes_to_memory_string, cast_memory_to_bytes, to_readable_time
from autofaiss.utils.decorators import Timeit
from autofaiss.indices import distributed
from autofaiss.indices.index_utils import initialize_direct_map
from autofaiss.indices.training import create_and_train_new_index
from autofaiss.indices.build import add_embeddings_to_index_local
logger = logging.getLogger("autofaiss")
def estimate_memory_required_for_index_creation(
nb_vectors: int,
vec_dim: int,
index_key: Optional[str] = None,
max_index_memory_usage: Optional[str] = None,
make_direct_map: bool = False,
nb_indices_to_keep: int = 1,
) -> Tuple[int, str]:
"""
Estimates the RAM necessary to create the index
The value returned is in Bytes
"""
if index_key is None:
if max_index_memory_usage is not None:
index_key = get_optimal_index_keys_v2(
nb_vectors, vec_dim, max_index_memory_usage, make_direct_map=make_direct_map
)[0]
else:
raise ValueError("you should give max_index_memory_usage value if no index_key is given")
metadata = IndexMetadata(index_key, nb_vectors, vec_dim, make_direct_map)
index_memory = metadata.estimated_index_size_in_bytes()
needed_for_adding = min(index_memory * 0.1, 10 ** 9)
index_needs_training = check_if_index_needs_training(index_key)
if index_needs_training:
# Compute the smallest number of vectors required to train the index given
# the maximal memory constraint
nb_vectors_train = get_optimal_train_size(nb_vectors, index_key, "1K", vec_dim)
memory_for_training = metadata.compute_memory_necessary_for_training(nb_vectors_train)
else:
memory_for_training = 0
# the calculation for max_index_memory_in_one_index comes from the way we split batches
# see _batch_loader in distributed.py
max_index_memory_in_one_index = index_memory // nb_indices_to_keep + index_memory % nb_indices_to_keep
return int(max(max_index_memory_in_one_index + needed_for_adding, memory_for_training)), index_key
def get_estimated_construction_time_infos(nb_vectors: int, vec_dim: int, indent: int = 0) -> str:
"""
Gives a general approximation of the construction time of the index
"""
size = 4 * nb_vectors * vec_dim
train = 1000 # seconds, depends on the number of points for training
add = 450 * size / (150 * 1024 ** 3) # seconds, Linear approx (450s for 150GB in classic conditions)
infos = (
f"-> Train: {to_readable_time(train, rounding=True)}\n"
f"-> Add: {to_readable_time(add, rounding=True)}\n"
f"Total: {to_readable_time(train + add, rounding=True)}"
)
tab = "\t" * indent
infos = tab + infos.replace("\n", "\n" + tab)
return infos
def add_embeddings_to_index(
embedding_reader: EmbeddingReader,
trained_index_or_path: Union[str, faiss.Index],
metadata: IndexMetadata,
current_memory_available: str,
embedding_ids_df_handler: Optional[Callable[[pd.DataFrame, int], Any]] = None,
distributed_engine: Optional[str] = None,
temporary_indices_folder: str = "hdfs://root/tmp/distributed_autofaiss_indices",
nb_indices_to_keep: int = 1,
index_optimizer: Callable = None,
) -> Tuple[Optional[faiss.Index], Optional[Dict[str, str]]]:
"""Add embeddings to the index"""
with Timeit("-> Adding the vectors to the index", indent=2):
# Estimate memory available for adding embeddings to index
size_per_index = metadata.estimated_index_size_in_bytes() / nb_indices_to_keep
memory_available_for_adding = cast_bytes_to_memory_string(
cast_memory_to_bytes(current_memory_available) - size_per_index
)
logger.info(
f"The memory available for adding the vectors is {memory_available_for_adding}"
"(total available - used by the index)"
)
if distributed_engine is None:
return add_embeddings_to_index_local(
embedding_reader=embedding_reader,
trained_index_or_path=trained_index_or_path,
memory_available_for_adding=memory_available_for_adding,
embedding_ids_df_handler=embedding_ids_df_handler,
index_optimizer=index_optimizer,
add_embeddings_with_ids=False,
)
elif distributed_engine == "pyspark":
return distributed.add_embeddings_to_index_distributed(
trained_index_or_path=trained_index_or_path,
embedding_reader=embedding_reader,
memory_available_for_adding=memory_available_for_adding,
embedding_ids_df_handler=embedding_ids_df_handler,
temporary_indices_folder=temporary_indices_folder,
nb_indices_to_keep=nb_indices_to_keep,
index_optimizer=index_optimizer,
)
else:
raise ValueError(f'Distributed by {distributed_engine} is not supported, only "pyspark" is supported')
def create_index(
embedding_reader: EmbeddingReader,
index_key: str,
metric_type: Union[str, int],
current_memory_available: str,
embedding_ids_df_handler: Optional[Callable[[pd.DataFrame, int], Any]] = None,
use_gpu: bool = False,
make_direct_map: bool = False,
distributed_engine: Optional[str] = None,
temporary_indices_folder: str = "hdfs://root/tmp/distributed_autofaiss_indices",
nb_indices_to_keep: int = 1,
index_optimizer: Callable = None,
) -> Tuple[Optional[faiss.Index], Optional[Dict[str, str]]]:
"""
Create an index and add embeddings to the index
"""
metadata = IndexMetadata(index_key, embedding_reader.count, embedding_reader.dimension, make_direct_map)
# Create and train index
trained_index = create_and_train_new_index(
embedding_reader, index_key, metadata, metric_type, current_memory_available, use_gpu
)
# Add embeddings to index
index, metrics = add_embeddings_to_index(
embedding_reader,
trained_index,
metadata,
current_memory_available,
embedding_ids_df_handler,
distributed_engine,
temporary_indices_folder,
nb_indices_to_keep,
index_optimizer,
)
if make_direct_map:
initialize_direct_map(index)
return index, metrics
def create_partitioned_indexes(
partitions: List[str],
output_root_dir: str,
embedding_column_name: str = "embedding",
index_key: Optional[str] = None,
index_path: Optional[str] = None,
id_columns: Optional[List[str]] = None,
should_be_memory_mappable: bool = False,
max_index_query_time_ms: float = 10.0,
max_index_memory_usage: str = "16G",
min_nearest_neighbors_to_retrieve: int = 20,
current_memory_available: str = "32G",
use_gpu: bool = False,
metric_type: str = "ip",
nb_cores: Optional[int] = None,
make_direct_map: bool = False,
temp_root_dir: str = "hdfs://root/tmp/distributed_autofaiss_indices",
big_index_threshold: int = 5_000_000,
nb_splits_per_big_index: int = 1,
maximum_nb_threads: int = 256,
) -> List[Optional[Dict[str, str]]]:
"""
Create partitioned indexes from a list of parquet partitions, i.e. create one index per parquet partition
Only supported with Pyspark. An active PySpark session must exist before calling this method
"""
return distributed.create_partitioned_indexes(
partitions=partitions,
big_index_threshold=big_index_threshold,
output_root_dir=output_root_dir,
nb_cores=nb_cores,
nb_splits_per_big_index=nb_splits_per_big_index,
id_columns=id_columns,
max_index_query_time_ms=max_index_query_time_ms,
min_nearest_neighbors_to_retrieve=min_nearest_neighbors_to_retrieve,
embedding_column_name=embedding_column_name,
index_key=index_key,
index_path=index_path,
max_index_memory_usage=max_index_memory_usage,
current_memory_available=current_memory_available,
use_gpu=use_gpu,
metric_type=metric_type,
make_direct_map=make_direct_map,
should_be_memory_mappable=should_be_memory_mappable,
temp_root_dir=temp_root_dir,
maximum_nb_threads=maximum_nb_threads,
)
|
""" Functions to find optimal index parameters """
import json
import logging
import re
from functools import partial, reduce
from math import floor, log2, sqrt
from operator import mul
from typing import Callable, List, Optional, TypeVar
import faiss
import fsspec
import numpy as np
from autofaiss.external.metadata import IndexMetadata, compute_memory_necessary_for_training_wrapper
from autofaiss.external.scores import compute_fast_metrics
from autofaiss.indices.index_utils import set_search_hyperparameters, speed_test_ms_per_query
from autofaiss.utils.algorithms import discrete_binary_search
from autofaiss.utils.cast import cast_memory_to_bytes
from autofaiss.utils.decorators import Timeit
from embedding_reader import EmbeddingReader
logger = logging.getLogger("autofaiss")
def check_if_index_needs_training(index_key: str) -> bool:
"""
Function that checks if the index needs to be trained
"""
if "IVF" in index_key:
return True
elif "IMI" in index_key:
return True
else:
return False
def index_key_to_nb_cluster(index_key: str) -> int:
"""
Function that takes an index key and returns the number of clusters
"""
matching = re.findall(r"IVF\d+|IMI\d+x\d+", index_key)
if matching:
# case IVF index
if re.findall(r"IVF\d+", matching[0]):
nb_clusters = int(matching[0][3:])
# case IMI index
elif re.findall(r"IMI\d+x\d+", matching[0]):
nb_clusters = 2 ** reduce(mul, [int(num) for num in re.findall(r"\d+", matching[0])])
else:
raise ValueError("Unable to determine the number of clusters for index {}".format(index_key))
else:
raise ValueError("Unable to determine the number of clusters for index {}".format(index_key))
return nb_clusters
def get_optimal_train_size(
nb_vectors: int, index_key: str, current_memory_available: Optional[str], vec_dim: Optional[int]
) -> int:
"""
Function that determines the number of training points necessary to
train the index, based on faiss heuristics for k-means clustering.
"""
matching = re.findall(r"IVF\d+|IMI\d+x\d+", index_key)
if matching:
nb_clusters = index_key_to_nb_cluster(index_key)
points_per_cluster: int = 100
# compute best possible number of vectors to give to train the index
# given memory constraints
if current_memory_available and vec_dim:
memory_per_cluster_set = compute_memory_necessary_for_training_wrapper(
points_per_cluster, index_key, vec_dim
)
size = cast_memory_to_bytes(current_memory_available)
points_per_cluster = max(min(size / memory_per_cluster_set, points_per_cluster), 31.0)
# You will need between 30 * nb_clusters and 256 * nb_clusters to train the index
train_size = min(round(points_per_cluster * nb_clusters), nb_vectors)
else:
raise ValueError(f"Unknown index type: {index_key}")
return train_size
def get_optimal_batch_size(vec_dim: int, current_memory_available: str) -> int:
"""compute optimal batch size to use the RAM at its full potential for adding vectors"""
memory = cast_memory_to_bytes(current_memory_available)
batch_size = int(min(memory, 10 ** 9) / (vec_dim * 4)) # using more than 1GB of ram is not faster here
return batch_size
def get_optimal_nb_clusters(nb_vectors: int) -> List[int]:
"""
Returns a list with the recommended number of clusters for an index containing nb_vectors vectors.
The first value is the most recommended one.
see: https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index
"""
nb_clusters_list = []
if nb_vectors < 1_000_000:
# no need to use HNSW for small number of clusters
x_initial = 4 * sqrt(nb_vectors) # between 4xsqrt(n) and 16xsqrt(n)
x_closest_power = 2 ** round(log2(x_initial))
nb_clusters_list.append(round(x_closest_power))
nb_clusters_list.append(2 * x_closest_power)
nb_clusters_list.append(x_closest_power)
nb_clusters_list.append(round(x_initial))
elif nb_vectors < 10_000_000:
nb_clusters_list.append(16_384)
nb_clusters_list.append(65_536)
elif nb_vectors < 300_000_000:
nb_clusters_list.append(65_536)
nb_clusters_list.append(2 ** 17)
nb_clusters_list.append(2 ** 18) # slow training !
else:
nb_clusters_list.append(2 ** 17)
nb_clusters_list.append(2 ** 18) # slow training !
nb_clusters_list.append(65_536)
nb_clusters_list.append(2 ** 20) # very slow training !
nb_clusters_list = [int(x) for x in nb_clusters_list]
if not nb_clusters_list:
return [256] # default value
return nb_clusters_list
def get_optimal_index_keys_v2(
nb_vectors: int,
dim_vector: int,
max_index_memory_usage: str,
flat_threshold: int = 1000,
quantization_threshold: int = 10000,
force_pq: Optional[int] = None,
make_direct_map: bool = False,
should_be_memory_mappable: bool = False,
ivf_flat_threshold: int = 1_000_000,
use_gpu: bool = False,
) -> List[str]:
"""
Gives a list of interesting indices to try, *the one at the top is the most promising*
See: https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index for
detailed explanations.
"""
# Exception cases:
if nb_vectors < flat_threshold: # When less than 1000 vectors, the flat index is usually faster
return ["IVF1,Flat" if should_be_memory_mappable else "Flat"]
if nb_vectors < quantization_threshold: # quantization is not possible (>=10_000 vectors needed)
if should_be_memory_mappable:
return get_optimal_ivf(nb_vectors)
return ["HNSW15"]
if force_pq is not None: # Forced quantization
return get_optimal_quantization(nb_vectors, dim_vector, force_quantization_value=force_pq)
# General cases:
# Get max memory usage
max_size_in_bytes = cast_memory_to_bytes(max_index_memory_usage)
if not should_be_memory_mappable:
# If we can build an HNSW with the given memory constraints, it's the best
m_hnsw = int(floor((max_size_in_bytes / (4 * nb_vectors) - dim_vector) / 2))
if m_hnsw >= 8:
return [f"HNSW{min(m_hnsw, 32)}"]
if nb_vectors < ivf_flat_threshold or use_gpu:
# Try to build a not quantized IVF index
index_keys = get_optimal_ivf(nb_vectors)
index_metadata = IndexMetadata(index_keys[0], nb_vectors, dim_vector, make_direct_map)
if index_metadata.estimated_index_size_in_bytes() <= max_size_in_bytes:
return index_keys
# Otherwise, there is not enough space, let's go for quantization
return get_optimal_quantization(nb_vectors, dim_vector, force_max_index_memory_usage=max_index_memory_usage)
def get_optimal_ivf(nb_vectors: int) -> List[str]:
"""
Function that returns a list of relevant index_keys to create not quantized IVF indices.
Parameters
----------
nb_vectors: int
Number of vectors in the dataset.
"""
index_keys = []
for nb_clusters in get_optimal_nb_clusters(nb_vectors):
index_keys.append(f"IVF{nb_clusters},Flat")
return index_keys
def get_optimal_quantization(
nb_vectors: int,
dim_vector: int,
force_quantization_value: Optional[int] = None,
force_max_index_memory_usage: Optional[str] = None,
) -> List[str]:
"""
Function that returns a list of relevant index_keys to create quantized indices.
Parameters:
----------
nb_vectors: int
Number of vectors in the dataset.
dim_vector: int
Dimension of the vectors in the dataset.
force_quantization_value: Optional[int]
Force to use this value as the size of the quantized vectors (PQx).
It can be used with the force_max_index_memory_usage parameter,
but the result might be empty.
force_max_index_memory_usage: Optional[str]
Add a memory constraint on the index.
It can be used with the force_quantization_value parameter,
but the result might be empty.
Return:
-------
index_keys: List[str]
List of index_keys that would be good choices for quantization.
The list can be empty if the given constraints are too strong.
"""
# Default values
pq_values = [256, 128, 64, 48, 32, 24, 16, 8, 4]
targeted_compression_ratio = 0.0 # 0 = no constraint
# Force compression ratio if required
if force_max_index_memory_usage is not None:
total_bytes = 4.0 * nb_vectors * dim_vector # x4 because float32
max_mem_bytes = float(cast_memory_to_bytes(force_max_index_memory_usage))
targeted_compression_ratio = total_bytes / max_mem_bytes
# Force quantization value if required
if force_quantization_value is not None:
pq_values = [force_quantization_value]
# Compute optimal number of clusters
relevant_list: List[str] = []
nb_clusters_list = get_optimal_nb_clusters(nb_vectors)
# Look for matching index keys
for pq in pq_values:
if pq < dim_vector:
for nb_clusters in nb_clusters_list:
# Compute quantized vector size
# https://github.com/facebookresearch/faiss/blob/main/faiss/invlists/InvertedLists.h#L193
embedding_id_byte = 8
vector_size_byte = pq + embedding_id_byte
# Compute compression ratio with quantization PQx
compression_ratio = (4 * dim_vector) / vector_size_byte
# Add index_key if compression ratio is high enough
if compression_ratio >= targeted_compression_ratio:
# y is a multiple of pq (required)
# y <= d, with d the dimension of the input vectors (preferable)
# y <= 6*pq (preferable)
# here we choose a y slightly bigger than d to avoid losing information
# in case such as 101, 128 is better than 64 to avoid losing information
# in the linear transform
y = (min(dim_vector // pq, 6) + 1) * pq
cluster_opt = f"IVF{nb_clusters}" if nb_clusters < 1000 else f"IVF{nb_clusters}_HNSW32"
relevant_list.append(f"OPQ{pq}_{y},{cluster_opt},PQ{pq}x8")
return relevant_list
T = TypeVar("T", int, float)
def get_min_param_value_for_best_neighbors_coverage(
index: faiss.Index,
parameter_range: List[T],
hyperparameter_str_from_param: Callable[[T], str],
targeted_nb_neighbors_to_query: int,
*,
targeted_coverage: float = 0.99,
use_gpu: bool = False,
) -> T:
"""
This function returns the minimal value to set in the index hyperparameters so that,
on average, the index retrieves 99% of the requested k=targeted_nb_neighbors_to_query nearest neighbors.
1 ^ ------------------------
| /
nearest | /
neighbors | /
coverage | /
| /
0 +--[--------------------------]--> param_value
^ ^ ^
| | |
| min_param_value |
| |
min(parameter_range) max(parameter_range)
Parameters
----------
index: faiss.Index
Index to search on.
parameter_range: List[T]
List of possible values for the hyperparameter. This list is sorted.
hyperparameter_str_from_param: Callable[[T], str]
Function to generate a hyperparameter string from the hyperparameter value
on which we do a binary search.
targeted_nb_neighbors_to_query: int
Targeted number of neighbors to query.
targeted_coverage: float
Targeted nearest neighbors coverage. The average ratio of neighbors really retrived
when asking for k=targeted_nb_neighbors_to_query nearest neighbors.
use_gpu: bool
Whether the index is on the GPU.
"""
# Initialize query vectors to run the benchmark
query_vectors = index.reconstruct_n(0, min(index.ntotal, 100))
# Function to compute the coverage of the nearest neighbors
def get_nearest_neighbors_coverage(k: int) -> float:
ind = index.search(query_vectors, k)[1]
return 1 - np.sum(ind == -1) / ind.size
# Display a warning if the targeted number of nearest neighbors is incoherent with the index size
if targeted_nb_neighbors_to_query > index.ntotal:
logger.warning(
f"The targeted number of nearest neighbors ({targeted_nb_neighbors_to_query}) "
f"is greater than the total number of vectors in the index ({index.ntotal}). "
"We set the targeted number of nearest neighbors to the total number of vectors."
)
targeted_nb_neighbors_to_query = index.ntotal
# Compute the max nearest neighbors coverage possible with the given hyperparameters
param_str = hyperparameter_str_from_param(parameter_range[-1])
set_search_hyperparameters(index, param_str, use_gpu)
max_nearest_neighbors_coverage = get_nearest_neighbors_coverage(targeted_nb_neighbors_to_query)
# If the index cannot reach the targeted coverage, we adapt it.
if max_nearest_neighbors_coverage < targeted_coverage:
logger.warning(
f"The maximum nearest neighbors coverage is {100*max_nearest_neighbors_coverage:.2f}% for this index. "
f"It means that when requesting {targeted_nb_neighbors_to_query} nearest neighbors, the average number "
f"of retrieved neighbors will be {round(targeted_nb_neighbors_to_query*max_nearest_neighbors_coverage)}. "
f"The program will try to find the best hyperparameters to reach 95% of this max coverage at least, "
"and then will optimize the search time for this target. "
"The index search speed could be higher than the requested max search speed."
)
# In that case there is a hard limit on the maximal nearest neighbors coverage.
# We redefine the new targeted coverage to reach the begining of the inflexion point
#
# 1 ^ <---- Initial target: 99% coverage
# |
# nearest | ------------------------- <---- New target 0.95*max_nearest_neighbors_coverage
# neighbors | /
# coverage | /
# | /
# 0 +--[--------------------------]--> param_value
# ^ ^ ^
# | | |
# | min_param_value |
# | |
# min(parameter_range) max(parameter_range)
targeted_coverage = 0.95 * max_nearest_neighbors_coverage
# Intialize the binary search
def is_meeting_constraint(rank: int) -> bool:
parameter_value = parameter_range[rank]
param_str = hyperparameter_str_from_param(parameter_value)
set_search_hyperparameters(index, param_str, use_gpu)
nearest_neighbors_coverage = get_nearest_neighbors_coverage(targeted_nb_neighbors_to_query)
return nearest_neighbors_coverage >= targeted_coverage
# Find the min param_value that reaches the targeted coverage
best_rank = max(0, discrete_binary_search(is_meeting_constraint, len(parameter_range)) - 1)
return parameter_range[best_rank]
def binary_search_on_param(
index: faiss.Index,
parameter_range: List[T],
max_speed_ms: float, # milliseconds
hyperparameter_str_from_param: Callable[[T], str],
timeout_boost_for_precision_search: float = 6.0,
use_gpu: bool = False,
max_timeout_per_iteration_s: float = 1.0, # seconds
) -> T:
"""
Apply a binary search on a given hyperparameter to maximize the recall given
a query speed constraint in milliseconds/query.
Parameters
----------
index: faiss.Index
Index to search on.
parameter_range: List[T]
List of possible values for the hyperparameter. This list is sorted.
max_speed_ms: float
Maximum query speed in milliseconds/query.
hyperparameter_str_from_param: Callable[[T], str]
Function to generate a hyperparameter string from the hyperparameter value
on which we do a binary search.
timeout_boost_for_precision_search: float
Timeout boost for the precision search phase.
use_gpu: bool
Whether the index is on the GPU.
max_timeout_per_iteration_s: float
Maximum timeout per iteration in seconds.
"""
query_vectors = index.reconstruct_n(0, min(index.ntotal, 4000))
timout_s = 15 * max_speed_ms / 1000
get_speed = partial(
speed_test_ms_per_query, query=query_vectors, ksearch=40, timout_s=min(max_timeout_per_iteration_s, timout_s)
)
def is_not_acceptable_speed(rank: int) -> bool:
parameter_value = parameter_range[rank]
param_str = hyperparameter_str_from_param(parameter_value)
set_search_hyperparameters(index, param_str, use_gpu)
speed = get_speed(index)
return speed >= max_speed_ms
best_rank = max(0, discrete_binary_search(is_not_acceptable_speed, len(parameter_range)) - 1)
# make sure that the query time is respected by spending X more time to evaluate the query speed
decreasing_ratio = 0.95
query_vectors = index.reconstruct_n(0, min(index.ntotal, 50000))
get_speed = partial(
speed_test_ms_per_query,
query=query_vectors,
ksearch=40,
timout_s=min(max_timeout_per_iteration_s, timeout_boost_for_precision_search * timout_s),
)
while is_not_acceptable_speed(best_rank) and best_rank > 1:
best_rank -= max(1, floor((1 - decreasing_ratio) * best_rank))
best_rank = max(0, min(best_rank, len(parameter_range) - 1))
return parameter_range[best_rank]
def get_optimal_hyperparameters(
index,
index_key: str,
max_speed_ms: float, # milliseconds
use_gpu: bool = False,
max_timeout_per_iteration_s: float = 1.0, # seconds
min_ef_search: int = 32,
min_nearest_neighbors_to_retrieve: int = 20,
) -> str:
"""Find the optimal hyperparameters to maximize the recall given a query speed in milliseconds/query"""
params = [int(x) for x in re.findall(r"\d+", index_key)]
if any(re.findall(r"OPQ\d+_\d+,IVF\d+,PQ\d+", index_key)):
ht = 2048
nb_clusters = int(params[2])
hyperparameter_str_from_param = lambda nprobe: f"nprobe={nprobe},ht={ht}"
parameter_range = list(range(1, min(6144, nb_clusters) + 1))
timeout_boost_for_precision_search = 6.0
elif any(re.findall(r"OPQ\d+_\d+,IVF\d+_HNSW\d+,PQ\d+", index_key)):
ht = 2048
nb_clusters = int(params[2])
hyperparameter_str_from_param = lambda nprobe: f"nprobe={nprobe},efSearch={2*nprobe},ht={ht}"
parameter_range = list(range(max(1, min_ef_search // 2), min(6144, nb_clusters) + 1))
timeout_boost_for_precision_search = 12.0
elif any(re.findall(r"HNSW\d+", index_key)):
hyperparameter_str_from_param = lambda ef_search: f"efSearch={ef_search}"
parameter_range = list(range(16, 2 ** 14))
timeout_boost_for_precision_search = 6.0
elif any(re.findall(r"IVF\d+,Flat", index_key)):
nb_clusters = int(params[0])
hyperparameter_str_from_param = lambda nprobe: f"nprobe={nprobe}"
parameter_range = list(range(1, nb_clusters + 1))
timeout_boost_for_precision_search = 6.0
elif index_key == "Flat":
return ""
else:
raise NotImplementedError(f"we don't have heuristics for that kind or index ({index_key})")
min_param_value = get_min_param_value_for_best_neighbors_coverage(
index, parameter_range, hyperparameter_str_from_param, min_nearest_neighbors_to_retrieve, use_gpu=use_gpu
)
parameter_range = [param_value for param_value in parameter_range if param_value >= min_param_value]
parameter_range = parameter_range or [min_param_value]
optimal_param = binary_search_on_param(
index,
parameter_range,
max_speed_ms,
hyperparameter_str_from_param,
timeout_boost_for_precision_search,
use_gpu,
max_timeout_per_iteration_s,
)
return hyperparameter_str_from_param(optimal_param)
def optimize_and_measure_index(
embedding_reader: EmbeddingReader,
index: faiss.Index,
index_infos_path: Optional[str],
index_key: str,
index_param: Optional[str],
index_path: Optional[str],
*,
max_index_query_time_ms: float,
min_nearest_neighbors_to_retrieve: int,
save_on_disk: bool,
use_gpu: bool,
):
"""Optimize one index by selecting the best hyperparameters and calculate its metrics"""
if index_param is None:
with Timeit(f"Computing best hyperparameters for index {index_path}", indent=1):
index_param = get_optimal_hyperparameters(
index,
index_key,
max_speed_ms=max_index_query_time_ms,
min_nearest_neighbors_to_retrieve=min_nearest_neighbors_to_retrieve,
use_gpu=use_gpu,
)
# Set search hyperparameters for the index
set_search_hyperparameters(index, index_param, use_gpu)
logger.info(f"The best hyperparameters are: {index_param}")
metric_infos = {"index_key": index_key, "index_param": index_param, "index_path": index_path}
with Timeit("Compute fast metrics", indent=1):
metric_infos.update(compute_fast_metrics(embedding_reader, index))
if save_on_disk:
with Timeit("Saving the index on local disk", indent=1):
with fsspec.open(index_path, "wb").open() as f:
faiss.write_index(index, faiss.PyCallbackIOWriter(f.write))
with fsspec.open(index_infos_path, "w").open() as f:
json.dump(metric_infos, f)
return metric_infos
|
"""
Index metadata for Faiss indices.
"""
import re
from enum import Enum
from math import ceil
from autofaiss.utils.cast import cast_bytes_to_memory_string
from autofaiss.external.descriptions import (
INDEX_DESCRIPTION_BLOCKS,
IndexBlock,
TUNABLE_PARAMETERS_DESCRIPTION_BLOCKS,
TunableParam,
)
class IndexType(Enum):
FLAT = 0
HNSW = 1
OPQ_IVF_PQ = 2
OPQ_IVF_HNSW_PQ = 3
PAD_IVF_HNSW_PQ = 4
NOT_SUPPORTED = 5
IVF_FLAT = 6
class IndexMetadata:
"""
Class to compute index metadata given the index_key, the number of vectors and their dimension.
Note: We don't create classes for each index type in order to keep the code simple.
"""
def __init__(self, index_key: str, nb_vectors: int, dim_vector: int, make_direct_map: bool = False):
self.index_key = index_key
self.nb_vectors = nb_vectors
self.dim_vector = dim_vector
self.fast_description = ""
self.description_blocs = []
self.tunable_params = []
self.params = {}
self.make_direct_map = make_direct_map
params = [int(x) for x in re.findall(r"\d+", index_key)]
if any(re.findall(r"OPQ\d+_\d+,IVF\d+,PQ\d+", index_key)):
self.index_type = IndexType.OPQ_IVF_PQ
self.fast_description = "An inverted file index (IVF) with quantization and OPQ preprocessing."
self.description_blocs = [IndexBlock.IVF, IndexBlock.PQ, IndexBlock.OPQ]
self.tunable_params = [TunableParam.NPROBE, TunableParam.HT]
self.params["pq"] = params[3]
self.params["nbits"] = params[4] if len(params) == 5 else 8 # default value
self.params["ncentroids"] = params[2]
self.params["out_d"] = params[1]
self.params["M_OPQ"] = params[0]
elif any(re.findall(r"OPQ\d+_\d+,IVF\d+_HNSW\d+,PQ\d+", index_key)):
self.index_type = IndexType.OPQ_IVF_HNSW_PQ
self.fast_description = "An inverted file index (IVF) with quantization, OPQ preprocessing, and HNSW index."
self.description_blocs = [IndexBlock.IVF_HNSW, IndexBlock.HNSW, IndexBlock.PQ, IndexBlock.OPQ]
self.tunable_params = [TunableParam.NPROBE, TunableParam.EFSEARCH, TunableParam.HT]
self.params["M_HNSW"] = params[3]
self.params["pq"] = params[4]
self.params["nbits"] = params[5] if len(params) == 6 else 8 # default value
self.params["ncentroids"] = params[2]
self.params["out_d"] = params[1]
self.params["M_OPQ"] = params[0]
elif any(re.findall(r"Pad\d+,IVF\d+_HNSW\d+,PQ\d+", index_key)):
self.index_type = IndexType.PAD_IVF_HNSW_PQ
self.fast_description = (
"An inverted file index (IVF) with quantization, a padding on input vectors, and HNSW index."
)
self.description_blocs = [IndexBlock.IVF_HNSW, IndexBlock.HNSW, IndexBlock.PQ, IndexBlock.PAD]
self.tunable_params = [TunableParam.NPROBE, TunableParam.EFSEARCH, TunableParam.HT]
self.params["out_d"] = params[0]
self.params["M_HNSW"] = params[2]
self.params["pq"] = params[3]
self.params["nbits"] = params[4] if len(params) == 5 else 8 # default value
self.params["ncentroids"] = params[1]
elif any(re.findall(r"HNSW\d+", index_key)):
self.index_type = IndexType.HNSW
self.fast_description = "An HNSW index."
self.description_blocs = [IndexBlock.HNSW]
self.tunable_params = [TunableParam.EFSEARCH]
self.params["M_HNSW"] = params[0]
elif any(re.findall(r"IVF\d+,Flat", index_key)):
self.index_type = IndexType.IVF_FLAT
self.fast_description = "An inverted file index (IVF) with no quantization"
self.description_blocs = [IndexBlock.IVF]
self.tunable_params = [TunableParam.NPROBE]
self.params["ncentroids"] = params[0]
elif index_key == "Flat":
self.index_type = IndexType.FLAT
self.fast_description = "A simple flat index."
self.description_blocs = [IndexBlock.FLAT]
self.tunable_params = []
else:
self.index_type = IndexType.NOT_SUPPORTED
self.fast_description = "No description for this index, feel free to contribute :)"
self.description_blocs = []
self.tunable_params = []
def get_index_type(self) -> IndexType:
"""
return the index type.
"""
return self.index_type
def estimated_index_size_in_bytes(self) -> int:
"""
Compute the estimated size of the index in bytes.
"""
if self.index_type == IndexType.FLAT:
return self.nb_vectors * self.dim_vector * 4
if self.index_type == IndexType.HNSW:
# M bidirectional links per vector in the HNSW graph
hnsw_graph_in_bytes = self.nb_vectors * self.params["M_HNSW"] * 2 * 4
vectors_size_in_bytes = self.nb_vectors * self.dim_vector * 4
return vectors_size_in_bytes + hnsw_graph_in_bytes
if self.index_type in [IndexType.OPQ_IVF_PQ, IndexType.OPQ_IVF_HNSW_PQ, IndexType.PAD_IVF_HNSW_PQ]:
direct_map_overhead = 8 * self.nb_vectors if self.make_direct_map else 0
# We neglict the size of the OPQ table for the moment.
code_size = ceil(self.params["pq"] * self.params["nbits"] / 8)
# https://github.com/facebookresearch/faiss/blob/main/faiss/invlists/InvertedLists.h#L193
embedding_id_byte = 8
vector_size_byte = code_size + embedding_id_byte
vectors_size_in_bytes = self.nb_vectors * vector_size_byte
centroid_size_in_bytes = self.params["ncentroids"] * self.dim_vector * 4
total_size_in_byte = direct_map_overhead + vectors_size_in_bytes + centroid_size_in_bytes
if self.index_type in [IndexType.OPQ_IVF_HNSW_PQ, IndexType.PAD_IVF_HNSW_PQ]:
total_size_in_byte += self.params["ncentroids"] * self.params["M_HNSW"] * 2 * 4
if self.index_type in [IndexType.OPQ_IVF_PQ, IndexType.OPQ_IVF_HNSW_PQ]:
total_size_in_byte += self.params["M_OPQ"] * self.params["out_d"] * 4
return total_size_in_byte
if self.index_type == IndexType.IVF_FLAT:
direct_map_overhead = 8 * self.nb_vectors if self.make_direct_map else 0
vectors_size_in_bytes = self.nb_vectors * self.dim_vector * 4
centroid_size_in_bytes = self.params["ncentroids"] * self.dim_vector * 4
return direct_map_overhead + vectors_size_in_bytes + centroid_size_in_bytes
return -1
def get_index_description(self, tunable_parameters_infos=False) -> str:
"""
Gives a generic description of the index.
"""
description = self.fast_description
if self.index_type == IndexType.NOT_SUPPORTED:
return description
description += "\n"
index_size_string = cast_bytes_to_memory_string(self.estimated_index_size_in_bytes())
description += f"The size of the index should be around {index_size_string}.\n\n"
description += "\n".join(INDEX_DESCRIPTION_BLOCKS[desc] for desc in self.description_blocs) + "\n\n"
if tunable_parameters_infos:
if not self.tunable_params:
description += "No parameters can be tuned to find a query speed VS recall tradeoff\n\n"
else:
description += "List of parameters that can be tuned to find a query speed VS recall tradeoff:\n"
description += (
"\n".join(TUNABLE_PARAMETERS_DESCRIPTION_BLOCKS[desc] for desc in self.tunable_params) + "\n\n"
)
description += """
For all indices except the flat index, the query speed can be adjusted.
The lower the speed limit the lower the recall. With a looser constraint
on the query time, the recall can be higher, but it is limited by the index
structure (if there is quantization for instance).
"""
return description
def compute_memory_necessary_for_training(self, nb_training_vectors: int) -> float:
"""
Function that computes the memory necessary to train an index with nb_training_vectors vectors
"""
if self.index_type == IndexType.FLAT:
return 0
elif self.index_type == IndexType.IVF_FLAT:
return self.compute_memory_necessary_for_ivf_flat(nb_training_vectors)
elif self.index_type == IndexType.HNSW:
return 0
elif self.index_type == IndexType.OPQ_IVF_PQ:
return self.compute_memory_necessary_for_opq_ivf_pq(nb_training_vectors)
elif self.index_type == IndexType.OPQ_IVF_HNSW_PQ:
return self.compute_memory_necessary_for_opq_ivf_hnsw_pq(nb_training_vectors)
elif self.index_type == IndexType.PAD_IVF_HNSW_PQ:
return self.compute_memory_necessary_for_pad_ivf_hnsw_pq(nb_training_vectors)
else:
return 500 * 10 ** 6
def compute_memory_necessary_for_ivf_flat(self, nb_training_vectors: int):
"""Compute the memory estimation for index type IVF_FLAT."""
ivf_memory_in_bytes = self._get_ivf_training_memory_usage_in_bytes()
# TODO: remove x1.5 when estimation is correct
return self._get_vectors_training_memory_usage_in_bytes(nb_training_vectors) * 1.5 + ivf_memory_in_bytes
def compute_memory_necessary_for_opq_ivf_pq(self, nb_training_vectors: int) -> float:
"""Compute the memory estimation for index type OPQ_IVF_PQ."""
# TODO: remove x1.5 when estimation is correct
return (
self._get_vectors_training_memory_usage_in_bytes(nb_training_vectors) * 1.5
+ self._get_opq_training_memory_usage_in_bytes(nb_training_vectors)
+ self._get_ivf_training_memory_usage_in_bytes()
+ self._get_pq_training_memory_usage_in_bytes()
)
def compute_memory_necessary_for_opq_ivf_hnsw_pq(self, nb_training_vectors: int) -> float:
"""Compute the memory estimation for index type OPQ_IVF_HNSW_PQ."""
# TODO: remove x1.5 when estimation is correct
return (
self._get_vectors_training_memory_usage_in_bytes(nb_training_vectors) * 1.5
+ self._get_opq_training_memory_usage_in_bytes(nb_training_vectors)
+ self._get_ivf_training_memory_usage_in_bytes()
+ self._get_ivf_hnsw_training_memory_usage_in_bytes()
+ self._get_pq_training_memory_usage_in_bytes()
)
def compute_memory_necessary_for_pad_ivf_hnsw_pq(self, nb_training_vectors: int):
"""Compute the memory estimation for index type PAD_IVF_HNSW_PQ."""
# TODO: remove x1.5 when estimation is correct
return (
self._get_vectors_training_memory_usage_in_bytes(nb_training_vectors) * 1.5
+ self._get_ivf_training_memory_usage_in_bytes()
+ self._get_ivf_hnsw_training_memory_usage_in_bytes()
+ self._get_pq_training_memory_usage_in_bytes()
)
def _get_vectors_training_memory_usage_in_bytes(self, nb_training_vectors: int):
"""Get vectors memory estimation in bytes."""
return 4.0 * self.dim_vector * nb_training_vectors
def _get_ivf_training_memory_usage_in_bytes(self):
"""Get IVF memory estimation in bytes."""
return 4.0 * self.params["ncentroids"] * self.dim_vector
def _get_ivf_hnsw_training_memory_usage_in_bytes(self):
"""Get HNSW followed by IVF memory estimation in bytes."""
hnsw_graph_in_bytes = self.params["ncentroids"] * self.params["M_HNSW"] * 2 * 4
vectors_size_in_bytes = self.params["ncentroids"] * self.dim_vector * 4
return vectors_size_in_bytes + hnsw_graph_in_bytes
def _get_opq_training_memory_usage_in_bytes(self, nb_training_vectors: int):
"""Get OPQ memory estimation in bytes."""
# see OPQMatrix::train on https://github.com/facebookresearch/faiss/blob/main/faiss/VectorTransform.cpp#L987
d_in, d_out, code_size = self.dim_vector, self.params["out_d"], self.params["M_OPQ"]
n = min(256 * 256, nb_training_vectors)
d = max(d_in, d_out)
d2 = d_out
xproj = d2 * n
pq_recons = d2 * n
xxr = d * n
tmp = d * d * 4
mem_code_size = code_size * n
opq_memory_in_bytes = (xproj + pq_recons + xxr + tmp) * 4.0 + mem_code_size * 1.0
return opq_memory_in_bytes
def _get_pq_training_memory_usage_in_bytes(self):
"""Get PQ memory estimation in bytes."""
return ceil(self.params["pq"] * self.params["nbits"] / 8)
def compute_memory_necessary_for_training_wrapper(nb_training_vectors: int, index_key: str, dim_vector: int):
# nb_vectors is useless for training memory estimation, so just put -1
return IndexMetadata(index_key, -1, dim_vector).compute_memory_necessary_for_training(
nb_training_vectors=nb_training_vectors
)
|
""" main file to create an index from the the begining """
import json
import logging
import logging.config
import multiprocessing
import os
import tempfile
from typing import Dict, List, Optional, Tuple, Union
from embedding_reader import EmbeddingReader
import faiss
import fire
import fsspec
import numpy as np
from autofaiss.indices.build import get_write_ids_df_to_parquet_fn, get_optimize_index_fn
from autofaiss.external.build import (
create_index,
create_partitioned_indexes,
estimate_memory_required_for_index_creation,
get_estimated_construction_time_infos,
)
from autofaiss.indices.training import create_empty_index
from autofaiss.external.optimize import get_optimal_hyperparameters, get_optimal_index_keys_v2
from autofaiss.external.scores import compute_fast_metrics, compute_medium_metrics
from autofaiss.indices.index_utils import set_search_hyperparameters
from autofaiss.utils.path import make_path_absolute
from autofaiss.utils.cast import cast_bytes_to_memory_string, cast_memory_to_bytes
from autofaiss.utils.decorators import Timeit
logger = logging.getLogger("autofaiss")
def _log_output_dict(infos: Dict):
logger.info("{")
for key, value in infos.items():
logger.info(f"\t{key}: {value}")
logger.info("}")
def setup_logging(logging_level: int):
"""Setup the logging."""
logging.config.dictConfig(dict(version=1, disable_existing_loggers=False))
logging_format = "%(asctime)s [%(levelname)s]: %(message)s"
logging.basicConfig(level=logging_level, format=logging_format)
def build_index(
embeddings: Union[str, np.ndarray, List[str]],
index_path: Optional[str] = "knn.index",
index_infos_path: Optional[str] = "index_infos.json",
ids_path: Optional[str] = None,
save_on_disk: bool = True,
file_format: str = "npy",
embedding_column_name: str = "embedding",
id_columns: Optional[List[str]] = None,
index_key: Optional[str] = None,
index_param: Optional[str] = None,
max_index_query_time_ms: float = 10.0,
max_index_memory_usage: str = "16G",
min_nearest_neighbors_to_retrieve: int = 20,
current_memory_available: str = "32G",
use_gpu: bool = False,
metric_type: str = "ip",
nb_cores: Optional[int] = None,
make_direct_map: bool = False,
should_be_memory_mappable: bool = False,
distributed: Optional[str] = None,
temporary_indices_folder: str = "hdfs://root/tmp/distributed_autofaiss_indices",
verbose: int = logging.INFO,
nb_indices_to_keep: int = 1,
) -> Tuple[Optional[faiss.Index], Optional[Dict[str, str]]]:
"""
Reads embeddings and creates a quantized index from them.
The index is stored on the current machine at the given output path.
Parameters
----------
embeddings : Union[str, np.ndarray, List[str]]
Local path containing all preprocessed vectors and cached files.
This could be a single directory or multiple directories.
Files will be added if empty.
Or directly the Numpy array of embeddings
index_path: Optional(str)
Destination path of the quantized model.
index_infos_path: Optional(str)
Destination path of the metadata file.
ids_path: Optional(str)
Only useful when id_columns is not None and file_format=`parquet`. T
his will be the path (in any filesystem)
where the mapping files Ids->vector index will be store in parquet format
save_on_disk: bool
Whether to save the index on disk, default to True.
file_format: Optional(str)
npy or parquet ; default npy
embedding_column_name: Optional(str)
embeddings column name for parquet ; default embedding
id_columns: Optional(List[str])
Can only be used when file_format=`parquet`.
In this case these are the names of the columns containing the Ids of the vectors,
and separate files will be generated to map these ids to indices in the KNN index ;
default None
index_key: Optional(str)
Optional string to give to the index factory in order to create the index.
If None, an index is chosen based on an heuristic.
index_param: Optional(str)
Optional string with hyperparameters to set to the index.
If None, the hyper-parameters are chosen based on an heuristic.
max_index_query_time_ms: float
Bound on the query time for KNN search, this bound is approximative
max_index_memory_usage: str
Maximum size allowed for the index, this bound is strict
min_nearest_neighbors_to_retrieve: int
Minimum number of nearest neighbors to retrieve when querying the index.
Parameter used only during index hyperparameter finetuning step, it is
not taken into account to select the indexing algorithm.
This parameter has the priority over the max_index_query_time_ms constraint.
current_memory_available: str
Memory available on the machine creating the index, having more memory is a boost
because it reduces the swipe between RAM and disk.
use_gpu: bool
Experimental, gpu training is faster, not tested so far
metric_type: str
Similarity function used for query:
- "ip" for inner product
- "l2" for euclidian distance
nb_cores: Optional[int]
Number of cores to use. Will try to guess the right number if not provided
make_direct_map: bool
Create a direct map allowing reconstruction of embeddings. This is only needed for IVF indices.
Note that might increase the RAM usage (approximately 8GB for 1 billion embeddings)
should_be_memory_mappable: bool
If set to true, the created index will be selected only among the indices that can be memory-mapped on disk.
This makes it possible to use 50GB indices on a machine with only 1GB of RAM. Default to False
distributed: Optional[str]
If "pyspark", create the indices using pyspark.
Only "parquet" file format is supported.
temporary_indices_folder: str
Folder to save the temporary small indices that are generated by each spark executor.
Only used when distributed = "pyspark".
verbose: int
set verbosity of outputs via logging level, default is `logging.INFO`
nb_indices_to_keep: int
Number of indices to keep at most when distributed is "pyspark".
It allows you to build an index larger than `current_memory_available`
If it is not equal to 1,
- You are expected to have at most `nb_indices_to_keep` indices with the following names:
"{index_path}i" where i ranges from 1 to `nb_indices_to_keep`
- `build_index` returns a mapping from index path to metrics
Default to 1.
"""
setup_logging(verbose)
# if using distributed mode, it doesn't make sense to use indices that are not memory mappable
if distributed == "pyspark":
should_be_memory_mappable = True
if index_path:
index_path = make_path_absolute(index_path)
elif save_on_disk:
logger.error("Please specify a index_path if you set save_on_disk as True")
return None, None
if index_infos_path:
index_infos_path = make_path_absolute(index_infos_path)
elif save_on_disk:
logger.error("Please specify a index_infos_path if you set save_on_disk as True")
return None, None
if ids_path:
ids_path = make_path_absolute(ids_path)
if nb_indices_to_keep < 1:
logger.error("Please specify nb_indices_to_keep an integer value larger or equal to 1")
return None, None
elif nb_indices_to_keep > 1:
if distributed is None:
logger.error('nb_indices_to_keep can only be larger than 1 when distributed is "pyspark"')
return None, None
if not save_on_disk:
logger.error("Please set save_on_disk to True when nb_indices_to_keep is larger than 1")
return None, None
current_bytes = cast_memory_to_bytes(current_memory_available)
max_index_bytes = cast_memory_to_bytes(max_index_memory_usage)
memory_left = current_bytes - max_index_bytes
if nb_indices_to_keep == 1 and memory_left < current_bytes * 0.1:
logger.error(
"You do not have enough memory to build this index, "
"please increase current_memory_available or decrease max_index_memory_usage"
)
return None, None
if nb_cores is None:
nb_cores = multiprocessing.cpu_count()
logger.info(f"Using {nb_cores} omp threads (processes), consider increasing --nb_cores if you have more")
faiss.omp_set_num_threads(nb_cores)
if isinstance(embeddings, np.ndarray):
tmp_dir_embeddings = tempfile.TemporaryDirectory()
np.save(os.path.join(tmp_dir_embeddings.name, "emb.npy"), embeddings)
embeddings_path = tmp_dir_embeddings.name
else:
embeddings_path = embeddings # type: ignore
with Timeit("Launching the whole pipeline"):
with Timeit("Reading total number of vectors and dimension"):
embedding_reader = EmbeddingReader(
embeddings_path,
file_format=file_format,
embedding_column=embedding_column_name,
meta_columns=id_columns,
)
nb_vectors = embedding_reader.count
vec_dim = embedding_reader.dimension
logger.info(f"There are {nb_vectors} embeddings of dim {vec_dim}")
with Timeit("Compute estimated construction time of the index", indent=1):
for log_lines in get_estimated_construction_time_infos(nb_vectors, vec_dim, indent=2).split("\n"):
logger.info(log_lines)
with Timeit("Checking that your have enough memory available to create the index", indent=1):
necessary_mem, index_key_used = estimate_memory_required_for_index_creation(
nb_vectors, vec_dim, index_key, max_index_memory_usage, make_direct_map, nb_indices_to_keep
)
logger.info(
f"{cast_bytes_to_memory_string(necessary_mem)} of memory "
"will be needed to build the index (more might be used if you have more)"
)
prefix = "(default) " if index_key is None else ""
if necessary_mem > cast_memory_to_bytes(current_memory_available):
r = (
f"The current memory available on your machine ({current_memory_available}) is not "
f"enough to create the {prefix}index {index_key_used} that requires "
f"{cast_bytes_to_memory_string(necessary_mem)} to train. "
"You can decrease the number of clusters of you index since the Kmeans algorithm "
"used for clusterisation is responsible for this high memory usage."
"Consider increasing the options current_memory_available or decreasing max_index_memory_usage"
)
logger.error(r)
return None, None
if index_key is None:
with Timeit("Selecting most promising index types given data characteristics", indent=1):
best_index_keys = get_optimal_index_keys_v2(
nb_vectors,
vec_dim,
max_index_memory_usage,
make_direct_map=make_direct_map,
should_be_memory_mappable=should_be_memory_mappable,
use_gpu=use_gpu,
)
if not best_index_keys:
return None, None
index_key = best_index_keys[0]
if id_columns is not None:
logger.info(f"Id columns provided {id_columns} - will be reading the corresponding columns")
if ids_path is not None:
logger.info(f"\tWill be writing the Ids DataFrame in parquet format to {ids_path}")
fs, _ = fsspec.core.url_to_fs(ids_path, use_listings_cache=False)
if fs.exists(ids_path):
fs.rm(ids_path, recursive=True)
fs.mkdirs(ids_path)
else:
logger.error(
"\tAs ids_path=None - the Ids DataFrame will not be written and will be ignored subsequently"
)
logger.error("\tPlease provide a value ids_path for the Ids to be written")
write_ids_df_to_parquet_fn = get_write_ids_df_to_parquet_fn(ids_path) if ids_path and id_columns else None
optimize_index_fn = get_optimize_index_fn(
embedding_reader=embedding_reader,
index_key=index_key,
index_path=index_path,
index_infos_path=index_infos_path,
use_gpu=use_gpu,
save_on_disk=save_on_disk,
max_index_query_time_ms=max_index_query_time_ms,
min_nearest_neighbors_to_retrieve=min_nearest_neighbors_to_retrieve,
index_param=index_param,
make_direct_map=make_direct_map,
)
with Timeit("Creating the index", indent=1):
index, metric_infos = create_index(
embedding_reader,
index_key,
metric_type,
current_memory_available,
use_gpu=use_gpu,
embedding_ids_df_handler=write_ids_df_to_parquet_fn,
make_direct_map=make_direct_map,
distributed_engine=distributed,
temporary_indices_folder=temporary_indices_folder,
nb_indices_to_keep=nb_indices_to_keep,
index_optimizer=optimize_index_fn,
)
if metric_infos:
_log_output_dict(metric_infos)
return index, metric_infos
def build_partitioned_indexes(
partitions: List[str],
output_root_dir: str,
embedding_column_name: str = "embedding",
index_key: Optional[str] = None,
index_path: Optional[str] = None,
id_columns: Optional[List[str]] = None,
max_index_query_time_ms: float = 10.0,
max_index_memory_usage: str = "16G",
min_nearest_neighbors_to_retrieve: int = 20,
current_memory_available: str = "32G",
use_gpu: bool = False,
metric_type: str = "ip",
nb_cores: Optional[int] = None,
make_direct_map: bool = False,
should_be_memory_mappable: bool = False,
temp_root_dir: str = "hdfs://root/tmp/distributed_autofaiss_indices",
verbose: int = logging.INFO,
nb_splits_per_big_index: int = 1,
big_index_threshold: int = 5_000_000,
maximum_nb_threads: int = 256,
) -> List[Optional[Dict[str, str]]]:
"""
Create partitioned indexes from a partitioned parquet dataset,
i.e. create one index per parquet partition
Only supported with PySpark. A PySpark session must be active before calling this function
Parameters
----------
partitions : str
List of partitions containing embeddings
output_root_dir: str
Output root directory where indexes, metrics and ids will be written
embedding_column_name: str
Parquet dataset column name containing embeddings
index_key: Optional(str)
Optional string to give to the index factory in order to create the index.
If None, an index is chosen based on an heuristic.
index_path: Optional(str)
Optional path to an index that will be used to add embeddings.
This index must be pre-trained if it needs a training
id_columns: Optional(List[str])
Parquet dataset column name(s) that are used as IDs for embeddings.
A mapping from these IDs to faiss indices will be written in separate files.
max_index_query_time_ms: float
Bound on the query time for KNN search, this bound is approximative
max_index_memory_usage: str
Maximum size allowed for the index, this bound is strict
min_nearest_neighbors_to_retrieve: int
Minimum number of nearest neighbors to retrieve when querying the index.
Parameter used only during index hyperparameter finetuning step, it is
not taken into account to select the indexing algorithm.
This parameter has the priority over the max_index_query_time_ms constraint.
current_memory_available: str
Memory available on the machine creating the index, having more memory is a boost
because it reduces the swipe between RAM and disk.
use_gpu: bool
Experimental, gpu training is faster, not tested so far
metric_type: str
Similarity function used for query:
- "ip" for inner product
- "l2" for euclidean distance
nb_cores: Optional[int]
Number of cores to use. Will try to guess the right number if not provided
make_direct_map: bool
Create a direct map allowing reconstruction of embeddings. This is only needed for IVF indices.
Note that might increase the RAM usage (approximately 8GB for 1 billion embeddings)
should_be_memory_mappable: bool
If set to true, the created index will be selected only among the indices that can be memory-mapped on disk.
This makes it possible to use 50GB indices on a machine with only 1GB of RAM. Default to False
temp_root_dir: str
Temporary directory that will be used to store intermediate results/computation
verbose: int
set verbosity of outputs via logging level, default is `logging.INFO`
nb_splits_per_big_index: int
Number of indices to split a big index into.
This allows you building indices bigger than `current_memory_available`.
big_index_threshold: int
Threshold used to define big indexes.
Indexes with more `than big_index_threshold` embeddings are considered big indexes.
maximum_nb_threads: int
Maximum number of threads to parallelize index creation
"""
setup_logging(verbose)
# Sanity checks
if not partitions:
raise ValueError("partitions can't be empty")
check_not_null_not_empty("output_root_dir", output_root_dir)
check_not_null_not_empty("embedding_column_name", embedding_column_name)
if nb_splits_per_big_index < 1:
raise ValueError(f"nb_indices_to_keep must be > 0; Got {nb_splits_per_big_index}")
if big_index_threshold < 1:
raise ValueError(f"big_index_threshold must be > 0; Got {big_index_threshold}")
if index_path is not None and not index_key:
raise ValueError(
"Please provide the index key of the input index; "
f"Got index_key: {index_key} and index_path: {index_path}"
)
if index_key:
n_dimensions = EmbeddingReader(
partitions[0], file_format="parquet", embedding_column=embedding_column_name
).dimension
# Create an empty index to validate the index key
create_empty_index(n_dimensions, index_key=index_key, metric_type=metric_type)
# Create partitioned indexes
return create_partitioned_indexes(
partitions=partitions,
output_root_dir=output_root_dir,
embedding_column_name=embedding_column_name,
index_key=index_key,
index_path=index_path,
id_columns=id_columns,
should_be_memory_mappable=should_be_memory_mappable,
max_index_query_time_ms=max_index_query_time_ms,
max_index_memory_usage=max_index_memory_usage,
min_nearest_neighbors_to_retrieve=min_nearest_neighbors_to_retrieve,
current_memory_available=current_memory_available,
use_gpu=use_gpu,
metric_type=metric_type,
nb_cores=nb_cores,
make_direct_map=make_direct_map,
temp_root_dir=temp_root_dir,
nb_splits_per_big_index=nb_splits_per_big_index,
big_index_threshold=big_index_threshold,
maximum_nb_threads=maximum_nb_threads,
)
def check_not_null_not_empty(name: str, value: str):
if not value:
raise ValueError(f"{name} can't be None or empty; Got {value}")
def tune_index(
index_path: Union[str, faiss.Index],
index_key: str,
index_param: Optional[str] = None,
output_index_path: Optional[str] = "tuned_knn.index",
save_on_disk: bool = True,
min_nearest_neighbors_to_retrieve: int = 20,
max_index_query_time_ms: float = 10.0,
use_gpu: bool = False,
verbose: int = logging.INFO,
) -> faiss.Index:
"""
Set hyperparameters to the given index.
If an index_param is given, set this hyperparameters to the index,
otherwise perform a greedy heusistic to make the best out or the max_index_query_time_ms constraint
Parameters
----------
index_path : Union[str, faiss.Index]
Path to .index file
Can also be an index
index_key: str
String to give to the index factory in order to create the index.
index_param: Optional(str)
Optional string with hyperparameters to set to the index.
If None, the hyper-parameters are chosen based on an heuristic.
output_index_path: str
Path to the newly created .index file
save_on_disk: bool
Whether to save the index on disk, default to True.
min_nearest_neighbors_to_retrieve: int
Minimum number of nearest neighbors to retrieve when querying the index.
max_index_query_time_ms: float
Query speed constraint for the index to create.
use_gpu: bool
Experimental, gpu training is faster, not tested so far.
verbose: int
set verbosity of outputs via logging level, default is `logging.INFO`
Returns
-------
index
The faiss index
"""
setup_logging(verbose)
if isinstance(index_path, str):
index_path = make_path_absolute(index_path)
with fsspec.open(index_path, "rb").open() as f:
index = faiss.read_index(faiss.PyCallbackIOReader(f.read))
else:
index = index_path
if index_param is None:
with Timeit("Compute best hyperparameters"):
index_param = get_optimal_hyperparameters(
index,
index_key,
max_speed_ms=max_index_query_time_ms,
min_nearest_neighbors_to_retrieve=min_nearest_neighbors_to_retrieve,
)
with Timeit("Set search hyperparameters for the index"):
set_search_hyperparameters(index, index_param, use_gpu)
logger.info(f"The optimal hyperparameters are {index_param}.")
if save_on_disk:
with fsspec.open(output_index_path, "wb").open() as f:
faiss.write_index(index, faiss.PyCallbackIOWriter(f.write))
logger.info("The index with these parameters has been saved on disk.")
return index
def score_index(
index_path: Union[str, faiss.Index],
embeddings: Union[str, np.ndarray],
save_on_disk: bool = True,
output_index_info_path: str = "infos.json",
current_memory_available: str = "32G",
verbose: int = logging.INFO,
) -> Optional[Dict[str, Union[str, float, int]]]:
"""
Compute metrics on a given index, use cached ground truth for fast scoring the next times.
Parameters
----------
index_path : Union[str, faiss.Index]
Path to .index file. Or in memory index
embeddings: Union[str, np.ndarray]
Path containing all preprocessed vectors and cached files. Can also be an in memory array.
save_on_disk: bool
Whether to save on disk
output_index_info_path : str
Path to index infos .json
current_memory_available: str
Memory available on the current machine, having more memory is a boost
because it reduces the swipe between RAM and disk.
verbose: int
set verbosity of outputs via logging level, default is `logging.INFO`
Returns
-------
metric_infos: Optional[Dict[str, Union[str, float, int]]]
Metric infos of the index.
"""
setup_logging(verbose)
faiss.omp_set_num_threads(multiprocessing.cpu_count())
if isinstance(index_path, str):
index_path = make_path_absolute(index_path)
with fsspec.open(index_path, "rb").open() as f:
index = faiss.read_index(faiss.PyCallbackIOReader(f.read))
fs, path_in_fs = fsspec.core.url_to_fs(index_path, use_listings_cache=False)
index_memory = fs.size(path_in_fs)
else:
index = index_path
with tempfile.NamedTemporaryFile("wb") as f:
faiss.write_index(index, faiss.PyCallbackIOWriter(f.write))
fs, path_in_fs = fsspec.core.url_to_fs(f.name, use_listings_cache=False)
index_memory = fs.size(path_in_fs)
if isinstance(embeddings, np.ndarray):
tmp_dir_embeddings = tempfile.TemporaryDirectory()
np.save(os.path.join(tmp_dir_embeddings.name, "emb.npy"), embeddings)
embeddings_path = tmp_dir_embeddings.name
else:
embeddings_path = embeddings
embedding_reader = EmbeddingReader(embeddings_path, file_format="npy")
infos: Dict[str, Union[str, float, int]] = {}
with Timeit("Compute fast metrics"):
infos.update(compute_fast_metrics(embedding_reader, index))
logger.info("Intermediate recap:")
_log_output_dict(infos)
current_in_bytes = cast_memory_to_bytes(current_memory_available)
memory_left = current_in_bytes - index_memory
if memory_left < current_in_bytes * 0.1:
logger.info(
f"Not enough memory, at least {cast_bytes_to_memory_string(index_memory * 1.1)}"
"is needed, please increase current_memory_available"
)
return None
with Timeit("Compute medium metrics"):
infos.update(compute_medium_metrics(embedding_reader, index, memory_left))
logger.info("Performances recap:")
_log_output_dict(infos)
if save_on_disk:
with fsspec.open(output_index_info_path, "w").open() as f:
json.dump(infos, f)
return infos
def main():
"""Main entry point"""
fire.Fire(
{
"build_index": build_index,
"tune_index": tune_index,
"score_index": score_index,
"build_partitioned_indexes": build_partitioned_indexes,
}
)
if __name__ == "__main__":
main()
|
""" Functions to compute metrics on an index """
import fsspec
from typing import Dict, Union, Optional
import numpy as np
import faiss
from embedding_reader import EmbeddingReader
from autofaiss.indices.index_utils import get_index_size, search_speed_test
from autofaiss.indices.memory_efficient_flat_index import MemEfficientFlatIndex
from autofaiss.metrics.recalls import one_recall_at_r, r_recall_at_r
from autofaiss.metrics.reconstruction import quantize_vec_without_modifying_index, reconstruction_error
from autofaiss.utils.cast import cast_memory_to_bytes
from autofaiss.utils.decorators import Timeit
def compute_fast_metrics(
embedding_reader: Union[np.ndarray, EmbeddingReader],
index: faiss.Index,
omp_threads: Optional[int] = None,
query_max: Optional[int] = 1000,
) -> Dict:
"""compute query speed, size and reconstruction of an index"""
infos: Dict[str, Union[str, int, float]] = {}
size_bytes = get_index_size(index)
infos["size in bytes"] = size_bytes
if isinstance(embedding_reader, EmbeddingReader):
# pylint: disable=bare-except
query_embeddings, _ = next(embedding_reader(start=0, end=query_max, batch_size=query_max))
else:
query_embeddings = embedding_reader[:query_max]
if omp_threads:
faiss.omp_set_num_threads(1)
speeds_ms = search_speed_test(index, query_embeddings, ksearch=40, timout_s=10.0)
if omp_threads:
faiss.omp_set_num_threads(omp_threads)
infos.update(speeds_ms)
# quantize query embeddings if the index uses quantization
quantized_embeddings = quantize_vec_without_modifying_index(index, query_embeddings)
rec_error = reconstruction_error(query_embeddings, quantized_embeddings)
infos["reconstruction error %"] = 100 * rec_error
infos["nb vectors"] = index.ntotal
infos["vectors dimension"] = index.d
infos["compression ratio"] = 4.0 * index.ntotal * index.d / size_bytes
return infos
def compute_medium_metrics(
embedding_reader: Union[np.ndarray, EmbeddingReader],
index: faiss.Index,
memory_available: Union[str, float],
ground_truth: Optional[np.ndarray] = None,
eval_item_ids: Optional[np.ndarray] = None,
) -> Dict[str, float]:
"""Compute recall@R and intersection recall@R of an index"""
nb_test_points = 500
if isinstance(embedding_reader, EmbeddingReader):
query_embeddings, _ = next(embedding_reader(start=0, end=nb_test_points, batch_size=nb_test_points))
else:
embedding_block = embedding_reader
query_embeddings = embedding_block[:nb_test_points]
if ground_truth is None:
if isinstance(embedding_reader, EmbeddingReader):
ground_truth_path = f"{embedding_reader.embeddings_folder}/small_ground_truth_test.gt"
fs, path = fsspec.core.url_to_fs(ground_truth_path, use_listings_cache=False)
if not fs.exists(path):
with Timeit("-> Compute small ground truth", indent=1):
ground_truth = get_ground_truth(
index.metric_type, embedding_reader, query_embeddings, memory_available
)
with fs.open(path, "wb") as gt_file:
np.save(gt_file, ground_truth)
else:
with Timeit("-> Load small ground truth", indent=1):
with fs.open(path, "rb") as gt_file:
ground_truth = np.load(gt_file)
else:
ground_truth = get_ground_truth(index.metric_type, embedding_block, query_embeddings, memory_available)
with Timeit("-> Compute recalls", indent=1):
one_recall = one_recall_at_r(query_embeddings, ground_truth, index, 40, eval_item_ids)
intersection_recall = r_recall_at_r(query_embeddings, ground_truth, index, 40, eval_item_ids)
infos: Dict[str, float] = {}
infos["1-recall@20"] = one_recall[20 - 1]
infos["1-recall@40"] = one_recall[40 - 1]
infos["20-recall@20"] = intersection_recall[20 - 1]
infos["40-recall@40"] = intersection_recall[40 - 1]
return infos
def get_ground_truth(
faiss_metric_type: int,
embedding_reader: Union[np.ndarray, EmbeddingReader],
query_embeddings: np.ndarray,
memory_available: Union[str, float],
):
"""compute the ground truth (result with a perfect index) of the query on the embeddings"""
dim = query_embeddings.shape[-1]
if isinstance(embedding_reader, EmbeddingReader):
perfect_index = MemEfficientFlatIndex(dim, faiss_metric_type)
perfect_index.add_files(embedding_reader)
else:
perfect_index = faiss.IndexFlat(dim, faiss_metric_type)
perfect_index.add(embedding_reader.astype("float32")) # pylint: disable= no-value-for-parameter
memory_available = cast_memory_to_bytes(memory_available) if isinstance(memory_available, str) else memory_available
batch_size = int(min(memory_available, 10 ** 9) / (dim * 4)) # at most 1GB of memory
if isinstance(embedding_reader, EmbeddingReader):
_, ground_truth = perfect_index.search_files(query_embeddings, k=40, batch_size=batch_size)
else:
_, ground_truth = perfect_index.search(query_embeddings, k=40)
return ground_truth
|
"""
File that contains the descriptions of the different indices features.
"""
from enum import Enum
class IndexBlock(Enum):
FLAT = 0
IVF = 1
IVF_HNSW = 2
HNSW = 3
PQ = 4
OPQ = 5
PAD = 6
class TunableParam(Enum):
EFSEARCH = 0
NPROBE = 1
HT = 2
INDEX_DESCRIPTION_BLOCKS = {
IndexBlock.FLAT: """Flat Index (Simple exhaustive search)
All the vectors are stored without compression in a 2D array.
The search is exhaustive and gives exact results, but it can be slow when there are
many vectors.
This index can't be memory-mapped on disk in current faiss implementation, but and IVF
index with just one cluster makes it possible to memory-map it.""",
IndexBlock.IVF: """IVF (Inverted File Index):
The vector space is divided into several groups that are represented by a cluster vector.
The algorithm first looks for the closest cluster vectors by iterating over them one by one.
Then, The IVF mapping is used to read the vectors in the selected groups. The algorithm reads
each of them and select the k nearest neighbors.
It is possible to memory-map this index on disk, it reduces the RAM footprint to the size of
its cluster vectors, but the index is slower in that case.
-> More info: https://hal.inria.fr/inria-00514462/PDF/jegou_pq_postprint.pdf""",
IndexBlock.IVF_HNSW: """IVF + HNSW (Inverted File Index + Hierarchical Navigable Small World index):
The vector space is divided into several groups that are represented by a cluster vector.
The algorithm first looks for the closest cluster vectors using an HNSW index (instead of
iterating over them one by one in the version without HNSW). Then, The IVF mapping is used
to read the vectors in the selected groups. The algorithm reads each of them and selects
the k nearest neighbors.
It is possible to memory-map this index on disk, it reduces the RAM footprint to the size of the
hnsw index, but the index is slower in that case.
-> More info: https://hal.inria.fr/inria-00514462/PDF/jegou_pq_postprint.pdf""",
IndexBlock.PQ: """PQ (Product Quantization):
The vectors are compressed using product quantization.
Some clever optimizations are implemented to compute distances in the compressed space.
-> More info: https://hal.inria.fr/inria-00514462/PDF/jegou_pq_postprint.pdf""",
IndexBlock.OPQ: """OPQ (Optimized Product Quantization):
The vectors are projected using a rotation matrix. The matrix is trained to minimize
the average compression error.
-> More info: http://kaiminghe.com/publications/pami13opq.pdf""",
IndexBlock.HNSW: """HNSW (Hierarchical Navigable Small World):
All the vectors are stored in a 2D array without compression, and
a bidirectional graph is built on the top of the vectors to enable a fast search.
This index can't be memory-mapped on disk.
-> More info: https://arxiv.org/ftp/arxiv/papers/1603/1603.09320.pdf""",
IndexBlock.PAD: """PAD (Padding):
Preprocessing operations where a padding with 0s is added to the end of the vectors.""",
}
TUNABLE_PARAMETERS_DESCRIPTION_BLOCKS = {
TunableParam.NPROBE: """ - nprobe: The number of vector groups to explore, the search time is proportional
to this value. If nprobe is high, the recall will also be high.
-> More info: https://hal.inria.fr/inria-00514462/PDF/jegou_pq_postprint.pdf""",
TunableParam.EFSEARCH: """ - efsearch: The number of times a greedy search is done in the HNSW graph. The results
of the different greedy searches are combined to get a more precise result.
The search time is proportional to this value. If efsearch is high, the recall will be high.
-> More info: https://arxiv.org/ftp/arxiv/papers/1603/1603.09320.pdf """,
TunableParam.HT: """ - ht (Hamming threshold): A threshold value to approximate the vector distances using the hamming distance.
Computing the Hamming distances between two vectors is much faster than computing the real distance,
but it is also less precise. We found out that it was better to deactivate this parameter as it
decreases the recall score over speed improvements (default value is 2048)
-> More info: https://arxiv.org/pdf/1609.01882.pdf""",
}
|
import torch
from torch import einsum, nn
import torch.nn.functional as F
from einops import rearrange
# rotary positional embedding
# https://arxiv.org/abs/2104.09864
class RotaryEmbedding(nn.Module):
def __init__(self, dim):
super().__init__()
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
self.register_buffer("inv_freq", inv_freq)
def forward(self, max_seq_len, *, device):
seq = torch.arange(max_seq_len, device=device, dtype=self.inv_freq.dtype)
freqs = einsum("i , j -> i j", seq, self.inv_freq)
return torch.cat((freqs, freqs), dim=-1)
def rotate_half(x):
x = rearrange(x, "... (j d) -> ... j d", j=2)
x1, x2 = x.unbind(dim=-2)
return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb(pos, t):
return (t * pos.cos()) + (rotate_half(t) * pos.sin())
# feedforward network
class FFN(nn.Module):
def __init__(
self,
dim,
hidden_dim,
dropout,
act=nn.GELU
):
super().__init__()
self.fc_in = nn.Linear(dim, hidden_dim)
self.fc_out = nn.Linear(hidden_dim, dim)
self.act = act()
self.resid_dropout = nn.Dropout(dropout)
self.ln_2 = nn.LayerNorm(dim)
def forward(self, hidden_states):
hidden_states = self.ln_2(hidden_states)
hidden_states = self.fc_in(hidden_states)
hidden_states = self.act(hidden_states)
hidden_states = self.fc_out(hidden_states)
hidden_states = self.resid_dropout(hidden_states)
return hidden_states
def blockwise_compute_ffn(cell, inputs, chunk_size):
inputs = rearrange(inputs, 'b (n c) d -> b n c d', c=chunk_size)
inputs = rearrange(inputs, 'b n c d -> n b c d')
num_q, _, _, _ = inputs.shape
res = []
for i in range(num_q):
res.append(cell(inputs[i]))
res = torch.stack(res, dim=0)
res = rearrange(res, 'n b c d -> b (n c) d')
return res
# Attention
class Attention(nn.Module):
def __init__(
self,
hidden_size,
num_heads,
intermediate_size,
resid_pdrop = 0.0,
):
super().__init__()
self.embed_dim = hidden_size
self.head_dim = self.embed_dim // num_heads
self.to_q = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
self.to_k = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
self.to_v = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
self.to_out = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
self.layer_norm_1 = nn.LayerNorm(dim)
self.dropout = nn.Dropout(resid_pdrop)
self.register_buffer("pos_emb", None, persistent=False)
def get_rotary_embedding(self, n, device):
if self.pos_emb is not None and self.pos_emb.shape[-2] >= n:
return self.pos_emb[:n]
pos_emb = self.rotary_emb(n, device=device)
self.register_buffer("pos_emb", pos_emb, persistent=False)
return pos_emb
def forward(self, x):
"""
einstein notation
b - batch
h - heads
n, i, j - sequence length (base sequence length, source, target)
d - feature dimension
"""
b, h, n, d, device = *x.shape, x.device
x = self.layer_norm_1(x)
query = self.to_q(x)
key = self.to_k(x)
value = self.to_v(x)
# split heads
query, key, value = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), (query, key, value))
# rotary embeddings
positions = self.get_rotary_embedding(n, device)
query, key = map(lambda t: apply_rotary_pos_emb(positions, t), (query, key))
q_len = query.shape[1]
kv_len = key.shape[1]
def blockwise_cross_entropy(logits, tokens, valid=None, chunk_size=None):
if valid is None:
valid = torch.ones(tokens.shape[:2], device=logits.device)
valid = valid.float()
logits = logits.view(-1, logits.shape[-1])
tokens = tokens.view(-1)
valid = valid.view(-1)
def _cross_entropy_loss_and_accuracy(logits, tokens, valid):
valid_text_length = torch.max(valid.sum(dim=-1), torch.tensor(1e-10).to(logits.device))
token_log_prob = F.log_softmax(logits, dim=-1)
token_log_prob = token_log_prob[torch.arange(len(tokens)), tokens]
token_log_prob = torch.where(valid > 0.0, token_log_prob, torch.tensor(0.0).to(logits.device))
correct = torch.where(
valid > 0.0,
torch.argmax(logits, dim=-1) == tokens,
torch.tensor(False).to(logits.device)
)
return token_log_prob, correct.float(), valid_text_length
num_chunk = logits.shape[0] // chunk_size
logits = rearrange(logits, '(n c) d -> n c d', c=chunk_size)
tokens = rearrange(tokens, '(n c) -> n c', c=chunk_size)
valid = rearrange(valid, '(n c) -> n c', c=chunk_size)
loss, accuracy, num = 0.0, 0.0, 0
for i in range(num_chunk):
token_log_prob, correct, valid_text_length = _cross_entropy_loss_and_accuracy(logits[i], tokens[i], valid[i])
loss += token_log_prob.sum() / valid_text_length
accuracy += correct.sum() / valid_text_length
num = num + 1
loss = - loss / num
accuracy = accuracy / num
return loss, accuracy
class Blockwise_LM_Head(nn.Module):
def __init__(self, vocab_size, chunk_size):
super().__init__()
self.vocab_size = vocab_size
self.chunk_size = chunk_size
self.lm_head = nn.Linear(
chunk_size,
vocab_size,
bias=True
)
def forward(self, inputs):
inputs = rearrange(inputs, 'b (n c) d -> b n c d', c=self.chunk_size)
inputs = rearrange(inputs, 'b n c d -> n b c d')
num_q, _, _, _ = inputs.shape
res = []
for i in range(num_q):
res.append(self.lm_head(inputs[i]))
res = torch.stack(res, dim=0)
res = rearrange(res, 'n b c d -> b (n c) d')
return res
|
import os
import subprocess
import sys
from setuptools import find_packages, setup
# ninja build does not work unless include_dirs are abs path
this_dir = os.path.dirname(os.path.abspath(__file__))
build_cuda_ext = True
ext_modules = []
if '--no_cuda_ext' in sys.argv:
sys.argv.remove('--no_cuda_ext')
build_cuda_ext = False
def get_cuda_bare_metal_version(cuda_dir):
raw_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"], universal_newlines=True)
output = raw_output.split()
release_idx = output.index("release") + 1
release = output[release_idx].split(".")
bare_metal_major = release[0]
bare_metal_minor = release[1][0]
return raw_output, bare_metal_major, bare_metal_minor
def check_cuda_torch_binary_vs_bare_metal(cuda_dir):
raw_output, bare_metal_major, bare_metal_minor = get_cuda_bare_metal_version(cuda_dir)
torch_binary_major = torch.version.cuda.split(".")[0]
torch_binary_minor = torch.version.cuda.split(".")[1]
print("\nCompiling cuda extensions with")
print(raw_output + "from " + cuda_dir + "/bin\n")
if bare_metal_major != torch_binary_major:
print(f'The detected CUDA version ({raw_output}) mismatches the version that was used to compile PyTorch '
f'({torch.version.cuda}). CUDA extension will not be installed.')
return False
if bare_metal_minor != torch_binary_minor:
print("\nWarning: Cuda extensions are being compiled with a version of Cuda that does "
"not match the version used to compile Pytorch binaries. "
f"Pytorch binaries were compiled with Cuda {torch.version.cuda}.\n"
"In some cases, a minor-version mismatch will not cause later errors: "
"https://github.com/NVIDIA/apex/pull/323#discussion_r287021798. ")
return True
def check_cuda_availability(cuda_dir):
if not torch.cuda.is_available():
# https://github.com/NVIDIA/apex/issues/486
# Extension builds after https://github.com/pytorch/pytorch/pull/23408 attempt to query
# torch.cuda.get_device_capability(), which will fail if you are compiling in an environment
# without visible GPUs (e.g. during an nvidia-docker build command).
print(
'\nWarning: Torch did not find available GPUs on this system.\n',
'If your intention is to cross-compile, this is not an error.\n'
'By default, Colossal-AI will cross-compile for Pascal (compute capabilities 6.0, 6.1, 6.2),\n'
'Volta (compute capability 7.0), Turing (compute capability 7.5),\n'
'and, if the CUDA version is >= 11.0, Ampere (compute capability 8.0).\n'
'If you wish to cross-compile for a single specific architecture,\n'
'export TORCH_CUDA_ARCH_LIST="compute capability" before running setup.py.\n')
if os.environ.get("TORCH_CUDA_ARCH_LIST", None) is None:
_, bare_metal_major, _ = get_cuda_bare_metal_version(cuda_dir)
if int(bare_metal_major) == 11:
os.environ["TORCH_CUDA_ARCH_LIST"] = "6.0;6.1;6.2;7.0;7.5;8.0"
else:
os.environ["TORCH_CUDA_ARCH_LIST"] = "6.0;6.1;6.2;7.0;7.5"
return False
if cuda_dir is None:
print("nvcc was not found. CUDA extension will not be installed. If you're installing within a container from "
"https://hub.docker.com/r/pytorch/pytorch, only images whose names contain 'devel' will provide nvcc.")
return False
return True
def append_nvcc_threads(nvcc_extra_args):
_, bare_metal_major, bare_metal_minor = get_cuda_bare_metal_version(CUDA_HOME)
if int(bare_metal_major) >= 11 and int(bare_metal_minor) >= 2:
return nvcc_extra_args + ["--threads", "4"]
return nvcc_extra_args
def fetch_requirements(path):
with open(path, 'r') as fd:
return [r.strip() for r in fd.readlines()]
def fetch_readme():
with open('README.md', encoding='utf-8') as f:
return f.read()
def get_version():
with open('version.txt') as f:
return f.read().strip()
if build_cuda_ext:
try:
import torch
from torch.utils.cpp_extension import (CUDA_HOME, BuildExtension, CUDAExtension)
print("\n\ntorch.__version__ = {}\n\n".format(torch.__version__))
TORCH_MAJOR = int(torch.__version__.split('.')[0])
TORCH_MINOR = int(torch.__version__.split('.')[1])
if TORCH_MAJOR < 1 or (TORCH_MAJOR == 1 and TORCH_MINOR < 8):
raise RuntimeError("Colossal-AI requires Pytorch 1.8 or newer.\n"
"The latest stable release can be obtained from https://pytorch.org/")
except ImportError:
print('torch is not found. CUDA extension will not be installed')
build_cuda_ext = False
if build_cuda_ext:
build_cuda_ext = check_cuda_availability(CUDA_HOME) and check_cuda_torch_binary_vs_bare_metal(CUDA_HOME)
if build_cuda_ext:
# Set up macros for forward/backward compatibility hack around
# https://github.com/pytorch/pytorch/commit/4404762d7dd955383acee92e6f06b48144a0742e
# and
# https://github.com/NVIDIA/apex/issues/456
# https://github.com/pytorch/pytorch/commit/eb7b39e02f7d75c26d8a795ea8c7fd911334da7e#diff-4632522f237f1e4e728cb824300403ac
version_dependent_macros = ['-DVERSION_GE_1_1', '-DVERSION_GE_1_3', '-DVERSION_GE_1_5']
def cuda_ext_helper(name, sources, extra_cuda_flags, extra_cxx_flags=[]):
return CUDAExtension(
name=name,
sources=[os.path.join('colossalai/kernel/cuda_native/csrc', path) for path in sources],
include_dirs=[os.path.join(this_dir, 'colossalai/kernel/cuda_native/csrc/kernels/include')],
extra_compile_args={
'cxx': ['-O3'] + version_dependent_macros + extra_cxx_flags,
'nvcc': append_nvcc_threads(['-O3', '--use_fast_math'] + version_dependent_macros + extra_cuda_flags)
})
ext_modules.append(
cuda_ext_helper('colossal_C', [
'colossal_C_frontend.cpp', 'multi_tensor_sgd_kernel.cu', 'multi_tensor_scale_kernel.cu',
'multi_tensor_adam.cu', 'multi_tensor_l2norm_kernel.cu', 'multi_tensor_lamb.cu'
], ['-lineinfo']))
cc_flag = ['-gencode', 'arch=compute_70,code=sm_70']
_, bare_metal_major, _ = get_cuda_bare_metal_version(CUDA_HOME)
if int(bare_metal_major) >= 11:
cc_flag.append('-gencode')
cc_flag.append('arch=compute_80,code=sm_80')
extra_cuda_flags = [
'-U__CUDA_NO_HALF_OPERATORS__', '-U__CUDA_NO_HALF_CONVERSIONS__', '--expt-relaxed-constexpr',
'--expt-extended-lambda'
]
ext_modules.append(
cuda_ext_helper('colossal_scaled_upper_triang_masked_softmax',
['scaled_upper_triang_masked_softmax.cpp', 'scaled_upper_triang_masked_softmax_cuda.cu'],
extra_cuda_flags + cc_flag))
ext_modules.append(
cuda_ext_helper('colossal_scaled_masked_softmax',
['scaled_masked_softmax.cpp', 'scaled_masked_softmax_cuda.cu'], extra_cuda_flags + cc_flag))
ext_modules.append(
cuda_ext_helper('colossal_moe_cuda', ['moe_cuda.cpp', 'moe_cuda_kernel.cu'], extra_cuda_flags + cc_flag))
extra_cuda_flags = ['-maxrregcount=50']
ext_modules.append(
cuda_ext_helper('colossal_layer_norm_cuda', ['layer_norm_cuda.cpp', 'layer_norm_cuda_kernel.cu'],
extra_cuda_flags + cc_flag))
extra_cuda_flags = [
'-std=c++14', '-U__CUDA_NO_HALF_OPERATORS__', '-U__CUDA_NO_HALF_CONVERSIONS__', '-U__CUDA_NO_HALF2_OPERATORS__',
'-DTHRUST_IGNORE_CUB_VERSION_CHECK'
]
ext_modules.append(
cuda_ext_helper('colossal_multihead_attention', [
'multihead_attention_1d.cpp', 'kernels/cublas_wrappers.cu', 'kernels/transform_kernels.cu',
'kernels/dropout_kernels.cu', 'kernels/normalize_kernels.cu', 'kernels/softmax_kernels.cu',
'kernels/general_kernels.cu', 'kernels/cuda_util.cu'
], extra_cuda_flags + cc_flag))
extra_cxx_flags = ['-std=c++14', '-lcudart', '-lcublas', '-g', '-Wno-reorder', '-fopenmp', '-march=native']
ext_modules.append(cuda_ext_helper('cpu_adam', ['cpu_adam.cpp'], extra_cuda_flags, extra_cxx_flags))
setup(
name='colossalai',
version=get_version(),
packages=find_packages(exclude=(
'benchmark',
'docker',
'tests',
'docs',
'examples',
'tests',
'scripts',
'requirements',
'*.egg-info',
)),
description='An integrated large-scale model training system with efficient parallelization techniques',
long_description=fetch_readme(),
long_description_content_type='text/markdown',
license='Apache Software License 2.0',
url='https://www.colossalai.org',
project_urls={
'Forum': 'https://github.com/hpcaitech/ColossalAI/discussions',
'Bug Tracker': 'https://github.com/hpcaitech/ColossalAI/issues',
'Examples': 'https://github.com/hpcaitech/ColossalAI-Examples',
'Documentation': 'http://colossalai.readthedocs.io',
'Github': 'https://github.com/hpcaitech/ColossalAI',
},
ext_modules=ext_modules,
cmdclass={'build_ext': BuildExtension} if ext_modules else {},
install_requires=fetch_requirements('requirements/requirements.txt'),
python_requires='>=3.7',
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License',
'Environment :: GPU :: NVIDIA CUDA',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: System :: Distributed Computing',
],
)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from functools import partial
from pathlib import Path
import pytest
import torch
import torch.multiprocessing as mp
from colossalai import launch
from colossalai.context.parallel_mode import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.utils import free_port
from colossalai.context import reset_seeds
from colossalai.global_variables import tensor_parallel_env as tp_env
from colossalai.testing import rerun_if_address_is_in_use
CONFIG_PATH_LIST = list(Path(__file__).parent.glob('configs/*.py'))
def check_data_parallel_rank(rank):
global_world_size = gpc.get_world_size(ParallelMode.GLOBAL)
mp_size = gpc.get_world_size(ParallelMode.MODEL)
num_dp_groups = global_world_size // mp_size
dp_local_rank = gpc.get_local_rank(ParallelMode.DATA)
assert gpc.get_world_size(ParallelMode.DATA) == num_dp_groups
for group_idx in range(num_dp_groups):
ranks_in_dp_group = range(group_idx * mp_size, (group_idx + 1) * mp_size)
if rank in ranks_in_dp_group:
assert dp_local_rank == group_idx
def check_pipeline_parallel_rank(rank):
mp_world_size = gpc.get_world_size(ParallelMode.MODEL)
tp_world_size = gpc.get_world_size(ParallelMode.TENSOR)
num_pipeline_stage = mp_world_size // tp_world_size
pipeline_local_rank = gpc.get_local_rank(ParallelMode.PIPELINE)
for stage_idx in range(num_pipeline_stage):
ranks_in_current_stage = range(stage_idx * tp_world_size, (stage_idx + 1) * tp_world_size)
if rank in ranks_in_current_stage:
assert stage_idx == pipeline_local_rank
def check_model_parallel_rank(rank):
mp_size = gpc.get_world_size(ParallelMode.MODEL)
rank_within_mp_group = rank % mp_size
mp_local_rank = gpc.get_local_rank(ParallelMode.MODEL)
assert rank_within_mp_group == mp_local_rank
def check_tensor_parallel_rank(rank):
if tp_env.mode == '2d':
check_2d_tensor_parallel_rank(rank)
elif tp_env == '2.5d':
check_2p5d_tensor_parallel_rank(rank)
elif tp_env == '3d':
check_3d_tensor_parallel_rank(rank)
def get_tp_info():
global_world_size = gpc.get_world_size(ParallelMode.GLOBAL)
tp_world_size = gpc.get_world_size(ParallelMode.TENSOR)
num_tp_groups = global_world_size // tp_world_size
tp_local_rank = gpc.get_local_rank(ParallelMode.TENSOR)
return tp_local_rank, tp_world_size, num_tp_groups
def check_2d_tensor_parallel_rank(rank):
tp_local_rank, tp_world_size, num_tp_groups = get_tp_info()
for group_id in range(num_tp_groups):
ranks_in_current_tp_group = range(group_id * tp_world_size, (group_id + 1) * tp_world_size)
if rank in ranks_in_current_tp_group:
col_local_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
row_local_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
assert col_local_rank == tp_local_rank // tp_env.summa_dim
assert row_local_rank == tp_local_rank % tp_env.summa_dim
def check_2p5d_tensor_parallel_rank(rank):
tp_local_rank, tp_world_size, num_tp_groups = get_tp_info()
for group_id in range(num_tp_groups):
ranks_in_current_tp_group = range(group_id * tp_world_size, (group_id + 1) * tp_world_size)
if rank in ranks_in_current_tp_group:
rp_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
cp_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
dp_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
xp_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_XZ)
assert rp_rank == tp_local_rank % tp_env.summa_dim
assert cp_rank == tp_local_rank // tp_env.tesseract_dim
assert dp_rank == tp_local_rank // (tp_env.summa_dim**2)
assert xp_rank == tp_local_rank // tp_env.summa_dim
def check_3d_tensor_parallel_rank(rank):
tp_local_rank, tp_world_size, num_tp_groups = get_tp_info()
for group_id in range(num_tp_groups):
ranks_in_current_tp_group = range(group_id * tp_world_size, (group_id + 1) * tp_world_size)
if rank in ranks_in_current_tp_group:
ip_rank = gpc.get_local_rank(ParallelMode.PARALLEL_3D_INPUT)
wp_rank = gpc.get_local_rank(ParallelMode.PARALLEL_3D_WEIGHT)
op_rank = gpc.get_local_rank(ParallelMode.PARALLEL_3D_OUTPUT)
assert ip_rank == tp_local_rank % tp_env.depth_3d
assert wp_rank == tp_local_rank // tp_env.depth_3d
assert op_rank == tp_local_rank // (tp_env.depth_3d**2)
def init_context(config_path, rank, world_size, backend, port, host):
dist_args = dict(config=config_path,
rank=rank,
world_size=world_size,
backend=backend,
port=port,
host=host,
verbose=True)
launch(**dist_args)
check_tensor_parallel_rank(rank)
check_data_parallel_rank(rank)
check_pipeline_parallel_rank(rank)
check_model_parallel_rank(rank)
gpc.destroy()
torch.cuda.empty_cache()
def run_dist(rank, world_size, backend, port_list, host):
for config_path, port in zip(CONFIG_PATH_LIST, port_list):
init_context(config_path=config_path, rank=rank, world_size=world_size, backend=backend, port=port, host=host)
reset_seeds()
@pytest.mark.cpu
@rerun_if_address_is_in_use()
def test_context():
"""
As no computation or communication is done, we can run this test on CPU.
"""
world_size = 32
port_list = []
for _ in range(len(CONFIG_PATH_LIST)):
while True:
port = free_port()
if port not in port_list:
port_list.append(port)
break
test_fn = partial(run_dist, world_size=world_size, backend='gloo', port_list=port_list, host='localhost')
mp.spawn(test_fn, nprocs=world_size)
if __name__ == '__main__':
test_context()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
parallel = dict(
pipeline=dict(size=2),
tensor=dict(
size=4,
mode='2d'
)
)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
parallel = dict(
pipeline=dict(size=2),
tensor=dict(
size=8,
mode='3d'
)
)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
parallel = dict(
pipeline=dict(size=2),
tensor=dict(
size=8,
depth=2,
mode='2.5d'
)
)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from functools import partial
import colossalai
import pytest
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from colossalai.context.parallel_mode import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.testing import rerun_if_address_is_in_use
from colossalai.utils import free_port
from colossalai.zero.init_ctx import ZeroInitContext
from colossalai.zero.shard_utils import TensorShardStrategy
from torchvision.models import resnet50
def run_dist(rank, world_size, port):
# this test only runs on resnet18
# as this model has sync batch normalization
# need to configure cudnn deterministic so that
# randomness of convolution layers will be disabled
zero_config = dict(model_config=dict(shard_strategy=TensorShardStrategy()))
colossalai.launch(config=dict(zero=zero_config, cudnn_determinstic=True, cudnn_benchmark=False),
rank=rank,
world_size=world_size,
host='localhost',
port=port,
backend='nccl')
with ZeroInitContext(target_device=torch.cuda.current_device(),
shard_strategy=gpc.config.zero.model_config.shard_strategy,
shard_param=True):
model = resnet50()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = torch.nn.CrossEntropyLoss()
engine, *args = colossalai.initialize(model, optimizer, criterion)
# train for dummy iterations
engine.train()
for _ in range(2):
data = torch.rand(4, 3, 128, 128).cuda().half()
label = torch.randint(0, 10, size=(4,)).cuda()
engine.zero_grad()
out = engine(data)
loss = engine.criterion(out, label)
engine.backward(loss)
engine.step()
# test
# need to make sure the batch norm stats are synchronized
# so that given the same input, the model will produce the same
# output on different ranks
engine.eval()
data = torch.rand(4, 3, 128, 128).cuda().half()
dist.broadcast(data, src=0, group=gpc.get_group(ParallelMode.DATA))
# predict
out = engine(data)
# test if results are equal
tensor_list = [torch.empty_like(out) for _ in range(world_size - 1)]
tensor_list.insert(rank, out)
dist.all_gather(tensor_list=tensor_list, tensor=out, group=gpc.get_group(ParallelMode.DATA))
assert torch.all(tensor_list[0] == tensor_list[1]), \
'expected the output from different ranks to be the same, but got different values'
@pytest.mark.dist
@rerun_if_address_is_in_use()
def test_sharded_optim_with_sync_bn():
"""
This test is to make sure that buffers are synchronized between ranks
when using ZeRO. An example of module buffer is the running stats of
BatchNormalization layer, i.e. mean and var.
If the buffers are not synchronized, the model will produce different
output even though the input and parameters are the same. This is not
wanted if we are doing predictions.
"""
world_size = 2
run_func = partial(run_dist, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_sharded_optim_with_sync_bn()
|
from functools import partial
import colossalai
from colossalai.utils.cuda import get_current_device
import pytest
import torch
import torch.multiprocessing as mp
from colossalai.nn.optimizer import HybridAdam
from colossalai.testing import parameterize, rerun_if_address_is_in_use
from colossalai.utils import free_port
from colossalai.zero.init_ctx import ZeroInitContext
from colossalai.zero.shard_utils import BucketTensorShardStrategy
from colossalai.zero.sharded_model import ShardedModelV2
from colossalai.zero.sharded_optim import ShardedOptimizerV2
from colossalai.zero.sharded_optim._utils import has_inf_or_nan
from tests.components_to_test.registry import non_distributed_component_funcs
from tests.test_zero.test_sharded_optim_v2 import _run_step
from common import CONFIG
@parameterize("cpu_offload", [True, False])
@parameterize("shard_strategy_class", [BucketTensorShardStrategy])
@parameterize("gpu_margin_mem_ratio", [0.0, 0.7])
def _run_test_found_inf(cpu_offload, shard_strategy_class, gpu_margin_mem_ratio):
test_models = ['repeated_computed_layers']
shard_strategy = shard_strategy_class()
for model_name in test_models:
get_components_func = non_distributed_component_funcs.get_callable(model_name)
model_builder, train_dataloader, _, optimizer_class, criterion = get_components_func()
with ZeroInitContext(target_device=torch.device(f'cpu:0') if cpu_offload else get_current_device(),
shard_strategy=shard_strategy,
shard_param=True):
zero_model = model_builder(checkpoint=True)
zero_model = ShardedModelV2(
zero_model,
shard_strategy,
tensor_placement_policy='cpu' if cpu_offload else 'cuda',
reuse_fp16_shard=True,
)
sharded_optim = HybridAdam(zero_model.parameters(), lr=1e-3)
sharded_optim = ShardedOptimizerV2(zero_model, sharded_optim, gpu_margin_mem_ratio=gpu_margin_mem_ratio)
for i, (data, label) in enumerate(train_dataloader):
if i > 1:
break
assert zero_model.overflow_counter == 0
data, label = data.cuda(), label.cuda()
_run_step(zero_model, sharded_optim, data, label, criterion, False)
for param in zero_model.parameters():
assert not has_inf_or_nan(param.colo_attr.data_payload)
def _run_dist(rank, world_size, port):
colossalai.launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
_run_test_found_inf()
# use_cpuadam = True can be used with cpu_offload = False
@pytest.mark.dist
@pytest.mark.parametrize("world_size", [1, 2])
@rerun_if_address_is_in_use()
def test_found_inf(world_size):
run_func = partial(_run_dist, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_found_inf(world_size=2)
|
import pytest
import colossalai
from colossalai.utils.cuda import get_current_device
from colossalai.zero.sharded_param import (StatefulTensor, colo_tensor_mem_usage, colo_model_data_tensor_move,
colo_model_data_tensor_move_inline, colo_model_data_move_to_cpu,
colo_model_tensor_clone)
from colossalai.utils import free_port
from colossalai.testing import rerun_if_address_is_in_use
import torch
from functools import partial
import torch.multiprocessing as mp
def _run_colo_tensor_mem_usage():
for i in range(1):
if i == 1:
t1 = StatefulTensor(torch.randn(2, 2))
t2 = StatefulTensor(torch.randn(4, 4))
c1, g1 = colo_tensor_mem_usage(t1)
c2, g2 = colo_tensor_mem_usage(t2)
assert c1 * 4 == c2
assert g1 * 4 == g2
else:
t1 = torch.randn(2, 2)
t2 = torch.randn(4, 4)
c1, g1 = colo_tensor_mem_usage(t1)
c2, g2 = colo_tensor_mem_usage(t2)
assert c1 * 4 == c2
assert g1 * 4 == g2
def _run_colo_model_data_tensor_move_inline():
for t in [StatefulTensor(torch.randn(2, 3)), torch.randn(2, 3)]:
colo_model_data_tensor_move_inline(t, get_current_device())
assert t.device == get_current_device()
def _run_colo_model_data_tensor_move():
for t in [(StatefulTensor(torch.ones(2, 3)), StatefulTensor(torch.zeros(2, 3).to(get_current_device()))),
(torch.ones(2, 3), torch.zeros(2, 3).to(get_current_device()))]:
cpu_t, cuda_t = t
colo_model_data_tensor_move(cpu_t, cuda_t)
assert cuda_t.device == get_current_device()
def _run_colo_model_data_move_to_cpu():
for t in [StatefulTensor(torch.randn(2, 2)), torch.randn(4, 4)]:
colo_model_data_move_to_cpu(t)
assert t.device == torch.device("cpu")
def _run_colo_model_tensor_clone():
for t in [
StatefulTensor(torch.randn(2, 2).cuda(torch.cuda.current_device())),
torch.randn(4, 4).cuda(torch.cuda.current_device())
]:
if issubclass(type(t), StatefulTensor):
assert t.payload.device == get_current_device()
else:
assert t.device == get_current_device()
p = colo_model_tensor_clone(t, get_current_device())
assert p.device == get_current_device()
for i in range(2):
for j in range(2):
if issubclass(type(t), StatefulTensor):
assert t.payload.device == p.device
assert t.payload[i][j] == p[i][j]
else:
assert t.device == p.device
assert t[i][j] == p[i][j]
def run_dist(rank, world_size, port):
colossalai.launch(config={}, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
_run_colo_tensor_mem_usage()
_run_colo_model_data_tensor_move_inline()
_run_colo_model_data_tensor_move()
_run_colo_model_data_move_to_cpu()
_run_colo_model_tensor_clone()
@pytest.mark.dist
@pytest.mark.parametrize("world_size", [4, 5])
@rerun_if_address_is_in_use()
def test_zero_tensor_utils(world_size):
run_func = partial(run_dist, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_zero_tensor_utils(world_size=2)
|
from copy import deepcopy
from functools import partial
import colossalai
import pytest
import torch
import torch.multiprocessing as mp
from colossalai.testing import parameterize, rerun_if_address_is_in_use
from colossalai.utils import free_port
from colossalai.zero.shard_utils import (BucketTensorShardStrategy, TensorShardStrategy)
from colossalai.zero.sharded_param import ShardedTensor
from colossalai.zero.sharded_param.sharded_param import ShardedParamV2
from tests.test_zero.common import CONFIG, allclose
from colossalai.zero.sharded_param.tensorful_state import StatefulTensor
@parameterize("shard_strategy_class", [TensorShardStrategy, BucketTensorShardStrategy])
def run_shard_tensor_with_strategy(shard_strategy_class, world_size):
t = ShardedTensor(tensor=torch.randn(world_size * 2, 3))
assert list(t.origin_shape) == [world_size * 2, 3]
assert list(t.shape) == [world_size * 2, 3]
shard_strategy = shard_strategy_class()
# test shard strategy
shard_strategy.shard([t])
assert list(t.shape) == [6], f"{list(t.shape)} vs 6"
shard_strategy.gather([t])
assert list(t.shape) == [world_size * 2, 3], f"{list(t.shape)} vs {[world_size * 2, 3]}"
def _run_shard_tensor(rank, world_size, port):
colossalai.launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
run_shard_tensor_with_strategy(world_size=world_size)
@pytest.mark.dist
@pytest.mark.parametrize("world_size", [1, 2])
@rerun_if_address_is_in_use()
def test_shard_tensor(world_size):
run_func = partial(_run_shard_tensor, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
def _run_shard_param_v2(rank, world_size, port):
colossalai.launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
param = torch.nn.Parameter(torch.randn(2, 3))
param_ref = deepcopy(param)
sparam = ShardedParamV2(param=param)
allclose(sparam.data_payload, param_ref.data)
# Test get memory usage
sparam.saved_grad = StatefulTensor(torch.randn(2, 3))
cuda_mem_use, cpu_mem_use = sparam.get_memory_usage()
assert cpu_mem_use == 2 * 3 * 4 * 2, f"cpu_mem_use: {cpu_mem_use}"
sparam.set_data_none()
assert (param.data.numel() == 0)
cuda_mem_use, cpu_mem_use = sparam.get_memory_usage()
# 4 is size of dummy tensor of param.data
assert cpu_mem_use == 2 * 3 * 4 * 2
sparam.saved_grad = StatefulTensor(torch.randn(2, 3))
sparam.set_data_none()
cuda_mem_use, cpu_mem_use = sparam.get_memory_usage()
assert cpu_mem_use == 2 * 3 * 4 * 2
assert cuda_mem_use == 0
# append a grad to torch param
param.data = sparam.data_payload
param.grad = torch.randn(2, 3)
cuda_mem_use, cpu_mem_use = sparam.get_memory_usage()
assert cpu_mem_use == 2 * 3 * 4 * 2 + 2 * 3 * 4, f"cpu_mem_use {cpu_mem_use}"
assert cuda_mem_use == 0
# reuse torch grad for sparam
sparam.saved_grad = StatefulTensor(param.grad)
cuda_mem_use, cpu_mem_use = sparam.get_memory_usage()
assert cpu_mem_use == 2 * 3 * 4 * 2
assert cuda_mem_use == 0
@pytest.mark.dist
@pytest.mark.parametrize("world_size", [1, 2])
@rerun_if_address_is_in_use()
def test_shard_param_v2(world_size):
run_func = partial(_run_shard_param_v2, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
# test_shard_tensor(2)
test_shard_param_v2(2)
|
from functools import partial
import colossalai
from colossalai.utils.cuda import get_current_device
import pytest
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from colossalai.amp import convert_to_apex_amp
from colossalai.nn.optimizer import CPUAdam
from colossalai.testing import parameterize, rerun_if_address_is_in_use
from colossalai.utils import free_port
from colossalai.zero.init_ctx import ZeroInitContext
from colossalai.zero.shard_utils import (BucketTensorShardStrategy, TensorShardStrategy)
from colossalai.zero.sharded_model import ShardedModelV2
from colossalai.zero.sharded_model.utils import col_model_deepcopy
from colossalai.zero.sharded_optim import ShardedOptimizerV2
from colossalai.zero.sharded_optim._utils import has_inf_or_nan
from tests.components_to_test.registry import non_distributed_component_funcs
from torch.nn.parallel import DistributedDataParallel as DDP
from common import CONFIG, check_sharded_model_params
def _run_step(model, optimizer, data, label, criterion, enable_autocast=False):
model.train()
optimizer.zero_grad()
with torch.cuda.amp.autocast(enabled=enable_autocast):
if criterion:
y = model(data)
loss = criterion(y, label)
else:
loss = model(data, label)
loss = loss.float()
if isinstance(model, ShardedModelV2):
optimizer.backward(loss)
else:
loss.backward()
optimizer.step()
@parameterize("cpu_offload", [True, False])
@parameterize("use_cpuadam", [True, False])
@parameterize("shard_strategy_class", [TensorShardStrategy, BucketTensorShardStrategy])
@parameterize("gpu_margin_mem_ratio", [0.0, 0.7])
def _run_test_sharded_optim_v2(cpu_offload, shard_strategy_class, use_cpuadam, gpu_margin_mem_ratio):
test_models = ['repeated_computed_layers', 'resnet18', 'bert', 'no_leaf_module']
shard_strategy = shard_strategy_class()
if use_cpuadam and cpu_offload is False:
return
if gpu_margin_mem_ratio > 0.0 and not (cpu_offload and use_cpuadam):
return
for model_name in test_models:
get_components_func = non_distributed_component_funcs.get_callable(model_name)
model_builder, train_dataloader, _, optimizer_class, criterion = get_components_func()
with ZeroInitContext(target_device=torch.device(f'cpu:0') if cpu_offload else get_current_device(),
shard_strategy=shard_strategy,
shard_param=True):
zero_model = model_builder(checkpoint=True)
zero_model = ShardedModelV2(
zero_model,
shard_strategy,
tensor_placement_policy='cpu' if cpu_offload else 'cuda',
reuse_fp16_shard=use_cpuadam,
)
model = model_builder(checkpoint=True).half()
col_model_deepcopy(zero_model, model)
model = model.cuda().float()
if use_cpuadam:
optimizer_class = CPUAdam
optim = optimizer_class(model.parameters(), lr=1e-3)
sharded_optim = optimizer_class(zero_model.parameters(), lr=1e-3)
sharded_optim = ShardedOptimizerV2(zero_model,
sharded_optim,
initial_scale=2**5,
gpu_margin_mem_ratio=gpu_margin_mem_ratio)
amp_config = dict(opt_level='O2', keep_batchnorm_fp32=False)
apex_model, apex_optimizer = convert_to_apex_amp(model, optim, amp_config)
if dist.get_world_size() > 1:
apex_model = DDP(apex_model, device_ids=[torch.cuda.current_device()])
for i, (data, label) in enumerate(train_dataloader):
if i > 5:
break
data, label = data.cuda(), label.cuda()
_run_step(apex_model, apex_optimizer, data, label, criterion, False)
_run_step(zero_model, sharded_optim, data, label, criterion, False)
check_sharded_model_params(model, zero_model, loose=True, reuse_fp16_shard=use_cpuadam)
for param in model.parameters():
assert not has_inf_or_nan(param)
def _run_dist(rank, world_size, port):
colossalai.launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
_run_test_sharded_optim_v2()
# use_cpuadam = True can be used with cpu_offload = False
@pytest.mark.dist
@pytest.mark.parametrize("world_size", [1, 2])
@rerun_if_address_is_in_use()
def test_sharded_optim_v2(world_size):
run_func = partial(_run_dist, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_sharded_optim_v2(world_size=2)
|
import torch
import colossalai
import pytest
import torch.multiprocessing as mp
from colossalai.utils.cuda import get_current_device
from colossalai.utils.memory_tracer import MemStatsCollector
from colossalai.utils.memory_tracer.model_data_memtracer import GLOBAL_MODEL_DATA_TRACER
from colossalai.utils.memory import colo_set_process_memory_fraction
from colossalai.gemini import StatefulTensorMgr
from colossalai.zero.sharded_param.sharded_param import ShardedParamV2
from colossalai.zero.sharded_param.tensorful_state import TensorState
from colossalai.utils import free_port
from colossalai.testing import rerun_if_address_is_in_use
from torch.nn.parameter import Parameter
from typing import List
from functools import partial
from colossalai.gemini import StatefulTensorMgr
from colossalai.gemini.tensor_placement_policy import AutoTensorPlacementPolicy
class Net(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
# each parameter is 128 MB
self.p0 = Parameter(torch.empty(1024, 1024, 32))
self.p1 = Parameter(torch.empty(1024, 1024, 32))
self.p2 = Parameter(torch.empty(1024, 1024, 32))
def limit_cuda_memory(memory_in_g: float):
cuda_capacity = torch.cuda.get_device_properties(get_current_device()).total_memory
fraction = (memory_in_g * 1024**3) / cuda_capacity
colo_set_process_memory_fraction(fraction)
def run_stm():
# warmup phase use 20% CUDA memory to store params
# only 2 params can be on CUDA
limit_cuda_memory(1.26)
model = Net()
for p in model.parameters():
p.colo_attr = ShardedParamV2(p, set_data_none=True)
GLOBAL_MODEL_DATA_TRACER.register_model(model)
mem_collector = MemStatsCollector()
tensor_placement_policy = AutoTensorPlacementPolicy(mem_stats_collector=mem_collector)
stateful_tensor_mgr = StatefulTensorMgr(tensor_placement_policy)
for p in model.parameters():
stateful_tensor_mgr.register_stateful_param(p.colo_attr)
mem_collector.start_collection()
# Compute order: 0 1 2 0 1
# warmup
# use naive eviction strategy
apply_adjust(model, model.p0, [model.p0], stateful_tensor_mgr)
mem_collector.sample_model_data()
mem_collector.sample_overall_data()
apply_adjust(model, model.p1, [model.p0, model.p1], stateful_tensor_mgr)
mem_collector.sample_model_data()
mem_collector.sample_overall_data()
apply_adjust(model, model.p2, [model.p1, model.p2], stateful_tensor_mgr)
mem_collector.sample_model_data()
mem_collector.sample_overall_data()
apply_adjust(model, model.p0, [model.p0, model.p2], stateful_tensor_mgr)
mem_collector.sample_model_data()
mem_collector.sample_overall_data()
apply_adjust(model, model.p1, [model.p1, model.p2], stateful_tensor_mgr)
mem_collector.sample_model_data()
mem_collector.finish_collection()
stateful_tensor_mgr.reset()
# warmup done
# only 2 params can be on CUDA
limit_cuda_memory(0.26 / tensor_placement_policy._steady_cuda_cap_ratio)
# use OPT-like eviction strategy
apply_adjust(model, model.p0, [model.p0, model.p1], stateful_tensor_mgr)
apply_adjust(model, model.p1, [model.p0, model.p1], stateful_tensor_mgr)
apply_adjust(model, model.p2, [model.p0, model.p2], stateful_tensor_mgr)
apply_adjust(model, model.p0, [model.p0, model.p2], stateful_tensor_mgr)
apply_adjust(model, model.p1, [model.p1, model.p2], stateful_tensor_mgr)
def apply_adjust(model: torch.nn.Module, compute_param: Parameter, cuda_param_after_adjust: List[Parameter],
stateful_tensor_mgr: StatefulTensorMgr):
compute_param.colo_attr._sharded_data_tensor.trans_state(TensorState.COMPUTE)
for p in model.parameters():
if p is not compute_param and p.colo_attr._sharded_data_tensor.state != TensorState.HOLD:
p.colo_attr._sharded_data_tensor.trans_state(TensorState.HOLD)
stateful_tensor_mgr.adjust_layout()
print_stats(model)
device = torch.device(torch.cuda.current_device())
cuda_param_after_adjust = [hash(p) for p in cuda_param_after_adjust]
for n, p in model.named_parameters():
if hash(p) in cuda_param_after_adjust:
assert p.colo_attr._sharded_data_tensor.device == device, f'{n} {p.colo_attr._sharded_data_tensor.device} vs {device}'
else:
assert p.colo_attr._sharded_data_tensor.device == torch.device('cpu')
def print_stats(model: torch.nn.Module):
msgs = []
for n, p in model.named_parameters():
msgs.append(f'{n}: {p.colo_attr._sharded_data_tensor.state}({p.colo_attr._sharded_data_tensor.device})')
print(f'[ {", ".join(msgs)} ]')
def run_dist(rank, world_size, port):
colossalai.launch(config={}, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
run_stm()
@pytest.mark.dist
@rerun_if_address_is_in_use()
def test_stateful_tensor_manager(world_size=1):
run_func = partial(run_dist, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
# this unit test can pass if available CUDA memory >= 1.5G
test_stateful_tensor_manager()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from functools import partial
import colossalai
import pytest
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from colossalai.core import global_context as gpc
from colossalai.testing import rerun_if_address_is_in_use
from colossalai.utils import free_port
from colossalai.zero.init_ctx import ZeroInitContext
from colossalai.zero.sharded_model.utils import col_model_deepcopy
from colossalai.zero.sharded_optim._utils import has_inf_or_nan
from tests.components_to_test.registry import non_distributed_component_funcs
from torch.nn.parallel import DistributedDataParallel as DDP
from common import (MP_PARALLEL_CONFIG, ZERO_PARALLEL_CONFIG, check_params, check_sharded_model_params)
def run_dist(rank, world_size, port, parallel_config):
colossalai.launch(config=parallel_config,
rank=rank,
world_size=world_size,
host='localhost',
port=port,
backend='nccl')
test_models = ['repeated_computed_layers', 'resnet18', 'bert']
for model_name in test_models:
get_components_func = non_distributed_component_funcs.get_callable(model_name)
model_builder, train_dataloader, _, optimizer_class, criterion = get_components_func()
with ZeroInitContext(target_device=torch.cuda.current_device(),
shard_strategy=gpc.config.zero.model_config.shard_strategy,
shard_param=True):
colo_model = model_builder(checkpoint=True)
colo_optimizer = optimizer_class(colo_model.parameters(), lr=1e-3)
engine, train_dataloader, _, _ = colossalai.initialize(colo_model,
optimizer=colo_optimizer,
criterion=criterion,
train_dataloader=train_dataloader)
torch_model = model_builder(checkpoint=True).half()
col_model_deepcopy(engine.model, torch_model)
torch_model = torch_model.cuda().float()
engine.train()
torch_optimizer = optimizer_class(torch_model.parameters(), lr=1e-3)
if dist.get_world_size() > 1:
torch_model = DDP(torch_model, device_ids=[torch.cuda.current_device()])
i = 0
for data, label in train_dataloader:
if i > 4:
break
data, label = data.cuda(), label.cuda()
engine.zero_grad()
torch_optimizer.zero_grad()
if criterion:
output = engine(data)
loss = engine.criterion(output, label)
torch_output = torch_model(data)
torch_loss = engine.criterion(torch_output, label)
else:
loss = engine(data, label)
torch_loss = torch_model(data, label)
engine.backward(loss)
engine.step()
torch_loss.backward()
for param in torch_model.parameters():
if param.grad is not None:
assert not has_inf_or_nan(param.grad)
torch_optimizer.step()
i += 1
if parallel_config == MP_PARALLEL_CONFIG:
check_params(torch_model, colo_model, loose=True)
elif parallel_config == ZERO_PARALLEL_CONFIG:
check_sharded_model_params(torch_model, colo_model, loose=True)
# FIXME: enable this test in next PR
@pytest.mark.skip
@pytest.mark.dist
@pytest.mark.parametrize("world_size", [2, 4])
@rerun_if_address_is_in_use()
def test_mp_engine(world_size):
run_func = partial(run_dist, world_size=world_size, port=free_port(), parallel_config=MP_PARALLEL_CONFIG)
mp.spawn(run_func, nprocs=world_size)
@pytest.mark.dist
@pytest.mark.parametrize("world_size", [1, 2])
@rerun_if_address_is_in_use()
def test_zero_engine(world_size):
run_func = partial(run_dist, world_size=world_size, port=free_port(), parallel_config=ZERO_PARALLEL_CONFIG)
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_zero_engine(world_size=4)
|
from functools import partial
import torch
import torch.distributed as dist
from colossalai.logging import get_dist_logger
from colossalai.utils import checkpoint
from colossalai.zero.shard_utils import TensorShardStrategy
from colossalai.zero.sharded_model import ShardedModelV2
LOGGER = get_dist_logger('zero_test')
MP_PARALLEL_CONFIG = dict(fp16=dict(mode=None,), parallel=dict(pipeline=dict(size=1), tensor=dict(size=2, mode=None)))
_ZERO_MODEL_CONFIG = dict(reduce_scatter_bucket_size_mb=25,
fp32_reduce_scatter=False,
tensor_placement_policy='cuda',
gradient_predivide_factor=1.0,
shard_strategy=TensorShardStrategy(),
reuse_fp16_shard=False)
_ZERO_OPTIMIZER_CONFIG = dict(initial_scale=2**5,
min_scale=1,
growth_factor=2,
backoff_factor=0.5,
growth_interval=1000,
hysteresis=2,
max_scale=2**32)
ZERO_PARALLEL_CONFIG = dict(fp16=dict(mode=None,),
zero=dict(
model_config=_ZERO_MODEL_CONFIG,
optimizer_config=_ZERO_OPTIMIZER_CONFIG,
),
parallel=dict(pipeline=dict(size=1), tensor=dict(size=1, mode=None)))
CONFIG = dict(fp16=dict(mode=None,),
zero=dict(level=3,
verbose=False,
offload_optimizer_config=dict(device='cpu', pin_memory=True, buffer_count=5, fast_init=False),
offload_param_config=dict(device='cpu',
pin_memory=True,
buffer_count=5,
buffer_size=1e8,
max_in_cpu=1e9)),
parallel=dict(pipeline=dict(size=1), tensor=dict(size=1, mode=None)))
def run_fwd_bwd(model, data, label, criterion, enable_autocast=False):
model.train()
with torch.cuda.amp.autocast(enabled=enable_autocast):
if criterion:
y = model(data)
loss = criterion(y, label)
else:
loss = model(data, label)
loss = loss.float()
if isinstance(model, ShardedModelV2):
model.backward(loss)
else:
loss.backward()
def checkpoint_wrapper(module, enable=True):
if enable:
module.forward = partial(checkpoint, module.forward)
return module
def allclose(tensor_a: torch.Tensor, tensor_b: torch.Tensor, loose=False) -> bool:
if loose:
return torch.allclose(tensor_a, tensor_b, atol=1e-2, rtol=1e-3)
return torch.allclose(tensor_a, tensor_b)
def check_grads(model, zero_model, loose=False):
for p, zero_p in zip(model.parameters(), zero_model.parameters()):
zero_grad = zero_p.grad.clone().to(p.device)
grad = p.grad.float()
assert grad.dtype == zero_grad.dtype
assert allclose(grad, zero_grad, loose=loose)
def check_params(model, zero_model, loose=False):
for p, zero_p in zip(model.parameters(), zero_model.parameters()):
zero_p = zero_p.clone().to(p.device)
# assert p.dtype == zero_p.dtype
assert allclose(p.float(), zero_p.float(), loose=loose), f"diff {p.float() - zero_p.float()}"
def check_grads_padding(model, zero_model, loose=False):
rank = dist.get_rank()
for (name, p), (zero_name, zero_p) in zip(model.named_parameters(), zero_model.named_parameters()):
# zero_grad = zero_p.grad.clone().to(p.device)
if zero_p.colo_attr.is_replicated:
zero_grad = zero_p.colo_attr.grad_payload.clone().to(p.device)
chunks = torch.flatten(p.grad).chunk(dist.get_world_size())
if rank >= len(chunks):
continue
grad = chunks[rank].float()
if zero_grad.size(0) > grad.size(0):
zero_grad = zero_grad[:grad.size(0)]
else:
zero_grad = zero_p.colo_attr.grad_payload
grad = p.grad.to(zero_grad.dtype)
assert grad.dtype == zero_grad.dtype
assert allclose(grad, zero_grad, loose=loose), f'diff: {grad - zero_grad}'
def check_params_padding(model, zero_model, loose=False):
rank = dist.get_rank()
for p, zero_p in zip(model.parameters(), zero_model.parameters()):
zero_p = zero_p.clone().to(p.device)
chunks = torch.flatten(p).chunk(dist.get_world_size())
if rank >= len(chunks):
continue
p = chunks[rank]
if zero_p.size(0) > p.size(0):
zero_p = zero_p[:p.size(0)]
assert p.dtype == zero_p.dtype
assert allclose(p, zero_p, loose=loose)
def check_sharded_model_params(model, zero_model, loose=False, reuse_fp16_shard=False):
rank = dist.get_rank()
for (name, p), (zero_name, zero_p) in zip(model.named_parameters(), zero_model.named_parameters()):
if zero_p.colo_attr.param_is_sharded:
zero_p = zero_p.colo_attr.data_payload.to(p.device).float()
chunks = torch.flatten(p).chunk(dist.get_world_size())
if rank >= len(chunks):
continue
p = chunks[rank].float()
if zero_p.size(0) > p.size(0):
zero_p = zero_p[:p.size(0)]
else:
zero_p = zero_p.colo_attr.data_payload.to(p.device)
assert p.dtype == zero_p.dtype
assert allclose(p, zero_p, loose=loose), f'{p} vs {zero_p}'
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from functools import partial
import colossalai
import pytest
import torch
import torch.multiprocessing as mp
from colossalai.logging import get_dist_logger
from colossalai.testing import parameterize, rerun_if_address_is_in_use
from colossalai.utils import free_port
from colossalai.utils.cuda import get_current_device
from colossalai.utils.memory_tracer.model_data_memtracer import \
colo_model_mem_usage
from colossalai.utils.memory import colo_device_memory_used
from colossalai.zero.init_ctx import ZeroInitContext
from colossalai.zero.shard_utils import (BucketTensorShardStrategy, TensorShardStrategy)
from tests.components_to_test.registry import non_distributed_component_funcs
from common import CONFIG
@parameterize("init_device_type", ['cpu', 'cuda'])
@parameterize("shard_strategy_class", [TensorShardStrategy, BucketTensorShardStrategy])
def run_model_test(init_device_type, shard_strategy_class):
logger = get_dist_logger("test_zero_init")
for get_components_func in non_distributed_component_funcs:
model_builder, _, _, _, _ = get_components_func()
if init_device_type == 'cuda':
init_device = get_current_device()
elif init_device_type == 'cpu':
init_device = torch.device("cpu")
else:
continue
model_numel_tensor = torch.zeros(1, dtype=torch.int)
with ZeroInitContext(target_device=init_device,
shard_strategy=shard_strategy_class(),
shard_param=True,
model_numel_tensor=model_numel_tensor):
model = model_builder(checkpoint=True)
for param in model.parameters():
assert hasattr(param, 'colo_attr')
assert param.colo_attr.sharded_data_tensor.dtype == torch.half
assert param.colo_attr.sharded_data_tensor.is_sharded
assert param.colo_attr.data_payload.device.type == init_device.type, \
f'{param.colo_attr.data_payload.device.type} vs. {init_device.type}'
cuda_mem_use, _ = colo_model_mem_usage(model)
model_data_cuda_mem_MB = cuda_mem_use / 1e6
logger.info(f"Existing ZeRO Context.\nModel Data CUDA Memory {model_data_cuda_mem_MB} MB", ranks=[0])
sys_cuda_mem_MB = colo_device_memory_used(get_current_device()) / 1e6
logger.info(f"System CUDA Memory Usage {sys_cuda_mem_MB} MB", ranks=[0])
logger.info(f"Model Number Parameter {model_numel_tensor.numpy()[0]/1e6} M", ranks=[0])
def run_dist(rank, world_size, port):
colossalai.launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
run_model_test()
@pytest.mark.dist
@pytest.mark.parametrize("world_size", [1, 4])
@rerun_if_address_is_in_use()
def test_zero_init_context(world_size):
run_func = partial(run_dist, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_zero_init_context(4)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from functools import partial
import colossalai
import pytest
import torch
import torch.multiprocessing as mp
from colossalai.testing import parameterize, rerun_if_address_is_in_use
from colossalai.utils import free_port
from colossalai.zero.init_ctx import ZeroInitContext
from colossalai.zero.shard_utils import (BucketTensorShardStrategy, TensorShardStrategy)
from colossalai.zero.sharded_model import ShardedModelV2
from colossalai.zero.sharded_model._utils import cast_tensor_to_fp16
from colossalai.zero.sharded_model.utils import col_model_deepcopy
from tests.components_to_test.registry import non_distributed_component_funcs
from torch.nn.parallel import DistributedDataParallel as DDP
from common import CONFIG, check_grads_padding, run_fwd_bwd
@parameterize("enable_autocast", [True])
@parameterize("shard_strategy_class", [BucketTensorShardStrategy])
def run_model_test(enable_autocast, shard_strategy_class):
test_models = ['repeated_computed_layers', 'resnet18', 'bert', 'no_leaf_module']
shard_strategy = shard_strategy_class()
for model_name in test_models:
get_components_func = non_distributed_component_funcs.get_callable(model_name)
model_builder, train_dataloader, _, _, criterion = get_components_func()
with ZeroInitContext(target_device=torch.device('cuda', torch.cuda.current_device()),
shard_strategy=shard_strategy,
shard_param=True):
zero_model = model_builder(checkpoint=True)
zero_model = ShardedModelV2(zero_model, shard_strategy)
model = model_builder(checkpoint=True).half()
col_model_deepcopy(zero_model, model)
model = model.cuda()
model = DDP(model, device_ids=[torch.cuda.current_device()])
for i, (data, label) in enumerate(train_dataloader):
if i > 5:
break
data, label = cast_tensor_to_fp16(data).cuda(), label.cuda()
run_fwd_bwd(model, data, label, criterion, enable_autocast)
run_fwd_bwd(zero_model, data, label, criterion, enable_autocast)
check_grads_padding(model, zero_model, loose=True)
def run_dist(rank, world_size, port):
colossalai.launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
run_model_test()
@pytest.mark.dist
@pytest.mark.parametrize("world_size", [1, 2])
@rerun_if_address_is_in_use()
def test_shard_model_v2(world_size):
run_func = partial(run_dist, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_shard_model_v2(world_size=2)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from copy import deepcopy
from functools import partial
import colossalai
import pytest
import torch
import torch.multiprocessing as mp
from colossalai.testing import parameterize, rerun_if_address_is_in_use
from colossalai.utils import free_port
from colossalai.zero.init_ctx import ZeroInitContext
from colossalai.zero.shard_utils import (BucketTensorShardStrategy, TensorShardStrategy)
from colossalai.zero.sharded_model import ShardedModelV2
from colossalai.zero.sharded_model.utils import col_model_deepcopy
from tests.components_to_test.registry import non_distributed_component_funcs
from common import CONFIG
@parameterize("shard_strategy_class", [TensorShardStrategy, BucketTensorShardStrategy])
def run_zero_state_dict(shard_strategy_class):
test_models = ['repeated_computed_layers', 'resnet18']
shard_strategy = shard_strategy_class()
for model_name in test_models:
get_components_func = non_distributed_component_funcs.get_callable(model_name)
model_builder, train_dataloader, test_dataloader, optimizer, criterion = get_components_func()
with ZeroInitContext(target_device=torch.device('cuda', torch.cuda.current_device()),
shard_strategy=shard_strategy,
shard_param=True):
zero_model = model_builder(checkpoint=True)
zero_model = ShardedModelV2(zero_model, shard_strategy)
model = model_builder(checkpoint=True).half()
col_model_deepcopy(zero_model, model)
model = model.cuda()
zero_state_dict = zero_model.state_dict()
for key, val in model.state_dict().items():
assert torch.equal(val, zero_state_dict[key])
def run_dist(rank, world_size, port):
colossalai.launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
run_zero_state_dict()
@pytest.mark.dist
@pytest.mark.parametrize("world_size", [1, 2])
@rerun_if_address_is_in_use()
def test_zero_state_dict(world_size):
run_func = partial(run_dist, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_zero_state_dict(2)
|
import torch
import colossalai
import pytest
import torch.multiprocessing as mp
import torch.nn as nn
import torch.nn.functional as F
from colossalai.utils.cuda import get_current_device
from colossalai.utils.memory import colo_device_memory_capacity, colo_set_process_memory_fraction
from colossalai.zero.init_ctx import ZeroInitContext
from colossalai.zero.sharded_model import ShardedModelV2
from colossalai.zero.shard_utils import BucketTensorShardStrategy
from colossalai.utils import free_port
from colossalai.testing import rerun_if_address_is_in_use
from functools import partial
class TestModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.proj1 = nn.Linear(512, 512)
self.weight = nn.Parameter(torch.randn(1024, 512))
self.proj2 = nn.Linear(1024, 512)
def forward(self, x):
x = self.proj1(x)
x = F.linear(x, self.weight)
x = self.proj2(x)
return x
def run_mem_collector_testing():
cuda_capacity = colo_device_memory_capacity(get_current_device())
fraction = (50 * 1024**2) / cuda_capacity
# limit max memory to 50MB
colo_set_process_memory_fraction(fraction)
shard_strategy = BucketTensorShardStrategy()
with ZeroInitContext(target_device=get_current_device(), shard_strategy=shard_strategy, shard_param=True):
model = TestModel()
model = ShardedModelV2(module=model,
shard_strategy=shard_strategy,
reduce_scatter_bucket_size_mb=1,
tensor_placement_policy='auto')
data = torch.randn(2, 512, device=get_current_device())
output = model(data)
loss = torch.mean(output)
model.backward(loss)
cuda_model_data_list = model._memstats_collector.model_data_list('cuda')
assert cuda_model_data_list == [1311744, 1836032, 1836032, 1311744, 1836032, 1836032]
cuda_non_model_data_list = model._memstats_collector.non_model_data_list('cuda')
assert cuda_non_model_data_list[0] > cuda_non_model_data_list[1]
assert cuda_non_model_data_list[-2] > cuda_non_model_data_list[-1]
def run_dist(rank, world_size, port):
colossalai.launch(config={}, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
run_mem_collector_testing()
@pytest.mark.dist
@rerun_if_address_is_in_use()
def test_mem_collector(world_size=2):
run_func = partial(run_dist, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_mem_collector()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import copy
import colossalai
from colossalai.zero.sharded_model.sharded_model_v2 import ShardedModelV2
import pytest
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn as nn
from colossalai.logging import disable_existing_loggers
from colossalai.utils import checkpoint, clip_grad_norm_fp32, free_port
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.nn.utils import clip_grad_norm_
from colossalai.zero.shard_utils.tensor_shard_strategy import TensorShardStrategy
from functools import partial
from colossalai.testing import parameterize, rerun_if_address_is_in_use
def checkpoint_wrapper(module, enable=True):
if enable:
module.forward = partial(checkpoint, module.forward, False)
return module
class Net(nn.Module):
def __init__(self, checkpoint=False) -> None:
super().__init__()
self.fc1 = nn.Linear(5, 5)
self.fc2 = nn.Linear(5, 5)
self.fc3 = nn.Linear(5, 1)
if checkpoint:
self.fc1 = checkpoint_wrapper(self.fc1)
self.layers = [self.fc1, self.fc2, self.fc1, self.fc2, self.fc3]
def forward(self, x):
for layer in self.layers:
x = layer(x)
return x
def run_step(model, optimizer, x, enable_autocast=False, norm_type=2.0):
model.train()
optimizer.zero_grad()
with torch.cuda.amp.autocast(enabled=enable_autocast):
y = model(x)
loss = y.sum()
loss = loss.float()
loss.backward()
clip_grad(model, norm_type)
optimizer.step()
def clip_grad(model, norm_type):
if isinstance(model, DDP):
clip_grad_norm_(model.parameters(), max_norm=1.0, norm_type=norm_type)
else:
clip_grad_norm_fp32(model.parameters(), max_norm=1.0, norm_type=norm_type)
def allclose(tensor_a: torch.Tensor, tensor_b: torch.Tensor, loose=False) -> bool:
if loose:
return torch.allclose(tensor_a, tensor_b, atol=1e-3, rtol=1e-3)
return torch.allclose(tensor_a, tensor_b)
def check_grads(model, zero_model, loose=False):
rank = dist.get_rank()
for p, zero_p in zip(model.parameters(), zero_model.parameters()):
zero_grad = zero_p.grad.clone().to(p.device)
chunks = torch.flatten(p.grad).chunk(4)
if rank >= len(chunks):
continue
grad = chunks[rank]
if zero_p.zero_shard_padding > 0:
zero_grad = zero_grad[:-zero_p.zero_shard_padding]
assert grad.dtype == zero_grad.dtype
assert allclose(grad, zero_grad, loose=loose)
def check_params(model, zero_model, loose=False):
rank = dist.get_rank()
for p, zero_p in zip(model.parameters(), zero_model.parameters()):
zero_shard_padding = zero_p.zero_shard_padding
zero_p = zero_p.clone().to(p.device)
chunks = torch.flatten(p).chunk(4)
if rank >= len(chunks):
continue
p = chunks[rank]
if zero_shard_padding > 0:
zero_p = zero_p[:-zero_shard_padding]
assert p.dtype == zero_p.dtype
assert allclose(p, zero_p, loose=loose)
def run_dist(rank, world_size, port):
disable_existing_loggers()
colossalai.launch(config={}, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
@pytest.mark.dist
@rerun_if_address_is_in_use()
def test_zero_clip_grad():
world_size = 4
run_func = partial(run_dist, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_zero_clip_grad()
|
import os
from functools import partial
from pathlib import Path
import colossalai
from colossalai.testing.utils import rerun_if_address_is_in_use
import pytest
import torch
import torch.multiprocessing as mp
import torch.nn as nn
from colossalai.core import global_context as gpc
from colossalai.logging import get_dist_logger
from colossalai.utils import free_port, get_dataloader
from colossalai.testing import rerun_if_address_is_in_use
from torch.optim import Adam
from torchvision import transforms
from torchvision.datasets import CIFAR10
from torchvision.models import resnet18
# Config
BATCH_SIZE = 2
NUM_CLASSES = 10
CONFIG = dict(parallel=dict(pipeline=dict(size=1), tensor=dict(size=1, mode=None)),
clip_grad_norm=1.0,
gradient_accumulation=4)
def run_no_pipeline(rank, world_size, port):
# init dist env
colossalai.launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
# build model
model = resnet18(num_classes=10)
# build dataloaders
train_dataset = CIFAR10(root=Path(os.environ['DATA']),
download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))
]))
train_dataloader = get_dataloader(dataset=train_dataset,
shuffle=True,
batch_size=BATCH_SIZE,
pin_memory=True,
drop_last=True)
# build optimizer
optimizer = Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()
engine, train_dataloader, *args = colossalai.initialize(model=model,
optimizer=optimizer,
criterion=criterion,
train_dataloader=train_dataloader)
logger = get_dist_logger()
rank = torch.distributed.get_rank()
param_track = []
grad_track = []
next(model.parameters()).retain_grad()
engine.train()
step = 0
for img, label in train_dataloader:
engine.zero_grad()
img = img.cuda()
label = label.cuda()
output = engine(img)
loss = engine.criterion(output, label)
engine.backward(loss)
engine.step()
# check
param_track.append(next(model.parameters())[0].clone())
grad_track.append(next(model.parameters()).grad[0].clone())
step += 1
if step == CONFIG['gradient_accumulation']:
break
assert not torch.all(grad_track[0] == grad_track[-1]), 'grad should be different in different iterations'
assert torch.all(param_track[0] == param_track[1]) and not torch.all(param_track[0] == param_track[-1]), \
'param should be the same in the first few iterations and only changed in the last iteration'
gpc.destroy()
torch.cuda.empty_cache()
@pytest.mark.dist
@rerun_if_address_is_in_use()
def test_engine():
world_size = 4
func = partial(run_no_pipeline, world_size=world_size, port=free_port())
mp.spawn(func, nprocs=world_size)
if __name__ == '__main__':
test_engine()
|
from colossalai.zero.sharded_param.tensor_utils import colo_model_data_tensor_move, colo_model_data_tensor_move_inline
from colossalai.utils import free_port
from colossalai.testing import rerun_if_address_is_in_use
from colossalai.zero.sharded_param import ShardedTensor
import colossalai
import torch
import torch.multiprocessing as mp
def run_tensor_move(rank):
colossalai.launch(config={}, rank=0, world_size=1, host='localhost', port=free_port(), backend='nccl')
src_t = torch.ones(2, 3).cuda()
tgt_t = torch.zeros(2, 3)
colo_model_data_tensor_move(src_t, tgt_t)
assert (torch.sum(tgt_t) == 6.0), f"{torch.sum(tgt_t.payload)} vs. 6.0"
src_t = torch.ones(2, 3)
tgt_t = torch.zeros(2, 3).cuda().half()
colo_model_data_tensor_move(src_t, tgt_t)
# the src_t has been removed
assert (src_t.numel() == 0)
assert (torch.sum(tgt_t) == 6.0), f"{torch.sum(tgt_t.payload)} vs. 6.0"
src_t = ShardedTensor(torch.ones(2, 3))
tgt_t = ShardedTensor(torch.zeros(2, 3).cuda().half())
colo_model_data_tensor_move(src_t, tgt_t)
assert (torch.sum(tgt_t.payload) == 6.0), f"{torch.sum(tgt_t.payload)} vs. 6.0"
assert (tgt_t.device.type == 'cuda')
colo_model_data_tensor_move_inline(tgt_t, torch.device('cpu'))
assert (tgt_t.device.type == 'cpu')
@rerun_if_address_is_in_use()
def test_tensor_move():
mp.spawn(run_tensor_move, nprocs=1)
if __name__ == '__main__':
test_tensor_move()
|
import pytest
import colossalai
from colossalai.utils.cuda import get_current_device
from colossalai.utils.memory import colo_set_process_memory_fraction, colo_device_memory_capacity
from colossalai.utils import free_port
from functools import partial
import torch.multiprocessing as mp
def _run_colo_set_process_memory_fraction_and_colo_device_memory_capacity():
frac1 = colo_device_memory_capacity(get_current_device())
colo_set_process_memory_fraction(0.5)
frac2 = colo_device_memory_capacity(get_current_device())
assert frac2 * 2 == frac1
def run_dist(rank, world_size, port):
colossalai.launch(config={}, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
_run_colo_set_process_memory_fraction_and_colo_device_memory_capacity()
@pytest.mark.dist
@pytest.mark.parametrize("world_size", [4, 5])
def test_memory_utils(world_size):
run_func = partial(run_dist, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_memory_utils(world_size=2)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import pytest
import torch
import torch.nn.functional as F
from colossalai.context.parallel_mode import ParallelMode
from colossalai.context.random import add_seed, seed, set_mode, reset_seeds
from colossalai.utils import checkpoint
def forward(x, weight):
out = torch.matmul(x, weight)
with seed(ParallelMode.DATA):
out_ = F.dropout(out, p=0.4, training=True)
return out_
@pytest.mark.gpu
@pytest.mark.parametrize("cpu_offload", [True, False])
def test_activation_checkpointing(cpu_offload):
# We put initilization here to avoid change cuda rng state below
inputs = torch.rand(2, 2, requires_grad=True, device='cuda')
weight = torch.rand(2, 4, requires_grad=True, device='cuda')
# Get a copy of input tensors
inputs_ = torch.empty(2, 2, requires_grad=True, device='cuda')
inputs_.data.copy_(inputs.data)
weight_ = torch.empty(2, 4, requires_grad=True, device='cuda')
weight_.data.copy_(weight.data)
add_seed(ParallelMode.GLOBAL, 1024)
add_seed(ParallelMode.DATA, 1026)
set_mode(ParallelMode.GLOBAL)
global_cuda_rng_state = torch.cuda.get_rng_state()
set_mode(ParallelMode.DATA)
data_parallel_cuda_rng_state = torch.cuda.get_rng_state()
set_mode(ParallelMode.GLOBAL)
out = forward(inputs, weight)
loss = out.sum()
loss.backward()
# Recover cuda rng states
set_mode(ParallelMode.GLOBAL)
torch.cuda.set_rng_state(global_cuda_rng_state)
set_mode(ParallelMode.DATA)
torch.cuda.set_rng_state(data_parallel_cuda_rng_state)
set_mode(ParallelMode.GLOBAL)
out = checkpoint(forward, cpu_offload, inputs_, weight_)
loss = out.sum()
loss.backward()
assert torch.all(inputs.grad == inputs_.grad), 'Gradient of the input does not match'
torch.cuda.empty_cache()
# as seed manager is singleton
# if we don't reset seeds here,
# other tests will fail if running together with this test
# as other tests can't overwrite the seed set by this test
reset_seeds()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import pprint
from functools import partial
import colossalai.nn as col_nn
import pytest
import torch
import torch.multiprocessing as mp
import torch.nn as nn
from colossalai.context.parallel_mode import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.initialize import launch
from colossalai.logging import disable_existing_loggers
from colossalai.utils import free_port, get_current_device, is_using_pp
from colossalai.utils.checkpointing import gather_pipeline_parallel_state_dict, load_checkpoint, save_checkpoint
from colossalai.testing import rerun_on_exception
def build_pipeline(model):
from colossalai.builder.pipeline import partition_uniform
pipeline_size = gpc.get_world_size(ParallelMode.PIPELINE)
pipeline_rank = gpc.get_local_rank(ParallelMode.PIPELINE)
depth = len(model)
start, end = partition_uniform(depth, pipeline_size, 1)[pipeline_rank][0]
layers = []
for i in range(depth):
if start <= i < end:
layers.append(model[i])
else:
layers.append(nn.Identity())
return nn.Sequential(*tuple(layers))
def check_equal(A, B):
assert torch.allclose(A, B, rtol=1e-3, atol=1e-2)
def check_checkpoint_2p5d(rank, world_size, port):
config = dict(parallel=dict(pipeline=dict(size=2), tensor=dict(size=4, depth=1, mode="2.5d")),)
disable_existing_loggers()
launch(config=config, rank=rank, world_size=world_size, host="localhost", port=port, backend="nccl")
m1 = nn.Sequential(nn.Linear(4, 8), nn.Linear(8, 4))
sd1 = m1.state_dict()
if gpc.get_global_rank() == 0:
print(f"Rank {gpc.get_global_rank()}:\n{pprint.pformat(sd1)}\n")
save_checkpoint("test.pt", 0, m1)
m2 = nn.Sequential(col_nn.Linear(4, 8), col_nn.Linear(8, 4))
if is_using_pp():
m2 = build_pipeline(m2)
load_checkpoint("test.pt", m2)
sd2 = m2.state_dict()
if is_using_pp() and gpc.get_local_rank(ParallelMode.TENSOR) == 0:
sd2 = gather_pipeline_parallel_state_dict(sd2)
print(f"Rank {gpc.get_global_rank()}:\n{pprint.pformat(sd2)}\n")
if gpc.get_global_rank() == 0:
for k, v in sd1.items():
assert k in sd2
check_equal(v, sd2[k].to(torch.device("cpu")))
@pytest.mark.dist
@rerun_on_exception(exception_type=mp.ProcessRaisedException, pattern=".*Address already in use.*")
def test_checkpoint_2p5d():
world_size = 8
run_func = partial(check_checkpoint_2p5d, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == "__main__":
test_checkpoint_2p5d()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import pprint
from functools import partial
import colossalai.nn as col_nn
import pytest
import torch
import torch.multiprocessing as mp
import torch.nn as nn
from colossalai.context.parallel_mode import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.initialize import launch
from colossalai.logging import disable_existing_loggers
from colossalai.utils import free_port, get_current_device, is_using_pp
from colossalai.utils.checkpointing import gather_pipeline_parallel_state_dict, load_checkpoint, save_checkpoint
from colossalai.testing import rerun_on_exception
def build_pipeline(model):
from colossalai.builder.pipeline import partition_uniform
pipeline_size = gpc.get_world_size(ParallelMode.PIPELINE)
pipeline_rank = gpc.get_local_rank(ParallelMode.PIPELINE)
depth = len(model)
start, end = partition_uniform(depth, pipeline_size, 1)[pipeline_rank][0]
layers = []
for i in range(depth):
if start <= i < end:
layers.append(model[i])
else:
layers.append(nn.Identity())
return nn.Sequential(*tuple(layers))
def check_equal(A, B):
assert torch.allclose(A, B, rtol=1e-3, atol=1e-2)
def check_checkpoint_3d(rank, world_size, port):
config = dict(parallel=dict(pipeline=dict(size=1), tensor=dict(size=8, mode="3d")),)
disable_existing_loggers()
launch(config=config, rank=rank, world_size=world_size, host="localhost", port=port, backend="nccl")
m1 = nn.Sequential(nn.Linear(4, 8), nn.Linear(8, 4))
sd1 = m1.state_dict()
if gpc.get_global_rank() == 0:
print(f"Rank {gpc.get_global_rank()}:\n{pprint.pformat(sd1)}\n")
save_checkpoint("test.pt", 0, m1)
m2 = nn.Sequential(col_nn.Linear(4, 8), col_nn.Linear(8, 4))
if is_using_pp():
m2 = build_pipeline(m2)
load_checkpoint("test.pt", m2)
sd2 = m2.state_dict()
if is_using_pp() and gpc.get_local_rank(ParallelMode.TENSOR) == 0:
sd2 = gather_pipeline_parallel_state_dict(sd2)
print(f"Rank {gpc.get_global_rank()}:\n{pprint.pformat(sd2)}\n")
if gpc.get_global_rank() == 0:
for k, v in sd1.items():
assert k in sd2
check_equal(v, sd2[k].to(torch.device("cpu")))
@pytest.mark.dist
@rerun_on_exception(exception_type=mp.ProcessRaisedException, pattern=".*Address already in use.*")
def test_checkpoint_3d():
world_size = 8
run_func = partial(check_checkpoint_3d, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == "__main__":
test_checkpoint_3d()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import pprint
from functools import partial
import colossalai.nn as col_nn
import pytest
import torch
import torch.multiprocessing as mp
import torch.nn as nn
from colossalai.context.parallel_mode import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.initialize import launch
from colossalai.logging import disable_existing_loggers
from colossalai.utils import free_port, get_current_device, is_using_pp
from colossalai.utils.checkpointing import gather_pipeline_parallel_state_dict, load_checkpoint, save_checkpoint
from colossalai.testing import rerun_on_exception
def build_pipeline(model):
from colossalai.builder.pipeline import partition_uniform
pipeline_size = gpc.get_world_size(ParallelMode.PIPELINE)
pipeline_rank = gpc.get_local_rank(ParallelMode.PIPELINE)
depth = len(model)
start, end = partition_uniform(depth, pipeline_size, 1)[pipeline_rank][0]
layers = []
for i in range(depth):
if start <= i < end:
layers.append(model[i])
else:
layers.append(nn.Identity())
return nn.Sequential(*tuple(layers))
def check_equal(A, B):
assert torch.allclose(A, B, rtol=1e-3, atol=1e-2)
def check_checkpoint_2d(rank, world_size, port):
config = dict(parallel=dict(pipeline=dict(size=2), tensor=dict(size=4, mode="2d")),)
disable_existing_loggers()
launch(config=config, rank=rank, world_size=world_size, host="localhost", port=port, backend="nccl")
m1 = nn.Sequential(nn.Linear(4, 8), nn.Linear(8, 4))
sd1 = m1.state_dict()
if gpc.get_global_rank() == 0:
print(f"Rank {gpc.get_global_rank()}:\n{pprint.pformat(sd1)}\n")
save_checkpoint("test.pt", 0, m1)
m2 = nn.Sequential(col_nn.Linear(4, 8), col_nn.Linear(8, 4))
if is_using_pp():
m2 = build_pipeline(m2)
load_checkpoint("test.pt", m2)
sd2 = m2.state_dict()
if is_using_pp() and gpc.get_local_rank(ParallelMode.TENSOR) == 0:
sd2 = gather_pipeline_parallel_state_dict(sd2)
print(f"Rank {gpc.get_global_rank()}:\n{pprint.pformat(sd2)}\n")
if gpc.get_global_rank() == 0:
for k, v in sd1.items():
assert k in sd2
check_equal(v, sd2[k].to(torch.device("cpu")))
@pytest.mark.dist
@rerun_on_exception(exception_type=mp.ProcessRaisedException, pattern=".*Address already in use.*")
def test_checkpoint_2d():
world_size = 8
run_func = partial(check_checkpoint_2d, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == "__main__":
test_checkpoint_2d()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import pprint
from functools import partial
import colossalai.nn as col_nn
import pytest
import torch
import torch.multiprocessing as mp
import torch.nn as nn
from colossalai.context.parallel_mode import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.initialize import launch
from colossalai.logging import disable_existing_loggers
from colossalai.utils import free_port, is_using_pp
from colossalai.utils.checkpointing import gather_pipeline_parallel_state_dict, load_checkpoint, save_checkpoint
from colossalai.testing import rerun_on_exception
def build_pipeline(model):
from colossalai.builder.pipeline import partition_uniform
pipeline_size = gpc.get_world_size(ParallelMode.PIPELINE)
pipeline_rank = gpc.get_local_rank(ParallelMode.PIPELINE)
depth = len(model)
start, end = partition_uniform(depth, pipeline_size, 1)[pipeline_rank][0]
layers = []
for i in range(depth):
if start <= i < end:
layers.append(model[i])
else:
layers.append(nn.Identity())
return nn.Sequential(*tuple(layers))
def check_equal(A, B):
assert torch.allclose(A, B, rtol=1e-3, atol=1e-2)
def check_checkpoint_1d(rank, world_size, port):
config = dict(parallel=dict(pipeline=dict(size=2), tensor=dict(size=4, mode="1d")),)
disable_existing_loggers()
launch(config=config, rank=rank, world_size=world_size, host="localhost", port=port, backend="nccl")
m1 = nn.Sequential(nn.Linear(4, 8), nn.Linear(8, 4))
sd1 = m1.state_dict()
if gpc.get_global_rank() == 0:
print(f"Rank {gpc.get_global_rank()}:\n{pprint.pformat(sd1)}\n")
save_checkpoint("test.pt", 0, m1)
m2 = nn.Sequential(col_nn.Linear(4, 8), col_nn.Linear(8, 4))
if is_using_pp():
m2 = build_pipeline(m2)
load_checkpoint("test.pt", m2)
sd2 = m2.state_dict()
if is_using_pp() and gpc.get_local_rank(ParallelMode.TENSOR) == 0:
sd2 = gather_pipeline_parallel_state_dict(sd2)
print(f"Rank {gpc.get_global_rank()}:\n{pprint.pformat(sd2)}\n")
if gpc.get_global_rank() == 0:
for k, v in sd1.items():
assert k in sd2
check_equal(v, sd2[k].to(torch.device("cpu")))
@pytest.mark.dist
@rerun_on_exception(exception_type=mp.ProcessRaisedException, pattern=".*Address already in use.*")
def test_checkpoint_1d():
world_size = 8
run_func = partial(check_checkpoint_1d, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == "__main__":
test_checkpoint_1d()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
from pathlib import Path
import pytest
from torchvision import transforms
from torch.utils.data import DataLoader
from colossalai.builder import build_dataset, build_transform
from colossalai.context import Config
TRAIN_DATA = dict(
dataset=dict(
type='CIFAR10',
root=Path(os.environ['DATA']),
train=True,
download=True
),
dataloader=dict(batch_size=4, shuffle=True, num_workers=2),
transform_pipeline=[
dict(type='ToTensor'),
dict(type='Normalize',
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5)
)
]
)
@pytest.mark.cpu
def test_cifar10_dataset():
config = Config(TRAIN_DATA)
dataset_cfg = config.dataset
dataloader_cfg = config.dataloader
transform_cfg = config.transform_pipeline
# build transform
transform_pipeline = [build_transform(cfg) for cfg in transform_cfg]
transform_pipeline = transforms.Compose(transform_pipeline)
dataset_cfg['transform'] = transform_pipeline
# build dataset
dataset = build_dataset(dataset_cfg)
# build dataloader
dataloader = DataLoader(dataset=dataset, **dataloader_cfg)
data_iter = iter(dataloader)
img, label = data_iter.next()
if __name__ == '__main__':
test_cifar10_dataset()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
from functools import partial
from pathlib import Path
import pytest
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.utils.data import DataLoader
import colossalai
from colossalai.builder import build_dataset, build_transform
from torchvision import transforms
from colossalai.context import ParallelMode, Config
from colossalai.core import global_context as gpc
from colossalai.utils import get_dataloader, free_port
from colossalai.testing import rerun_if_address_is_in_use
CONFIG = Config(
dict(
train_data=dict(dataset=dict(
type='CIFAR10',
root=Path(os.environ['DATA']),
train=True,
download=True,
),
dataloader=dict(batch_size=8,),
transform_pipeline=[
dict(type='ToTensor'),
dict(type='Normalize', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))
]),
parallel=dict(
pipeline=dict(size=1),
tensor=dict(size=1, mode=None),
),
seed=1024,
))
def run_data_sampler(rank, world_size, port):
dist_args = dict(config=CONFIG, rank=rank, world_size=world_size, backend='gloo', port=port, host='localhost')
colossalai.launch(**dist_args)
print('finished initialization')
transform_pipeline = [build_transform(cfg) for cfg in gpc.config.train_data.transform_pipeline]
transform_pipeline = transforms.Compose(transform_pipeline)
gpc.config.train_data.dataset['transform'] = transform_pipeline
dataset = build_dataset(gpc.config.train_data.dataset)
dataloader = get_dataloader(dataset, **gpc.config.train_data.dataloader)
data_iter = iter(dataloader)
img, label = data_iter.next()
img = img[0]
if gpc.get_local_rank(ParallelMode.DATA) != 0:
img_to_compare = img.clone()
else:
img_to_compare = img
dist.broadcast(img_to_compare, src=0, group=gpc.get_group(ParallelMode.DATA))
if gpc.get_local_rank(ParallelMode.DATA) != 0:
assert not torch.equal(
img, img_to_compare), 'Same image was distributed across ranks but expected it to be different'
torch.cuda.empty_cache()
@pytest.mark.cpu
@rerun_if_address_is_in_use()
def test_data_sampler():
world_size = 4
test_func = partial(run_data_sampler, world_size=world_size, port=free_port())
mp.spawn(test_func, nprocs=world_size)
if __name__ == '__main__':
test_data_sampler()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
from functools import partial
from pathlib import Path
import pytest
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torchvision import transforms
from torch.utils.data import DataLoader
import colossalai
from colossalai.builder import build_dataset, build_transform
from colossalai.context import ParallelMode, Config
from colossalai.core import global_context as gpc
from colossalai.utils import free_port
from colossalai.testing import rerun_if_address_is_in_use
CONFIG = Config(
dict(
train_data=dict(dataset=dict(
type='CIFAR10',
root=Path(os.environ['DATA']),
train=True,
download=True,
),
dataloader=dict(num_workers=2, batch_size=2, shuffle=True),
transform_pipeline=[
dict(type='ToTensor'),
dict(type='RandomCrop', size=32),
dict(type='Normalize', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))
]),
parallel=dict(
pipeline=dict(size=1),
tensor=dict(size=1, mode=None),
),
seed=1024,
))
def run_data_sampler(rank, world_size, port):
dist_args = dict(config=CONFIG, rank=rank, world_size=world_size, backend='gloo', port=port, host='localhost')
colossalai.launch(**dist_args)
dataset_cfg = gpc.config.train_data.dataset
dataloader_cfg = gpc.config.train_data.dataloader
transform_cfg = gpc.config.train_data.transform_pipeline
# build transform
transform_pipeline = [build_transform(cfg) for cfg in transform_cfg]
transform_pipeline = transforms.Compose(transform_pipeline)
dataset_cfg['transform'] = transform_pipeline
# build dataset
dataset = build_dataset(dataset_cfg)
# build dataloader
dataloader = DataLoader(dataset=dataset, **dataloader_cfg)
data_iter = iter(dataloader)
img, label = data_iter.next()
img = img[0]
if gpc.get_local_rank(ParallelMode.DATA) != 0:
img_to_compare = img.clone()
else:
img_to_compare = img
dist.broadcast(img_to_compare, src=0, group=gpc.get_group(ParallelMode.DATA))
if gpc.get_local_rank(ParallelMode.DATA) != 0:
# this is without sampler
# this should be false if data parallel sampler to given to the dataloader
assert torch.equal(img,
img_to_compare), 'Same image was distributed across ranks and expected it to be the same'
torch.cuda.empty_cache()
@pytest.mark.cpu
@rerun_if_address_is_in_use()
def test_data_sampler():
world_size = 4
test_func = partial(run_data_sampler, world_size=world_size, port=free_port())
mp.spawn(test_func, nprocs=world_size)
if __name__ == '__main__':
test_data_sampler()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from functools import partial
import pytest
import torch
import torch.multiprocessing as mp
from colossalai.core import global_context as gpc
from colossalai.logging import disable_existing_loggers
from colossalai.initialize import launch
from colossalai.utils import free_port
from colossalai.testing import rerun_if_address_is_in_use
from checks_1d.check_layer_1d import *
CONFIG = dict(parallel=dict(pipeline=dict(size=1), tensor=dict(size=4, mode='1d')),)
def check_layer(rank, world_size, port):
disable_existing_loggers()
launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
check_linear_col()
check_linear_row()
check_embed()
check_vocab_parallel_embed()
check_classifier_no_given_weight()
check_vocab_parallel_classifier_no_given_weight()
check_classifier_given_embed_weight()
check_vocab_parallel_classifier_given_embed_weight()
check_vocab_parallel_loss()
gpc.destroy()
torch.cuda.empty_cache()
@pytest.mark.dist
@rerun_if_address_is_in_use()
def test_1d():
world_size = 4
run_func = partial(check_layer, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_1d()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import torch
DEPTH = 4
BATCH_SIZE = 8
SEQ_LENGTH = 8
IMG_SIZE = 16
HIDDEN_SIZE = 8
NUM_CLASSES = 8
VOCAB_SIZE = 16
def check_equal(A, B):
assert torch.allclose(A, B, rtol=1e-3, atol=1e-1) == True
|
import torch
import torch.distributed as dist
from colossalai.context.parallel_mode import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.global_variables import tensor_parallel_env as env
from colossalai.nn import (Classifier1D, Embedding1D, Linear1D_Col, Linear1D_Row, VanillaClassifier,
VocabParallelClassifier1D, VocabParallelCrossEntropyLoss1D, VocabParallelEmbedding1D)
from colossalai.utils import get_current_device, print_rank_0
from torch.nn import Parameter
from .common import BATCH_SIZE, DEPTH, HIDDEN_SIZE, NUM_CLASSES, SEQ_LENGTH, VOCAB_SIZE, check_equal
def check_linear_col():
device = get_current_device()
dtype = torch.float32
INPUT_SIZE = HIDDEN_SIZE
OUTPUT_SIZE = 2 * HIDDEN_SIZE
i = gpc.get_local_rank(ParallelMode.PARALLEL_1D)
layer = Linear1D_Col(INPUT_SIZE, OUTPUT_SIZE)
A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
dist.broadcast(A_master, src=0)
A = A_master.clone()
A.requires_grad = True
W_shape = (OUTPUT_SIZE, INPUT_SIZE)
W_master = torch.randn(W_shape, dtype=dtype, device=device)
dist.broadcast(W_master, src=0)
W = torch.chunk(W_master, DEPTH, dim=0)[i]
W = W.clone()
W.requires_grad = True
B_shape = (OUTPUT_SIZE)
B_master = torch.randn(B_shape, dtype=dtype, device=device)
dist.broadcast(B_master, src=0)
B = torch.chunk(B_master, DEPTH, dim=0)[i]
B = B.clone()
B.requires_grad = True
layer.weight = Parameter(W)
layer.bias = Parameter(B)
out = layer(A)
A_master = A_master.clone()
A_master.requires_grad = True
W_master = W_master.clone()
W_master.requires_grad = True
B_master = B_master.clone()
B_master.requires_grad = True
C_master = torch.matmul(A_master, W_master.transpose(0, 1)) + B_master
C = torch.chunk(C_master, DEPTH, dim=-1)[i]
check_equal(out, C)
print_rank_0('linear_col forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=get_current_device())
dist.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=-1)[i]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
A_grad = A_master.grad
check_equal(A_grad, A.grad)
W_grad = W_master.grad
W_grad = torch.chunk(W_grad, DEPTH, dim=0)[i]
check_equal(W_grad, layer.weight.grad)
B_grad = B_master.grad
B_grad = torch.chunk(B_grad, DEPTH, dim=0)[i]
check_equal(B_grad, layer.bias.grad)
print_rank_0('linear_col backward: pass')
def check_linear_row():
device = get_current_device()
dtype = torch.float32
INPUT_SIZE = HIDDEN_SIZE
OUTPUT_SIZE = 2 * HIDDEN_SIZE
i = gpc.get_local_rank(ParallelMode.PARALLEL_1D)
layer = Linear1D_Row(OUTPUT_SIZE, INPUT_SIZE)
A_shape = (BATCH_SIZE, SEQ_LENGTH, OUTPUT_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
dist.broadcast(A_master, src=0)
A = torch.chunk(A_master, DEPTH, dim=-1)[i]
A = A.clone()
A.requires_grad = True
W_shape = (INPUT_SIZE, OUTPUT_SIZE)
W_master = torch.randn(W_shape, dtype=dtype, device=device)
dist.broadcast(W_master, src=0)
W = torch.chunk(W_master, DEPTH, dim=-1)[i]
W = W.clone()
W.requires_grad = True
B_shape = (INPUT_SIZE)
B_master = torch.randn(B_shape, dtype=dtype, device=device)
dist.broadcast(B_master, src=0)
B = B_master.clone()
B.requires_grad = True
layer.weight = Parameter(W)
layer.bias = Parameter(B)
out = layer(A)
A_master = A_master.clone()
A_master.requires_grad = True
W_master = W_master.clone()
W_master.requires_grad = True
B_master = B_master.clone()
B_master.requires_grad = True
C_master = torch.matmul(A_master, W_master.transpose(0, 1)) + B_master
C = C_master.clone()
check_equal(out, C)
print_rank_0('linear_row forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=get_current_device())
dist.broadcast(grad_master, src=0)
grad = grad_master.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, DEPTH, dim=-1)[i]
check_equal(A_grad, A.grad)
W_grad = W_master.grad
W_grad = torch.chunk(W_grad, DEPTH, dim=-1)[i]
check_equal(W_grad, layer.weight.grad)
B_grad = B_master.grad
check_equal(B_grad, layer.bias.grad)
print_rank_0('linear_row backward: pass')
def check_embed():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_1D)
embed = Embedding1D(VOCAB_SIZE, HIDDEN_SIZE)
embed = embed.to(dtype).to(device)
embed_master = torch.nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
embed_master = embed_master.to(dtype).to(device)
weight_master = embed_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, DEPTH, dim=-1)[i]
embed.weight.data.copy_(weight)
A_shape = (BATCH_SIZE, SEQ_LENGTH)
A_master = torch.randint(VOCAB_SIZE, A_shape, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = embed(A)
A_master = A_master.clone()
C_master = embed_master(A_master)
C = C_master.clone()
check_equal(out, C)
print_rank_0('embed forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = grad_master.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
B_grad = embed_master.weight.grad
B_grad = torch.chunk(B_grad, DEPTH, dim=-1)[i]
check_equal(B_grad, embed.weight.grad)
print_rank_0('embed backward: pass')
def check_vocab_parallel_embed():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_1D)
embed = VocabParallelEmbedding1D(VOCAB_SIZE, HIDDEN_SIZE)
embed = embed.to(dtype).to(device)
embed_master = torch.nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
embed_master = embed_master.to(dtype).to(device)
weight_master = embed_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, DEPTH, dim=0)[i]
embed.weight.data.copy_(weight)
A_shape = (BATCH_SIZE, SEQ_LENGTH)
A_master = torch.randint(VOCAB_SIZE, A_shape, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = embed(A)
A_master = A_master.clone()
C_master = embed_master(A_master)
C = C_master.clone()
check_equal(out, C)
print_rank_0('vocab parallel embed forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = grad_master.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
B_grad = embed_master.weight.grad
B_grad = torch.chunk(B_grad, DEPTH, dim=0)[i]
check_equal(B_grad, embed.weight.grad)
print_rank_0('vocab parallel embed backward: pass')
def check_classifier_no_given_weight():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_1D)
env.parallel_input_1d = False
parallel_input_1d = env.parallel_input_1d
layer = Classifier1D(HIDDEN_SIZE, NUM_CLASSES, bias=True)
layer.to(dtype).to(device)
layer_master = VanillaClassifier(HIDDEN_SIZE, NUM_CLASSES, bias=True)
layer_master = layer_master.to(dtype).to(device)
W_master = layer_master.weight.data
dist.broadcast(W_master, src=0)
W = torch.chunk(W_master, DEPTH, dim=-1)[i]
layer.weight.data.copy_(W)
B_master = layer_master.bias.data
dist.broadcast(B_master, src=0)
B = B_master.clone()
layer.bias.data.copy_(B)
A_shape = (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
dist.broadcast(A_master, src=0)
if parallel_input_1d:
A = torch.chunk(A_master, DEPTH, dim=-1)[i]
A = A.clone()
else:
A = A_master.clone()
A.requires_grad = True
out = layer(A)
A_master = A_master.clone()
A_master.requires_grad = True
C_master = layer_master(A_master)
C = C_master.clone()
check_equal(out, C)
print_rank_0('classifier (no given weight) forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
dist.broadcast(grad_master, src=0)
grad = grad_master.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
A_grad = A_master.grad
if parallel_input_1d:
A_grad = torch.chunk(A_grad, DEPTH, dim=-1)[i]
check_equal(A_grad, A.grad)
W_grad = layer_master.weight.grad
W_grad = torch.chunk(W_grad, DEPTH, dim=-1)[i]
check_equal(W_grad, layer.weight.grad)
B_grad = layer_master.bias.grad
check_equal(B_grad, layer.bias.grad)
print_rank_0('classifier (no given weight) backward: pass')
def check_vocab_parallel_classifier_no_given_weight():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_1D)
layer = VocabParallelClassifier1D(HIDDEN_SIZE, VOCAB_SIZE, bias=True)
layer.to(dtype).to(device)
layer_master = VanillaClassifier(HIDDEN_SIZE, VOCAB_SIZE, bias=True)
layer_master = layer_master.to(dtype).to(device)
W_master = layer_master.weight.data
dist.broadcast(W_master, src=0)
W = torch.chunk(W_master, DEPTH, dim=0)[i]
layer.weight.data.copy_(W)
B_master = layer_master.bias.data
dist.broadcast(B_master, src=0)
B = torch.chunk(B_master, DEPTH, dim=0)[i]
layer.bias.data.copy_(B)
A_shape = (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
dist.broadcast(A_master, src=0)
A = A_master.clone()
A.requires_grad = True
out = layer(A)
A_master = A_master.clone()
A_master.requires_grad = True
C_master = layer_master(A_master)
C = torch.chunk(C_master, DEPTH, dim=-1)[i]
check_equal(out, C)
print_rank_0('vocab parallel classifier (no given weight) forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
dist.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=-1)[i]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
A_grad = A_master.grad
check_equal(A_grad, A.grad)
W_grad = layer_master.weight.grad
W_grad = torch.chunk(W_grad, DEPTH, dim=0)[i]
check_equal(W_grad, layer.weight.grad)
B_grad = layer_master.bias.grad
B_grad = torch.chunk(B_grad, DEPTH, dim=0)[i]
check_equal(B_grad, layer.bias.grad)
print_rank_0('vocab parallel classifier (no given weight) backward: pass')
def check_classifier_given_embed_weight():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_1D)
embed = Embedding1D(VOCAB_SIZE, HIDDEN_SIZE)
embed = embed.to(dtype).to(device)
embed_master = torch.nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
embed_master = embed_master.to(dtype).to(device)
weight_master = embed_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, DEPTH, dim=-1)[i]
embed.weight.data.copy_(weight)
env.parallel_input_1d = False
layer = Classifier1D(HIDDEN_SIZE, NUM_CLASSES, weight=embed.weight, bias=False)
layer.to(dtype).to(device)
layer_master = VanillaClassifier(HIDDEN_SIZE, NUM_CLASSES, weight=embed_master.weight, bias=False)
layer_master = layer_master.to(dtype).to(device)
A_shape = (BATCH_SIZE, SEQ_LENGTH)
A_master = torch.randint(VOCAB_SIZE, A_shape, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = layer(embed(A))
A_master = A_master.clone()
C_master = layer_master(embed_master(A_master))
C = C_master.clone()
check_equal(out, C)
print_rank_0('classifier (given embed weight) forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
dist.broadcast(grad_master, src=0)
grad = grad_master.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
W_grad = embed_master.weight.grad
W_grad = torch.chunk(W_grad, DEPTH, dim=-1)[i]
check_equal(W_grad, embed.weight.grad)
print_rank_0('classifier (given embed weight) backward: pass')
def check_vocab_parallel_classifier_given_embed_weight():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_1D)
embed = VocabParallelEmbedding1D(VOCAB_SIZE, HIDDEN_SIZE)
embed = embed.to(dtype).to(device)
embed_master = torch.nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
embed_master = embed_master.to(dtype).to(device)
weight_master = embed_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, DEPTH, dim=0)[i]
embed.weight.data.copy_(weight)
env.parallel_input_1d = False
layer = VocabParallelClassifier1D(HIDDEN_SIZE, NUM_CLASSES, weight=embed.weight, bias=False)
layer.to(dtype).to(device)
layer_master = VanillaClassifier(HIDDEN_SIZE, NUM_CLASSES, weight=embed_master.weight, bias=False)
layer_master = layer_master.to(dtype).to(device)
A_shape = (BATCH_SIZE, SEQ_LENGTH)
A_master = torch.randint(VOCAB_SIZE, A_shape, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = layer(embed(A))
A_master = A_master.clone()
C_master = layer_master(embed_master(A_master))
C = torch.chunk(C_master, DEPTH, dim=-1)[i]
check_equal(out, C)
print_rank_0('vocab parallel classifier (given embed weight) forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
dist.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=-1)[i]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
W_grad = embed_master.weight.grad
W_grad = torch.chunk(W_grad, DEPTH, dim=0)[i]
check_equal(W_grad, embed.weight.grad)
print_rank_0('vocab parallel classifier (given embed weight) backward: pass')
def check_vocab_parallel_loss():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_1D)
criterion = VocabParallelCrossEntropyLoss1D()
criterion_master = torch.nn.CrossEntropyLoss()
out_shape = (BATCH_SIZE, SEQ_LENGTH, NUM_CLASSES)
out_master = torch.randn(out_shape, dtype=dtype, device=device)
target_master = torch.randint(NUM_CLASSES, (BATCH_SIZE, SEQ_LENGTH), dtype=torch.long, device=device)
torch.distributed.broadcast(out_master, src=0)
torch.distributed.broadcast(target_master, src=0)
out = torch.chunk(out_master, DEPTH, dim=-1)[i]
out = out.clone()
out.requires_grad = True
loss = criterion(out, target_master)
out_master = out_master.clone()
out_master.requires_grad = True
loss_master = criterion_master(out_master, target_master)
check_equal(loss, loss_master)
print_rank_0('vocab parallel loss forward: pass')
loss.backward()
loss_master.backward()
out_grad = out_master.grad
out_grad = torch.chunk(out_grad, DEPTH, dim=-1)[i]
check_equal(out_grad, out.grad)
print_rank_0('vocab parallel loss backward: pass')
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from functools import partial
import pytest
import torch
import torch.multiprocessing as mp
from colossalai.core import global_context as gpc
from colossalai.initialize import launch
from colossalai.logging import disable_existing_loggers
from colossalai.utils import free_port
from colossalai.testing import rerun_if_address_is_in_use
from checks_2d.check_layer_2d import (check_classifier_given_embed_weight, check_classifier_no_given_weight,
check_embed, check_layernorm, check_linear, check_loss, check_patch_embed,
check_vocab_parallel_classifier_given_embed_weight,
check_vocab_parallel_classifier_no_given_weight, check_vocab_parallel_embed,
check_vocab_parallel_loss)
from checks_2d.check_operation_2d import check_AB, check_ABT, check_ATB
CONFIG = dict(parallel=dict(pipeline=dict(size=1), tensor=dict(size=4, mode='2d')),)
def check_operations():
check_AB()
check_ABT()
check_ATB()
def check_layer():
check_linear()
check_layernorm()
check_embed()
check_patch_embed()
check_vocab_parallel_embed()
check_classifier_no_given_weight()
check_vocab_parallel_classifier_no_given_weight()
check_classifier_given_embed_weight()
check_vocab_parallel_classifier_given_embed_weight()
check_loss()
check_vocab_parallel_loss()
def check_layer_and_operation(rank, world_size, port):
disable_existing_loggers()
launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.backends.cudnn.deterministic = True
# check_operations()
check_layer()
gpc.destroy()
torch.cuda.empty_cache()
@pytest.mark.dist
@rerun_if_address_is_in_use()
def test_2d():
world_size = 4
run_func = partial(check_layer_and_operation, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_2d()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import torch
DEPTH = 2
BATCH_SIZE = 8
SEQ_LENGTH = 8
HIDDEN_SIZE = 8
NUM_CLASSES = 8
VOCAB_SIZE = 16
IMG_SIZE = 16
def check_equal(A, B):
assert torch.allclose(A, B, rtol=1e-3, atol=1e-2)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import torch
from colossalai.context.parallel_mode import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.nn.layer.parallel_2d._operation import Matmul_AB_2D, Matmul_ABT_2D, Matmul_ATB_2D
from colossalai.utils import get_current_device
from colossalai.utils import print_rank_0
from .common import check_equal, BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE, DEPTH
def check_AB():
data_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.DATA) else gpc.get_local_rank(ParallelMode.DATA)
pipeline_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_local_rank(
ParallelMode.PIPELINE)
pipeline_parallel_size = 1 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_world_size(
ParallelMode.PIPELINE)
tensor_parallel_size = gpc.get_world_size(ParallelMode.TENSOR)
dtype = torch.float
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
A_shape = (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=get_current_device())
torch.distributed.broadcast(A_master, src=0)
A = torch.chunk(A_master, DEPTH, dim=0)[i]
A = torch.chunk(A, DEPTH, dim=-1)[j]
A = A.clone()
A.requires_grad = True
B_shape = (HIDDEN_SIZE, 4 * HIDDEN_SIZE)
B_master = torch.randn(B_shape, dtype=dtype, device=get_current_device())
torch.distributed.broadcast(B_master, src=0)
B = torch.chunk(B_master, DEPTH, dim=0)[i]
B = torch.chunk(B, DEPTH, dim=-1)[j]
B = B.clone()
B.requires_grad = True
out_shape = (BATCH_SIZE // DEPTH, SEQ_LENGTH, 4 * HIDDEN_SIZE // DEPTH)
out = Matmul_AB_2D.apply(
A, B,
DEPTH,
out_shape,
i, j,
ParallelMode.PARALLEL_2D_ROW,
ParallelMode.PARALLEL_2D_COL,
data_parallel_rank,
pipeline_parallel_rank,
pipeline_parallel_size,
tensor_parallel_size
)
C_shape = (BATCH_SIZE, SEQ_LENGTH, 4 * HIDDEN_SIZE)
A_master = A_master.clone()
A_master.requires_grad = True
B_master = B_master.clone()
B_master.requires_grad = True
C_master = torch.matmul(A_master, B_master)
C = torch.chunk(C_master, DEPTH, dim=0)[i]
C = torch.chunk(C, DEPTH, dim=-1)[j]
# check forward correctness
check_equal(out, C)
print_rank_0('AB forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=get_current_device())
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=0)[i]
grad = torch.chunk(grad, DEPTH, dim=-1)[j]
out.backward(grad)
C_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, DEPTH, dim=0)[i]
A_grad = torch.chunk(A_grad, DEPTH, dim=-1)[j]
# check backward correctness
check_equal(A_grad, A.grad)
B_grad = B_master.grad
B_grad = torch.chunk(B_grad, DEPTH, dim=0)[i]
B_grad = torch.chunk(B_grad, DEPTH, dim=-1)[j]
# check backward correctness
check_equal(B_grad, B.grad)
print_rank_0('AB backward: pass')
def check_ABT():
data_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.DATA) else gpc.get_local_rank(ParallelMode.DATA)
pipeline_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_local_rank(
ParallelMode.PIPELINE)
pipeline_parallel_size = 1 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_world_size(
ParallelMode.PIPELINE)
tensor_parallel_size = gpc.get_world_size(ParallelMode.TENSOR)
dtype = torch.float
device = get_current_device()
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
C_shape = (BATCH_SIZE, SEQ_LENGTH, 4 * HIDDEN_SIZE)
C_master = torch.randn(C_shape, dtype=dtype, device=device)
torch.distributed.broadcast(C_master, src=0)
C = torch.chunk(C_master, DEPTH, dim=0)[i]
C = torch.chunk(C, DEPTH, dim=-1)[j]
C = C.clone()
C.requires_grad = True
B_shape = (HIDDEN_SIZE, 4 * HIDDEN_SIZE)
B_master = torch.randn(B_shape, dtype=dtype, device=device)
torch.distributed.broadcast(B_master, src=0)
B = torch.chunk(B_master, DEPTH, dim=0)[i]
B = torch.chunk(B, DEPTH, dim=-1)[j]
B = B.clone()
B.requires_grad = True
out = Matmul_ABT_2D.apply(
C, B,
DEPTH, (BATCH_SIZE // DEPTH, SEQ_LENGTH, HIDDEN_SIZE // DEPTH),
i, j,
ParallelMode.PARALLEL_2D_ROW,
ParallelMode.PARALLEL_2D_COL,
data_parallel_rank,
pipeline_parallel_rank,
pipeline_parallel_size,
tensor_parallel_size
)
A_shape = (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE)
C_master = C_master.clone()
C_master.requires_grad = True
B_master = B_master.clone()
B_master.requires_grad = True
A_master = torch.matmul(C_master, B_master.transpose(0, 1))
A = torch.chunk(A_master, DEPTH, dim=0)[i]
A = torch.chunk(A, DEPTH, dim=-1)[j]
check_equal(out, A)
print_rank_0('ABT forward: pass')
grad_shape = A_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=0)[i]
grad = torch.chunk(grad, DEPTH, dim=-1)[j]
# backward
out.backward(grad)
A_master.backward(grad_master)
C_grad = C_master.grad
C_grad = torch.chunk(C_grad, DEPTH, dim=0)[i]
C_grad = torch.chunk(C_grad, DEPTH, dim=-1)[j]
check_equal(C_grad, C.grad)
B_grad = B_master.grad
B_grad = torch.chunk(B_grad, DEPTH, dim=0)[i]
B_grad = torch.chunk(B_grad, DEPTH, dim=-1)[j]
check_equal(B_grad, B.grad)
print_rank_0('ABT backward: pass')
def check_ATB():
data_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.DATA) else gpc.get_local_rank(ParallelMode.DATA)
pipeline_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_local_rank(
ParallelMode.PIPELINE)
pipeline_parallel_size = 1 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_world_size(
ParallelMode.PIPELINE)
tensor_parallel_size = gpc.get_world_size(ParallelMode.TENSOR)
device = get_current_device()
dtype = torch.float
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
A_shape = (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
torch.distributed.broadcast(A_master, src=0)
A = torch.chunk(A_master, DEPTH, dim=0)[i]
A = torch.chunk(A, DEPTH, dim=-1)[j]
A = A.clone()
A.requires_grad = True
C_shape = (BATCH_SIZE, SEQ_LENGTH, 4 * HIDDEN_SIZE)
C_master = torch.randn(C_shape, dtype=dtype, device=device)
torch.distributed.broadcast(C_master, src=0)
C = torch.chunk(C_master, DEPTH, dim=0)[i]
C = torch.chunk(C, DEPTH, dim=-1)[j]
C = C.clone()
C.requires_grad = True
out = Matmul_ATB_2D.apply(
A, C,
DEPTH, (HIDDEN_SIZE // DEPTH, 4 * HIDDEN_SIZE // DEPTH),
i, j,
ParallelMode.PARALLEL_2D_ROW,
ParallelMode.PARALLEL_2D_COL,
data_parallel_rank,
pipeline_parallel_rank,
pipeline_parallel_size,
tensor_parallel_size
)
B_shape = (HIDDEN_SIZE, 4 * HIDDEN_SIZE)
A_master = A_master.clone()
A_master.requires_grad = True
C_master = C_master.clone()
C_master.requires_grad = True
B_master = torch.matmul(
A_master.view(-1, A_master.shape[-1]).transpose(0, 1),
C_master.view(-1, C_master.shape[-1]))
B = torch.chunk(B_master, DEPTH, dim=0)[i]
B = torch.chunk(B, DEPTH, dim=-1)[j]
check_equal(out, B)
print_rank_0('ATB forward: pass')
grad_shape = B_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=0)[i]
grad = torch.chunk(grad, DEPTH, dim=-1)[j]
out.backward(grad)
B_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, DEPTH, dim=0)[i]
A_grad = torch.chunk(A_grad, DEPTH, dim=-1)[j]
check_equal(A_grad, A.grad)
C_grad = C_master.grad
C_grad = torch.chunk(C_grad, DEPTH, dim=0)[i]
C_grad = torch.chunk(C_grad, DEPTH, dim=-1)[j]
check_equal(C_grad, C.grad)
print_rank_0('ATB backward: pass')
|
import torch
from colossalai.context.parallel_mode import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.nn import (Classifier2D, CrossEntropyLoss2D, Embedding2D, LayerNorm2D, Linear2D, PatchEmbedding2D,
VanillaClassifier, VanillaPatchEmbedding, VocabParallelClassifier2D,
VocabParallelCrossEntropyLoss2D, VocabParallelEmbedding2D)
from colossalai.utils import get_current_device, print_rank_0
from .common import (BATCH_SIZE, DEPTH, HIDDEN_SIZE, IMG_SIZE, NUM_CLASSES, SEQ_LENGTH, VOCAB_SIZE, check_equal)
def check_linear():
device = get_current_device()
dtype = torch.float32
INPUT_SIZE = HIDDEN_SIZE
OUTPUT_SIZE = HIDDEN_SIZE
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
layer = Linear2D(INPUT_SIZE, OUTPUT_SIZE)
A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
torch.distributed.broadcast(A_master, src=0)
A = torch.chunk(A_master, DEPTH, dim=0)[i]
A = torch.chunk(A, DEPTH, dim=-1)[j]
A = A.clone()
A.requires_grad = True
W_shape = (INPUT_SIZE, OUTPUT_SIZE)
W_master = torch.randn(W_shape, dtype=dtype, device=device)
torch.distributed.broadcast(W_master, src=0)
W = torch.chunk(W_master, DEPTH, dim=0)[i]
W = torch.chunk(W, DEPTH, dim=-1)[j]
W = W.clone()
W.requires_grad = True
B_shape = (OUTPUT_SIZE)
B_master = torch.randn(B_shape, dtype=dtype, device=device)
torch.distributed.broadcast(B_master, src=0)
B = torch.chunk(B_master, DEPTH, dim=-1)[j]
B = torch.chunk(B, DEPTH, dim=-1)[i]
B = B.clone()
B.requires_grad = True
layer.weight.data.copy_(W)
layer.bias.data.copy_(B)
out = layer(A)
A_master = A_master.clone()
A_master.requires_grad = True
W_master = W_master.clone()
W_master.requires_grad = True
B_master = B_master.clone()
B_master.requires_grad = True
C_master = torch.matmul(A_master, W_master) + B_master
C = torch.chunk(C_master, DEPTH, dim=0)[i]
C = torch.chunk(C, DEPTH, dim=-1)[j]
check_equal(out, C)
print_rank_0('linear forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=get_current_device())
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=0)[i]
grad = torch.chunk(grad, DEPTH, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, DEPTH, dim=0)[i]
A_grad = torch.chunk(A_grad, DEPTH, dim=-1)[j]
check_equal(A_grad, A.grad)
W_grad = W_master.grad
W_grad = torch.chunk(W_grad, DEPTH, dim=0)[i]
W_grad = torch.chunk(W_grad, DEPTH, dim=-1)[j]
check_equal(W_grad, layer.weight.grad)
B_grad = B_master.grad
B_grad = torch.chunk(B_grad, DEPTH, dim=-1)[j]
B_grad = torch.chunk(B_grad, DEPTH, dim=-1)[i]
# if i == 0:
check_equal(B_grad, layer.bias.grad)
print_rank_0('linear backward: pass')
def check_layernorm():
device = get_current_device()
dtype = torch.float32
INPUT_SIZE = HIDDEN_SIZE
EPS = 1e-12
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
layernorm = LayerNorm2D(INPUT_SIZE)
A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
torch.distributed.broadcast(A_master, src=0)
A = torch.chunk(A_master, DEPTH, dim=0)[i]
A = torch.chunk(A, DEPTH, dim=-1)[j]
A = A.clone()
A.requires_grad = True
out = layernorm(A)
A_master = A_master.clone()
A_master.requires_grad = True
E_master = torch.sum(A_master, dim=-1, keepdim=True)
E_master /= INPUT_SIZE
V_master = torch.sum(A_master * A_master, dim=-1, keepdim=True)
V_master /= INPUT_SIZE
V_master = V_master - E_master * E_master
V_master = 1.0 / torch.sqrt(V_master + EPS)
C_master = (A_master - E_master) * V_master
C = torch.chunk(C_master, DEPTH, dim=0)[i]
C = torch.chunk(C, DEPTH, dim=-1)[j]
check_equal(out, C)
print_rank_0('layer norm forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=get_current_device())
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=0)[i]
grad = torch.chunk(grad, DEPTH, dim=-1)[j]
out.backward(grad)
C_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, DEPTH, dim=0)[i]
A_grad = torch.chunk(A_grad, DEPTH, dim=-1)[j]
check_equal(A_grad, A.grad)
print_rank_0('layer norm backward: pass')
def check_embed():
device = get_current_device()
dtype = torch.float32
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
embed = Embedding2D(VOCAB_SIZE, HIDDEN_SIZE)
embed = embed.to(dtype).to(device)
embed_master = torch.nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
embed_master = embed_master.to(dtype).to(device)
weight_master = embed_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, DEPTH, dim=-1)[j]
weight = torch.chunk(weight, DEPTH, dim=-1)[i]
embed.weight.data.copy_(weight)
A_shape = (BATCH_SIZE, SEQ_LENGTH)
A_master = torch.randint(VOCAB_SIZE, A_shape, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = embed(A)
A_master = A_master.clone()
C_master = embed_master(A_master)
C = torch.chunk(C_master, DEPTH, dim=0)[i]
C = torch.chunk(C, DEPTH, dim=-1)[j]
check_equal(out, C)
print_rank_0('embed forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=0)[i]
grad = torch.chunk(grad, DEPTH, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
B_grad = embed_master.weight.grad
B_grad = torch.chunk(B_grad, DEPTH, dim=-1)[j]
B_grad = torch.chunk(B_grad, DEPTH, dim=-1)[i]
check_equal(B_grad, embed.weight.grad)
print_rank_0('embed backward: pass')
def check_patch_embed():
device = get_current_device()
dtype = torch.float32
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
layer = PatchEmbedding2D(IMG_SIZE, 4, 3, HIDDEN_SIZE, dtype=dtype)
torch.nn.init.ones_(layer.cls_token)
torch.nn.init.ones_(layer.pos_embed)
layer = layer.to(device)
layer_master = VanillaPatchEmbedding(IMG_SIZE, 4, 3, HIDDEN_SIZE, dtype=dtype)
torch.nn.init.ones_(layer_master.cls_token)
torch.nn.init.ones_(layer_master.pos_embed)
layer_master = layer_master.to(device)
proj_weight_master = layer_master.weight.data
torch.distributed.broadcast(proj_weight_master, src=0)
proj_weight = torch.chunk(proj_weight_master, DEPTH, dim=0)[j]
proj_weight = torch.chunk(proj_weight, DEPTH, dim=0)[i]
layer.weight.data.copy_(proj_weight)
proj_bias_master = layer_master.bias.data
torch.distributed.broadcast(proj_bias_master, src=0)
proj_bias = torch.chunk(proj_bias_master, DEPTH, dim=0)[j]
proj_bias = torch.chunk(proj_bias, DEPTH, dim=0)[i]
layer.bias.data.copy_(proj_bias)
A_shape = (BATCH_SIZE, 3, IMG_SIZE, IMG_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = layer(A)
A_master = A_master.clone()
C_master = layer_master(A_master)
C = torch.chunk(C_master, DEPTH, dim=0)[i]
C = torch.chunk(C, DEPTH, dim=-1)[j]
check_equal(out, C)
print_rank_0('patch embed forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=0)[i]
grad = torch.chunk(grad, DEPTH, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
cls_grad_master = layer_master.cls_token.grad
cls_grad = torch.chunk(cls_grad_master, DEPTH, dim=-1)[j]
cls_grad = torch.chunk(cls_grad, DEPTH, dim=-1)[i]
check_equal(cls_grad, layer.cls_token.grad)
pos_grad_master = layer_master.pos_embed.grad
pos_grad = torch.chunk(pos_grad_master, DEPTH, dim=-1)[j]
pos_grad = torch.chunk(pos_grad, DEPTH, dim=-1)[i]
check_equal(pos_grad, layer.pos_embed.grad)
B_grad = layer_master.weight.grad
B_grad = torch.chunk(B_grad, DEPTH, dim=0)[j]
B_grad = torch.chunk(B_grad, DEPTH, dim=0)[i]
check_equal(B_grad, layer.weight.grad)
bias_grad = layer_master.bias.grad
bias_grad = torch.chunk(bias_grad, DEPTH)[j]
bias_grad = torch.chunk(bias_grad, DEPTH)[i]
check_equal(bias_grad, layer.bias.grad)
print_rank_0('patch embed backward: pass')
def check_vocab_parallel_embed():
device = get_current_device()
dtype = torch.float32
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
embed = VocabParallelEmbedding2D(VOCAB_SIZE, HIDDEN_SIZE)
embed = embed.to(dtype).to(device)
embed_master = torch.nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
embed_master = embed_master.to(dtype).to(device)
weight_master = embed_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, DEPTH, dim=-1)[j]
weight = torch.chunk(weight, DEPTH, dim=0)[i]
embed.weight.data.copy_(weight)
A_shape = (BATCH_SIZE, SEQ_LENGTH)
A_master = torch.randint(VOCAB_SIZE, A_shape, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = embed(A)
A_master = A_master.clone()
C_master = embed_master(A_master)
C = torch.chunk(C_master, DEPTH, dim=0)[i]
C = torch.chunk(C, DEPTH, dim=-1)[j]
check_equal(out, C)
print_rank_0('vocab parallel embed forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=0)[i]
grad = torch.chunk(grad, DEPTH, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
B_grad = embed_master.weight.grad
B_grad = torch.chunk(B_grad, DEPTH, dim=-1)[j]
B_grad = torch.chunk(B_grad, DEPTH, dim=0)[i]
check_equal(B_grad, embed.weight.grad)
print_rank_0('vocab parallel embed backward: pass')
def check_classifier_no_given_weight():
device = get_current_device()
dtype = torch.float32
INPUT_SIZE = HIDDEN_SIZE
OUTPUT_SIZE = NUM_CLASSES
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
layer = Classifier2D(INPUT_SIZE, OUTPUT_SIZE)
A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
A_master = torch.randint(5, A_shape, dtype=dtype, device=device)
torch.distributed.broadcast(A_master, src=0)
A = torch.chunk(A_master, DEPTH, dim=0)[i]
A = torch.chunk(A, DEPTH, dim=-1)[j]
A = A.clone()
A.requires_grad = True
W_shape = (OUTPUT_SIZE, INPUT_SIZE)
W_master = torch.randint(5, W_shape, dtype=dtype, device=device)
torch.distributed.broadcast(W_master, src=0)
W = torch.chunk(W_master, DEPTH, dim=-1)[j]
W = torch.chunk(W, DEPTH, dim=-1)[i]
W = W.clone()
layer.weight.data.copy_(W)
# W.requires_grad = True
B_shape = (OUTPUT_SIZE, )
B_master = torch.randint(5, B_shape, dtype=dtype, device=device)
torch.distributed.broadcast(B_master, src=0)
# B = torch.chunk(B_master, DEPTH, dim=0)[j]
B = B_master.clone()
layer.bias.data.copy_(B)
out = layer(A)
A_master = A_master.clone()
A_master.requires_grad = True
W_master = W_master.clone()
W_master.requires_grad = True
B_master = B_master.clone()
B_master.requires_grad = True
C_master = torch.matmul(A_master, W_master.transpose(0, 1)) + B_master
C = torch.chunk(C_master, DEPTH, dim=0)[i]
# C = torch.chunk(C, DEPTH, dim=-1)[j]
check_equal(out, C)
print_rank_0('classifier (no given weight) forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=get_current_device())
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=0)[i]
# grad = torch.chunk(grad, DEPTH, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, DEPTH, dim=0)[i]
A_grad = torch.chunk(A_grad, DEPTH, dim=-1)[j]
check_equal(A_grad, A.grad)
W_grad = W_master.grad
W_grad = torch.chunk(W_grad, DEPTH, dim=-1)[j]
W_grad = torch.chunk(W_grad, DEPTH, dim=-1)[i]
check_equal(W_grad, layer.weight.grad)
B_grad = B_master.grad
# B_grad = torch.chunk(B_grad, DEPTH, dim=0)[j]
# if i == 0:
check_equal(B_grad, layer.bias.grad)
print_rank_0('classifier (no given weight) backward: pass')
def check_vocab_parallel_classifier_no_given_weight():
device = get_current_device()
dtype = torch.float32
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
layer = VocabParallelClassifier2D(HIDDEN_SIZE, VOCAB_SIZE, bias=True)
layer = layer.to(dtype).to(device)
layer_master = VanillaClassifier(HIDDEN_SIZE, VOCAB_SIZE, bias=True)
layer_master = layer_master.to(dtype).to(device)
weight_master = layer_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, DEPTH, dim=0)[i]
weight = torch.chunk(weight, DEPTH, dim=-1)[j]
layer.weight.data.copy_(weight)
bias_master = layer_master.bias.data
torch.distributed.broadcast(bias_master, src=0)
bias = torch.chunk(bias_master, DEPTH)[j]
bias = torch.chunk(bias, DEPTH)[i]
layer.bias.data.copy_(bias)
A_shape = (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
torch.distributed.broadcast(A_master, src=0)
A = torch.chunk(A_master, DEPTH, dim=0)[i]
A = torch.chunk(A, DEPTH, dim=-1)[j]
A = A.clone()
A.requires_grad = True
out = layer(A)
A_master = A_master.clone()
A_master.requires_grad = True
C_master = layer_master(A_master)
C = torch.chunk(C_master, DEPTH, dim=0)[i]
C = torch.chunk(C, DEPTH, dim=-1)[j]
check_equal(out, C)
print_rank_0('vocab parallel classifier (no given weight) forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=0)[i]
grad = torch.chunk(grad, DEPTH, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, DEPTH, dim=0)[i]
A_grad = torch.chunk(A_grad, DEPTH, dim=-1)[j]
check_equal(A_grad, A.grad)
W_grad = layer_master.weight.grad
W_grad = torch.chunk(W_grad, DEPTH, dim=0)[i]
W_grad = torch.chunk(W_grad, DEPTH, dim=-1)[j]
check_equal(W_grad, layer.weight.grad)
B_grad = layer_master.bias.grad
B_grad = torch.chunk(B_grad, DEPTH)[j]
B_grad = torch.chunk(B_grad, DEPTH)[i]
check_equal(B_grad, layer.bias.grad)
print_rank_0('vocab parallel classifier (no given weight) backward: pass')
def check_classifier_given_embed_weight():
device = get_current_device()
dtype = torch.float32
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
embed = Embedding2D(VOCAB_SIZE, HIDDEN_SIZE)
embed = embed.to(dtype).to(device)
embed_master = torch.nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
embed_master = embed_master.to(dtype).to(device)
weight_master = embed_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, DEPTH, dim=-1)[j]
weight = torch.chunk(weight, DEPTH, dim=-1)[i]
embed.weight.data.copy_(weight)
layer = Classifier2D(HIDDEN_SIZE, VOCAB_SIZE, weight=embed.weight, bias=False)
layer = layer.to(dtype).to(device)
layer_master = VanillaClassifier(HIDDEN_SIZE, VOCAB_SIZE, weight=embed_master.weight, bias=False)
layer_master = layer_master.to(dtype).to(device)
A_shape = (BATCH_SIZE, SEQ_LENGTH)
A_master = torch.randint(VOCAB_SIZE, A_shape, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = layer(embed(A))
A_master = A_master.clone()
C_master = layer_master(embed_master(A_master))
C = torch.chunk(C_master, DEPTH, dim=0)[i]
check_equal(out, C)
print_rank_0('classifier (given embed weight) forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=0)[i]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
W_grad = embed_master.weight.grad
W_grad = torch.chunk(W_grad, DEPTH, dim=-1)[j]
W_grad = torch.chunk(W_grad, DEPTH, dim=-1)[i]
check_equal(W_grad, embed.weight.grad)
print_rank_0('classifier (given embed weight) backward: pass')
def check_vocab_parallel_classifier_given_embed_weight():
device = get_current_device()
dtype = torch.float32
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
embed = VocabParallelEmbedding2D(VOCAB_SIZE, HIDDEN_SIZE)
embed = embed.to(dtype).to(device)
embed_master = torch.nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
embed_master = embed_master.to(dtype).to(device)
weight_master = embed_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, DEPTH, dim=-1)[j]
weight = torch.chunk(weight, DEPTH, dim=0)[i]
embed.weight.data.copy_(weight)
layer = VocabParallelClassifier2D(HIDDEN_SIZE, VOCAB_SIZE, weight=embed.weight, bias=False)
layer = layer.to(dtype).to(device)
layer_master = VanillaClassifier(HIDDEN_SIZE, VOCAB_SIZE, weight=embed_master.weight, bias=False)
layer_master = layer_master.to(dtype).to(device)
A_shape = (BATCH_SIZE, SEQ_LENGTH)
A_master = torch.randint(VOCAB_SIZE, A_shape, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = layer(embed(A))
A_master = A_master.clone()
C_master = layer_master(embed_master(A_master))
C = torch.chunk(C_master, DEPTH, dim=0)[i]
C = torch.chunk(C, DEPTH, dim=-1)[j]
check_equal(out, C)
print_rank_0('vocab parallel classifier (given embed weight) forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, DEPTH, dim=0)[i]
grad = torch.chunk(grad, DEPTH, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
W_grad = embed_master.weight.grad
W_grad = torch.chunk(W_grad, DEPTH, dim=-1)[j]
W_grad = torch.chunk(W_grad, DEPTH, dim=0)[i]
check_equal(W_grad, embed.weight.grad)
print_rank_0('vocab parallel classifier (given embed weight) backward: pass')
def check_loss():
device = get_current_device()
dtype = torch.float32
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
criterion = CrossEntropyLoss2D()
criterion_master = torch.nn.CrossEntropyLoss()
out_shape = (BATCH_SIZE, NUM_CLASSES)
out_master = torch.randn(out_shape, dtype=dtype, device=device)
target_master = torch.randint(NUM_CLASSES, (BATCH_SIZE, ), dtype=torch.long, device=device)
torch.distributed.broadcast(out_master, src=0)
torch.distributed.broadcast(target_master, src=0)
out = torch.chunk(out_master, DEPTH, dim=0)[i]
out = out.clone()
out.requires_grad = True
loss = criterion(out, target_master)
out_master = out_master.clone()
out_master.requires_grad = True
loss_master = criterion_master(out_master, target_master)
check_equal(loss, loss_master)
print_rank_0('cross entropy loss forward: pass')
loss.backward()
loss_master.backward()
out_grad = out_master.grad
out_grad = torch.chunk(out_grad, DEPTH, dim=0)[i]
check_equal(out_grad, out.grad)
print_rank_0('cross entropy loss backward: pass')
def check_vocab_parallel_loss():
device = get_current_device()
dtype = torch.float32
j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
criterion = VocabParallelCrossEntropyLoss2D()
criterion_master = torch.nn.CrossEntropyLoss()
out_shape = (BATCH_SIZE, NUM_CLASSES)
out_master = torch.randn(out_shape, dtype=dtype, device=device)
target_master = torch.randint(NUM_CLASSES, (BATCH_SIZE, ), dtype=torch.long, device=device)
torch.distributed.broadcast(out_master, src=0)
torch.distributed.broadcast(target_master, src=0)
out = torch.chunk(out_master, DEPTH, dim=0)[i]
out = torch.chunk(out, DEPTH, dim=-1)[j]
out = out.clone()
out.requires_grad = True
loss = criterion(out, target_master)
out_master = out_master.clone()
out_master.requires_grad = True
loss_master = criterion_master(out_master, target_master)
check_equal(loss, loss_master)
print_rank_0('vocab parallel cross entropy loss forward: pass')
loss.backward()
loss_master.backward()
out_grad = out_master.grad
out_grad = torch.chunk(out_grad, DEPTH, dim=0)[i]
out_grad = torch.chunk(out_grad, DEPTH, dim=-1)[j]
check_equal(out_grad, out.grad)
print_rank_0('vocab parallel cross entropy loss backward: pass')
# def check_attention():
# device = get_current_device()
# dtype = torch.float32
# INPUT_SIZE = HIDDEN_SIZE
# NUM_ATTENTION_HEADS = 2
# j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
# i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
# layer = TransformerSelfAttention2D(
# HIDDEN_SIZE,
# NUM_ATTENTION_HEADS,
# attention_dropout_prob=0.5,
# hidden_dropout_prob=0.5,
# )
# A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
# A_master = torch.randn(A_shape, dtype=dtype, device=device)
# torch.distributed.broadcast(A_master, src=0)
# A = torch.chunk(A_master, DEPTH, dim=0)[i]
# A = torch.chunk(A, DEPTH, dim=-1)[j]
# A = A.clone()
# A.requires_grad = True
# mask_shape = (BATCH_SIZE // DEPTH, NUM_ATTENTION_HEADS // DEPTH, SEQ_LENGTH, SEQ_LENGTH)
# attention_mask = torch.zeros(mask_shape, dtype=dtype, device=device)
# out = layer(A, attention_mask)
# assert out.shape == (BATCH_SIZE // DEPTH, SEQ_LENGTH, INPUT_SIZE // DEPTH)
# print_rank_0('self attention forward: pass')
# grad_shape = out.shape
# grad = torch.randn(grad_shape, dtype=dtype, device=device)
# out.backward(grad)
# assert A.grad.shape == A.shape
# print_rank_0('self attention backward: pass')
# def check_mlp():
# device = get_current_device()
# dtype = torch.float32
# INPUT_SIZE = HIDDEN_SIZE
# j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
# i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
# layer = TransformerMLP2D(
# HIDDEN_SIZE,
# dropout_prob=0.5,
# act_func='gelu',
# )
# A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
# A_master = torch.randn(A_shape, dtype=dtype, device=device)
# torch.distributed.broadcast(A_master, src=0)
# A = torch.chunk(A_master, DEPTH, dim=0)[i]
# A = torch.chunk(A, DEPTH, dim=-1)[j]
# A = A.clone()
# A.requires_grad = True
# out = layer(A)
# assert out.shape == (BATCH_SIZE // DEPTH, SEQ_LENGTH, INPUT_SIZE // DEPTH)
# print_rank_0('mlp forward: pass')
# grad_shape = out.shape
# grad = torch.randn(grad_shape, dtype=dtype, device=device)
# out.backward(grad)
# assert A.grad.shape == A.shape
# print_rank_0('mlp backward: pass')
# def check_transformerlayer():
# device = get_current_device()
# dtype = torch.float32
# INPUT_SIZE = HIDDEN_SIZE
# NUM_ATTENTION_HEADS = 2
# j = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)
# i = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)
# layer = TransformerLayer2D(HIDDEN_SIZE,
# NUM_ATTENTION_HEADS,
# act_func='gelu',
# attention_dropout_prob=0.5,
# hidden_dropout_prob=0.5)
# A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
# A_master = torch.randn(A_shape, dtype=dtype, device=device)
# torch.distributed.broadcast(A_master, src=0)
# A = torch.chunk(A_master, DEPTH, dim=0)[i]
# A = torch.chunk(A, DEPTH, dim=-1)[j]
# A = A.clone()
# A.requires_grad = True
# mask_shape = (BATCH_SIZE // DEPTH, NUM_ATTENTION_HEADS // DEPTH, SEQ_LENGTH, SEQ_LENGTH)
# attention_mask = torch.zeros(mask_shape, dtype=dtype, device=device)
# out = layer(A, attention_mask)
# assert out.shape == (BATCH_SIZE // DEPTH, SEQ_LENGTH, INPUT_SIZE // DEPTH)
# print_rank_0('transformerlayer forward: pass')
# grad_shape = out.shape
# grad = torch.randn(grad_shape, dtype=dtype, device=device)
# out.backward(grad)
# assert A.grad.shape == A.shape
# print_rank_0('transformerlayer backward: pass')
|
import colossalai
import colossalai.nn as col_nn
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import pytest
from colossalai.core import global_context as gpc
from colossalai.context import ParallelMode
from colossalai.testing import rerun_if_address_is_in_use
from functools import partial
CONFIG = dict(parallel=dict(tensor=dict(size=4, mode='sequence')))
def check_ring_qk(rank, world_size):
# params
batch_size = 4
num_heads = 4
seq_length = 32
attention_head_size = 32
sub_seq_length = seq_length // world_size
# create master tensors
q = torch.rand(batch_size * num_heads, seq_length, attention_head_size).cuda()
k = torch.rand(batch_size * num_heads, seq_length, attention_head_size).cuda()
dist.broadcast(q, src=0, group=gpc.get_group(ParallelMode.SEQUENCE))
dist.broadcast(k, src=0, group=gpc.get_group(ParallelMode.SEQUENCE))
# create distributed tensors
sub_q = q.clone()[:, rank * sub_seq_length:(rank + 1) * sub_seq_length].contiguous()
sub_k = k.clone()[:, rank * sub_seq_length:(rank + 1) * sub_seq_length].contiguous()
# set autograd attributes
q.requires_grad = True
k.requires_grad = True
q.retain_grad()
k.retain_grad()
sub_q.requires_grad = True
sub_k.requires_grad = True
sub_q.retain_grad()
sub_k.retain_grad()
# compute master attention scores
a = torch.matmul(q, k.transpose(2, 1))
# compute distributed attention scores
ring_qk = colossalai.nn.layer.parallel_sequence.RingQK.apply
sub_a = ring_qk(sub_q, sub_k, batch_size, num_heads, sub_seq_length)
# check master and distributed attetion scores
sub_master_a = a[:, rank * sub_seq_length:(rank + 1) * sub_seq_length]
assert torch.allclose(sub_a, sub_master_a, rtol=1e-5, atol=1e-2)
# run master backward
a.retain_grad()
a.mean().backward()
# run distributed backward
partial_master_a_grad = a.grad[:, rank * sub_seq_length:(rank + 1) * sub_seq_length]
torch.autograd.backward(sub_a, partial_master_a_grad)
# check master and distributed grads
partial_master_q_grad = q.grad[:, rank * sub_seq_length:(rank + 1) * sub_seq_length]
assert torch.allclose(sub_q.grad, partial_master_q_grad, rtol=1e-5, atol=1e-2), \
'attention score cannot match'
def check_ring_av(rank, world_size):
# params
batch_size = 4
num_heads = 4
seq_length = 16
attention_head_size = 32
sub_seq_length = seq_length // world_size
# create master tensors
a = torch.rand(batch_size * num_heads, seq_length, seq_length).cuda()
v = torch.rand(batch_size * num_heads, seq_length, attention_head_size).cuda()
dist.broadcast(a, src=0, group=gpc.get_group(ParallelMode.SEQUENCE))
dist.broadcast(v, src=0, group=gpc.get_group(ParallelMode.SEQUENCE))
# create distributed tensors
sub_a = a.clone()[:, rank * sub_seq_length:(rank + 1) * sub_seq_length].contiguous()
sub_v = v.clone()[:, rank * sub_seq_length:(rank + 1) * sub_seq_length].contiguous()
# set autograd attributes
a.requires_grad = True
v.requires_grad = True
a.retain_grad()
v.retain_grad()
sub_a.requires_grad = True
sub_v.requires_grad = True
sub_a.retain_grad()
sub_v.retain_grad()
# compute master attention scores
out = torch.matmul(a, v)
# compute distributed attention scores
ring_av = colossalai.nn.layer.parallel_sequence.RingAV.apply
sub_out = ring_av(sub_a, sub_v, batch_size, num_heads, attention_head_size, sub_seq_length)
# print(f'master output shape: {out.shape}, partial output shape: {sub_out.shape}')
# check master and distributed output
sub_master_out = out[:, rank * sub_seq_length:(rank + 1) * sub_seq_length]
assert torch.allclose(sub_out, sub_master_out, rtol=1e-5, atol=1e-2)
# # run master backward
out.retain_grad()
out.mean().backward()
# # run distributed backward
partial_master_out_grad = out.grad[:, rank * sub_seq_length:(rank + 1) * sub_seq_length]
torch.autograd.backward(sub_out, partial_master_out_grad)
# # check master and distributed grads
partial_master_a_grad = a.grad[:, rank * sub_seq_length:(rank + 1) * sub_seq_length]
assert torch.allclose(sub_a.grad, partial_master_a_grad, rtol=1e-5, atol=1e-2), \
'attention output cannot match'
def run_test(rank, world_size):
colossalai.launch(rank=rank, world_size=world_size, config=CONFIG, host='localhost', port=29500)
# check_ring_qk(rank, world_size)
check_ring_av(rank, world_size)
gpc.destroy()
torch.cuda.empty_cache()
@pytest.mark.dist
@rerun_if_address_is_in_use()
def test_sequence():
world_size = 4
run_func = partial(run_test, world_size=world_size)
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_sequence()
|
import torch
from colossalai.context import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.nn import TransformerSelfAttentionRing
from colossalai.utils import get_current_device
def check_selfattention():
WORLD_SIZE = gpc.get_world_size(ParallelMode.SEQUENCE)
SUB_SEQ_LENGTH = 8
BATCH = 4
HIDDEN_SIZE = 16
layer = TransformerSelfAttentionRing(
16,
8,
8,
0.1
)
layer = layer.to(get_current_device())
hidden_states = torch.rand(SUB_SEQ_LENGTH, BATCH, HIDDEN_SIZE).to(get_current_device())
attention_mask = torch.randint(low=0, high=2, size=(BATCH, 1, 1, 1, SUB_SEQ_LENGTH * WORLD_SIZE)).to(
get_current_device())
out = layer(hidden_states, attention_mask)
|
from functools import partial
import pytest
import torch
import torch.multiprocessing as mp
from colossalai.core import global_context as gpc
from colossalai.initialize import launch
from colossalai.logging import disable_existing_loggers
from colossalai.utils import free_port
from colossalai.testing import rerun_if_address_is_in_use
from checks_2p5d.check_layer_2p5d import *
from checks_2p5d.check_operation_2p5d import check_AB, check_ABT, check_ATB
CONFIG = dict(parallel=dict(
pipeline=dict(size=1),
tensor=dict(size=4, mode='2.5d', depth=1),
),)
def check_operations():
check_AB()
check_ABT()
check_ATB()
def check_layer():
check_linear()
check_layernorm()
check_embed()
check_patch_embed()
check_vocab_parallel_embed()
check_classifier_no_given_weight()
check_vocab_parallel_classifier_no_given_weight()
check_classifier_given_embed_weight()
check_vocab_parallel_classifier_given_embed_weight()
check_loss()
check_vocab_parallel_loss()
def check_layer_and_operation(rank, world_size, port):
disable_existing_loggers()
launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.backends.cudnn.deterministic = True
check_operations()
check_layer()
gpc.destroy()
torch.cuda.empty_cache()
@pytest.mark.dist
@rerun_if_address_is_in_use()
def test_2p5d():
world_size = 4
run_func = partial(check_layer_and_operation, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_2p5d()
|
import torch
from colossalai.context.parallel_mode import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.nn import (Classifier2p5D, CrossEntropyLoss2p5D, Embedding2p5D, LayerNorm2p5D, Linear2p5D,
PatchEmbedding2p5D, VanillaClassifier, VanillaPatchEmbedding, VocabParallelClassifier2p5D,
VocabParallelCrossEntropyLoss2p5D, VocabParallelEmbedding2p5D)
from colossalai.utils import get_current_device, print_rank_0
from torch.nn import Parameter
from .common import *
def check_linear():
device = get_current_device()
dtype = torch.float32
INPUT_SIZE = HIDDEN_SIZE
OUTPUT_SIZE = 2 * HIDDEN_SIZE
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
layer = Linear2p5D(INPUT_SIZE, OUTPUT_SIZE, dtype=dtype, skip_bias_add=False)
A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
torch.distributed.broadcast(A_master, src=0)
A = torch.chunk(A_master, TESSERACT_DIM, dim=0)[i]
A = torch.chunk(A, TESSERACT_DIM, dim=-1)[j]
A = A.clone()
A.requires_grad = True
W_shape = (INPUT_SIZE, OUTPUT_SIZE)
W_master = torch.randn(W_shape, dtype=dtype, device=device)
torch.distributed.broadcast(W_master, src=0)
W = torch.chunk(W_master, TESSERACT_DIM, dim=0)[i]
W = torch.chunk(W, TESSERACT_DIM, dim=-1)[j]
W = W.clone()
W.requires_grad = True
B_shape = (OUTPUT_SIZE)
B_master = torch.randn(B_shape, dtype=dtype, device=device)
torch.distributed.broadcast(B_master, src=0)
B = torch.chunk(B_master, TESSERACT_DIM, dim=0)[j]
B = B.clone()
B.requires_grad = True
layer.weight = Parameter(W)
layer.bias = Parameter(B)
out = layer(A)
bias = layer.bias
A_master = A_master.clone()
A_master.requires_grad = True
W_master = W_master.clone()
W_master.requires_grad = True
B_master = B_master.clone()
B_master.requires_grad = True
C_master = torch.matmul(A_master, W_master) + B_master
C = torch.chunk(C_master, TESSERACT_DIM, dim=0)[i]
C = torch.chunk(C, TESSERACT_DIM, dim=-1)[j]
check_equal(out, C)
print_rank_0('linear forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=get_current_device())
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, TESSERACT_DIM, dim=0)[i]
grad = torch.chunk(grad, TESSERACT_DIM, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, TESSERACT_DIM, dim=0)[i]
A_grad = torch.chunk(A_grad, TESSERACT_DIM, dim=-1)[j]
check_equal(A_grad, A.grad)
W_grad = W_master.grad
W_grad = torch.chunk(W_grad, TESSERACT_DIM, dim=0)[i]
W_grad = torch.chunk(W_grad, TESSERACT_DIM, dim=-1)[j]
check_equal(W_grad, layer.weight.grad)
B_grad = B_master.grad
B_grad = torch.chunk(B_grad, TESSERACT_DIM, dim=0)[j]
if i == 0:
check_equal(B_grad, layer.bias.grad)
print_rank_0('linear backward: pass')
def check_layernorm():
device = get_current_device()
dtype = torch.float32
INPUT_SIZE = HIDDEN_SIZE
EPS = 1e-12
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
layernorm = LayerNorm2p5D(INPUT_SIZE, dtype=dtype)
A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
torch.distributed.broadcast(A_master, src=0)
A = torch.chunk(A_master, TESSERACT_DIM, dim=0)[i]
A = torch.chunk(A, TESSERACT_DIM, dim=-1)[j]
A = A.clone()
A.requires_grad = True
out = layernorm(A)
A_master = A_master.clone()
A_master.requires_grad = True
E_master = torch.sum(A_master, dim=-1, keepdim=True)
E_master /= INPUT_SIZE
V_master = torch.sum(A_master * A_master, dim=-1, keepdim=True)
V_master /= INPUT_SIZE
V_master = V_master - E_master * E_master
V_master = 1.0 / torch.sqrt(V_master + EPS)
C_master = (A_master - E_master) * V_master
C = torch.chunk(C_master, TESSERACT_DIM, dim=0)[i]
C = torch.chunk(C, TESSERACT_DIM, dim=-1)[j]
check_equal(out, C)
print_rank_0('layer norm forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=get_current_device())
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, TESSERACT_DIM, dim=0)[i]
grad = torch.chunk(grad, TESSERACT_DIM, dim=-1)[j]
out.backward(grad)
C_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, TESSERACT_DIM, dim=0)[i]
A_grad = torch.chunk(A_grad, TESSERACT_DIM, dim=-1)[j]
check_equal(A_grad, A.grad)
print_rank_0('layer norm backward: pass')
def check_embed():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
embed = Embedding2p5D(VOCAB_SIZE, HIDDEN_SIZE)
embed = embed.to(dtype).to(device)
embed_master = torch.nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
embed_master = embed_master.to(dtype).to(device)
weight_master = embed_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, TESSERACT_DIM, dim=-1)[j]
weight = torch.chunk(weight, TESSERACT_DIM, dim=-1)[i]
embed.weight.data.copy_(weight)
A_shape = (BATCH_SIZE, SEQ_LENGTH)
A_master = torch.randint(VOCAB_SIZE, A_shape, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = embed(A)
A_master = A_master.clone()
C_master = embed_master(A_master)
C = torch.chunk(C_master, TESSERACT_DIM, dim=0)[i]
C = torch.chunk(C, TESSERACT_DIM, dim=-1)[j]
check_equal(out, C)
print_rank_0('embed forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, TESSERACT_DIM, dim=0)[i]
grad = torch.chunk(grad, TESSERACT_DIM, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
B_grad = embed_master.weight.grad
B_grad = torch.chunk(B_grad, TESSERACT_DIM, dim=-1)[j]
B_grad = torch.chunk(B_grad, TESSERACT_DIM, dim=-1)[i]
check_equal(B_grad, embed.weight.grad)
print_rank_0('embed backward: pass')
def check_patch_embed():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
layer = PatchEmbedding2p5D(IMG_SIZE, 4, 3, HIDDEN_SIZE, dtype=dtype)
torch.nn.init.ones_(layer.cls_token)
torch.nn.init.ones_(layer.pos_embed)
layer = layer.to(device)
layer_master = VanillaPatchEmbedding(IMG_SIZE, 4, 3, HIDDEN_SIZE, dtype=dtype)
torch.nn.init.ones_(layer_master.cls_token)
torch.nn.init.ones_(layer_master.pos_embed)
layer_master = layer_master.to(device)
proj_weight_master = layer_master.weight.data
torch.distributed.broadcast(proj_weight_master, src=0)
proj_weight = torch.chunk(proj_weight_master, TESSERACT_DIM, dim=0)[j]
proj_weight = torch.chunk(proj_weight, TESSERACT_DIM, dim=0)[i]
layer.weight.data.copy_(proj_weight)
proj_bias_master = layer_master.bias.data
torch.distributed.broadcast(proj_bias_master, src=0)
proj_bias = torch.chunk(proj_bias_master, TESSERACT_DIM, dim=0)[j]
proj_bias = torch.chunk(proj_bias, TESSERACT_DIM, dim=0)[i]
layer.bias.data.copy_(proj_bias)
A_shape = (BATCH_SIZE, 3, IMG_SIZE, IMG_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = layer(A)
A_master = A_master.clone()
C_master = layer_master(A_master)
C = torch.chunk(C_master, TESSERACT_DIM, dim=0)[i]
C = torch.chunk(C, TESSERACT_DIM, dim=-1)[j]
check_equal(out, C)
print_rank_0('patch embed forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, TESSERACT_DIM, dim=0)[i]
grad = torch.chunk(grad, TESSERACT_DIM, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
cls_grad_master = layer_master.cls_token.grad
cls_grad = torch.chunk(cls_grad_master, TESSERACT_DIM, dim=-1)[j]
cls_grad = torch.chunk(cls_grad, TESSERACT_DIM, dim=-1)[i]
check_equal(cls_grad, layer.cls_token.grad)
pos_grad_master = layer_master.pos_embed.grad
pos_grad = torch.chunk(pos_grad_master, TESSERACT_DIM, dim=-1)[j]
pos_grad = torch.chunk(pos_grad, TESSERACT_DIM, dim=-1)[i]
check_equal(pos_grad, layer.pos_embed.grad)
B_grad = layer_master.weight.grad
B_grad = torch.chunk(B_grad, TESSERACT_DIM, dim=0)[j]
B_grad = torch.chunk(B_grad, TESSERACT_DIM, dim=0)[i]
check_equal(B_grad, layer.weight.grad)
bias_grad = layer_master.bias.grad
bias_grad = torch.chunk(bias_grad, TESSERACT_DIM)[j]
bias_grad = torch.chunk(bias_grad, TESSERACT_DIM)[i]
check_equal(bias_grad, layer.bias.grad)
print_rank_0('patch embed backward: pass')
def check_vocab_parallel_embed():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
embed = VocabParallelEmbedding2p5D(VOCAB_SIZE, HIDDEN_SIZE)
embed = embed.to(dtype).to(device)
embed_master = torch.nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
embed_master = embed_master.to(dtype).to(device)
weight_master = embed_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, TESSERACT_DIM, dim=-1)[j]
weight = torch.chunk(weight, TESSERACT_DIM, dim=0)[i]
embed.weight.data.copy_(weight)
A_shape = (BATCH_SIZE, SEQ_LENGTH)
A_master = torch.randint(VOCAB_SIZE, A_shape, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = embed(A)
A_master = A_master.clone()
C_master = embed_master(A_master)
C = torch.chunk(C_master, TESSERACT_DIM, dim=0)[i]
C = torch.chunk(C, TESSERACT_DIM, dim=-1)[j]
check_equal(out, C)
print_rank_0('vocab parallel embed forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, TESSERACT_DIM, dim=0)[i]
grad = torch.chunk(grad, TESSERACT_DIM, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
B_grad = embed_master.weight.grad
B_grad = torch.chunk(B_grad, TESSERACT_DIM, dim=-1)[j]
B_grad = torch.chunk(B_grad, TESSERACT_DIM, dim=0)[i]
check_equal(B_grad, embed.weight.grad)
print_rank_0('vocab parallel embed backward: pass')
def check_classifier_no_given_weight():
device = get_current_device()
dtype = torch.float32
INPUT_SIZE = HIDDEN_SIZE
OUTPUT_SIZE = NUM_CLASSES
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
layer = Classifier2p5D(INPUT_SIZE, OUTPUT_SIZE)
A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
A_master = torch.randint(5, A_shape, dtype=dtype, device=device)
torch.distributed.broadcast(A_master, src=0)
A = torch.chunk(A_master, TESSERACT_DIM, dim=0)[i]
A = torch.chunk(A, TESSERACT_DIM, dim=-1)[j]
A = A.clone()
A.requires_grad = True
W_shape = (OUTPUT_SIZE, INPUT_SIZE)
W_master = torch.randint(5, W_shape, dtype=dtype, device=device)
torch.distributed.broadcast(W_master, src=0)
# W = torch.chunk(W_master, TESSERACT_DIM, dim=-1)[j]
W = torch.chunk(W_master, TESSERACT_DIM, dim=-1)[j]
W = torch.chunk(W, TESSERACT_DIM, dim=-1)[i]
W = W.clone()
layer.weight.data.copy_(W)
# W.requires_grad = True
B_shape = (OUTPUT_SIZE, )
B_master = torch.randint(5, B_shape, dtype=dtype, device=device)
torch.distributed.broadcast(B_master, src=0)
# B = torch.chunk(B_master, TESSERACT_DIM, dim=0)[j]
B = B_master.clone()
layer.bias.data.copy_(B)
out = layer(A)
A_master = A_master.clone()
A_master.requires_grad = True
W_master = W_master.clone()
W_master.requires_grad = True
B_master = B_master.clone()
B_master.requires_grad = True
C_master = torch.matmul(A_master, W_master.transpose(0, 1)) + B_master
C = torch.chunk(C_master, TESSERACT_DIM, dim=0)[i]
# C = torch.chunk(C, TESSERACT_DIM, dim=-1)[j]
check_equal(out, C)
print_rank_0('classifier (no given weight) forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=get_current_device())
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, TESSERACT_DIM, dim=0)[i]
# grad = torch.chunk(grad, TESSERACT_DIM, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, TESSERACT_DIM, dim=0)[i]
A_grad = torch.chunk(A_grad, TESSERACT_DIM, dim=-1)[j]
check_equal(A_grad, A.grad)
W_grad = W_master.grad
W_grad = torch.chunk(W_grad, TESSERACT_DIM, dim=-1)[j]
W_grad = torch.chunk(W_grad, TESSERACT_DIM, dim=-1)[i]
check_equal(W_grad, layer.weight.grad)
B_grad = B_master.grad
# B_grad = torch.chunk(B_grad, TESSERACT_DIM, dim=0)[j]
# if i == 0:
check_equal(B_grad, layer.bias.grad)
print_rank_0('classifier (no given weight) backward: pass')
def check_vocab_parallel_classifier_no_given_weight():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
layer = VocabParallelClassifier2p5D(HIDDEN_SIZE, VOCAB_SIZE, bias=True)
layer = layer.to(dtype).to(device)
layer_master = VanillaClassifier(HIDDEN_SIZE, VOCAB_SIZE, bias=True)
layer_master = layer_master.to(dtype).to(device)
weight_master = layer_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, TESSERACT_DIM, dim=0)[i]
weight = torch.chunk(weight, TESSERACT_DIM, dim=-1)[j]
layer.weight.data.copy_(weight)
bias_master = layer_master.bias.data
torch.distributed.broadcast(bias_master, src=0)
bias = torch.chunk(bias_master, TESSERACT_DIM)[j]
layer.bias.data.copy_(bias)
A_shape = (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
torch.distributed.broadcast(A_master, src=0)
A = torch.chunk(A_master, TESSERACT_DIM, dim=0)[i]
A = torch.chunk(A, TESSERACT_DIM, dim=-1)[j]
A = A.clone()
A.requires_grad = True
out = layer(A)
A_master = A_master.clone()
A_master.requires_grad = True
C_master = layer_master(A_master)
C = torch.chunk(C_master, TESSERACT_DIM, dim=0)[i]
C = torch.chunk(C, TESSERACT_DIM, dim=-1)[j]
check_equal(out, C)
print_rank_0('vocab parallel classifier (no given weight) forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, TESSERACT_DIM, dim=0)[i]
grad = torch.chunk(grad, TESSERACT_DIM, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, TESSERACT_DIM, dim=0)[i]
A_grad = torch.chunk(A_grad, TESSERACT_DIM, dim=-1)[j]
check_equal(A_grad, A.grad)
W_grad = layer_master.weight.grad
W_grad = torch.chunk(W_grad, TESSERACT_DIM, dim=0)[i]
W_grad = torch.chunk(W_grad, TESSERACT_DIM, dim=-1)[j]
check_equal(W_grad, layer.weight.grad)
B_grad = layer_master.bias.grad
B_grad = torch.chunk(B_grad, TESSERACT_DIM)[j]
if i == 0:
check_equal(B_grad, layer.bias.grad)
print_rank_0('vocab parallel classifier (no given weight) backward: pass')
def check_classifier_given_embed_weight():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
embed = Embedding2p5D(VOCAB_SIZE, HIDDEN_SIZE)
embed = embed.to(dtype).to(device)
embed_master = torch.nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
embed_master = embed_master.to(dtype).to(device)
weight_master = embed_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, TESSERACT_DIM, dim=-1)[j]
weight = torch.chunk(weight, TESSERACT_DIM, dim=-1)[i]
embed.weight.data.copy_(weight)
layer = Classifier2p5D(HIDDEN_SIZE, VOCAB_SIZE, weight=embed.weight, bias=False)
layer = layer.to(dtype).to(device)
layer_master = VanillaClassifier(HIDDEN_SIZE, VOCAB_SIZE, weight=embed_master.weight, bias=False)
layer_master = layer_master.to(dtype).to(device)
A_shape = (BATCH_SIZE, SEQ_LENGTH)
A_master = torch.randint(VOCAB_SIZE, A_shape, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = layer(embed(A))
A_master = A_master.clone()
C_master = layer_master(embed_master(A_master))
C = torch.chunk(C_master, TESSERACT_DIM, dim=0)[i]
check_equal(out, C)
print_rank_0('classifier (given embed weight) forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, TESSERACT_DIM, dim=0)[i]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
W_grad = embed_master.weight.grad
W_grad = torch.chunk(W_grad, TESSERACT_DIM, dim=-1)[j]
W_grad = torch.chunk(W_grad, TESSERACT_DIM, dim=-1)[i]
check_equal(W_grad, embed.weight.grad)
print_rank_0('classifier (given embed weight) backward: pass')
def check_vocab_parallel_classifier_given_embed_weight():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
embed = VocabParallelEmbedding2p5D(VOCAB_SIZE, HIDDEN_SIZE)
embed = embed.to(dtype).to(device)
embed_master = torch.nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
embed_master = embed_master.to(dtype).to(device)
weight_master = embed_master.weight.data
torch.distributed.broadcast(weight_master, src=0)
weight = torch.chunk(weight_master, TESSERACT_DIM, dim=-1)[j]
weight = torch.chunk(weight, TESSERACT_DIM, dim=0)[i]
embed.weight.data.copy_(weight)
layer = VocabParallelClassifier2p5D(HIDDEN_SIZE, VOCAB_SIZE, weight=embed.weight, bias=False)
layer = layer.to(dtype).to(device)
layer_master = VanillaClassifier(HIDDEN_SIZE, VOCAB_SIZE, weight=embed_master.weight, bias=False)
layer_master = layer_master.to(dtype).to(device)
A_shape = (BATCH_SIZE, SEQ_LENGTH)
A_master = torch.randint(VOCAB_SIZE, A_shape, device=device)
torch.distributed.broadcast(A_master, src=0)
A = A_master.clone()
out = layer(embed(A))
A_master = A_master.clone()
C_master = layer_master(embed_master(A_master))
C = torch.chunk(C_master, TESSERACT_DIM, dim=0)[i]
C = torch.chunk(C, TESSERACT_DIM, dim=-1)[j]
check_equal(out, C)
print_rank_0('vocab parallel classifier (given embed weight) forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, TESSERACT_DIM, dim=0)[i]
grad = torch.chunk(grad, TESSERACT_DIM, dim=-1)[j]
grad = grad.clone()
out.backward(grad)
grad_master = grad_master.clone()
C_master.backward(grad_master)
W_grad = embed_master.weight.grad
W_grad = torch.chunk(W_grad, TESSERACT_DIM, dim=-1)[j]
W_grad = torch.chunk(W_grad, TESSERACT_DIM, dim=0)[i]
check_equal(W_grad, embed.weight.grad)
print_rank_0('vocab parallel classifier (given embed weight) backward: pass')
def check_loss():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
criterion = CrossEntropyLoss2p5D()
criterion_master = torch.nn.CrossEntropyLoss()
out_shape = (BATCH_SIZE, NUM_CLASSES)
out_master = torch.randn(out_shape, dtype=dtype, device=device)
target_master = torch.randint(NUM_CLASSES, (BATCH_SIZE, ), dtype=torch.long, device=device)
torch.distributed.broadcast(out_master, src=0)
torch.distributed.broadcast(target_master, src=0)
out = torch.chunk(out_master, TESSERACT_DIM, dim=0)[i]
out = out.clone()
out.requires_grad = True
loss = criterion(out, target_master)
out_master = out_master.clone()
out_master.requires_grad = True
loss_master = criterion_master(out_master, target_master)
check_equal(loss, loss_master)
print_rank_0('cross entropy loss forward: pass')
loss.backward()
loss_master.backward()
out_grad = out_master.grad
out_grad = torch.chunk(out_grad, TESSERACT_DIM, dim=0)[i]
check_equal(out_grad, out.grad)
print_rank_0('cross entropy loss backward: pass')
def check_vocab_parallel_loss():
device = get_current_device()
dtype = torch.float32
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
criterion = VocabParallelCrossEntropyLoss2p5D()
criterion_master = torch.nn.CrossEntropyLoss()
out_shape = (BATCH_SIZE, NUM_CLASSES)
out_master = torch.randn(out_shape, dtype=dtype, device=device)
target_master = torch.randint(NUM_CLASSES, (BATCH_SIZE, ), dtype=torch.long, device=device)
torch.distributed.broadcast(out_master, src=0)
torch.distributed.broadcast(target_master, src=0)
out = torch.chunk(out_master, TESSERACT_DIM, dim=0)[i]
out = torch.chunk(out, TESSERACT_DIM, dim=-1)[j]
out = out.clone()
out.requires_grad = True
loss = criterion(out, target_master)
out_master = out_master.clone()
out_master.requires_grad = True
loss_master = criterion_master(out_master, target_master)
check_equal(loss, loss_master)
print_rank_0('vocab parallel cross entropy loss forward: pass')
loss.backward()
loss_master.backward()
out_grad = out_master.grad
out_grad = torch.chunk(out_grad, TESSERACT_DIM, dim=0)[i]
out_grad = torch.chunk(out_grad, TESSERACT_DIM, dim=-1)[j]
check_equal(out_grad, out.grad)
print_rank_0('vocab parallel cross entropy loss backward: pass')
# def check_attention():
# device = get_current_device()
# dtype = torch.float32
# INPUT_SIZE = HIDDEN_SIZE
# NUM_ATTENTION_HEADS = 2
# i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
# j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
# k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
# layer = TransformerSelfAttention2p5D(
# HIDDEN_SIZE, NUM_ATTENTION_HEADS,
# attention_dropout_prob=0.5,
# hidden_dropout_prob=0.5,
# dtype=dtype,
# )
# A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
# A_master = torch.randn(A_shape, dtype=dtype, device=device)
# torch.distributed.broadcast(A_master, src=0)
# A = torch.chunk(A_master, TESSERACT_DIM, dim=0)[i]
# A = torch.chunk(A, TESSERACT_DIM, dim=-1)[j]
# A = A.clone()
# A.requires_grad = True
# mask_shape = (BATCH_SIZE // TESSERACT_DIM, NUM_ATTENTION_HEADS // TESSERACT_DIM, SEQ_LENGTH, SEQ_LENGTH)
# attention_mask = torch.zeros(mask_shape, dtype=dtype, device=device)
# out = layer(A, attention_mask)
# assert out.shape == (BATCH_SIZE // TESSERACT_DIM, SEQ_LENGTH, INPUT_SIZE // TESSERACT_DIM)
# print_rank_0('self attention forward: pass')
# grad_shape = out.shape
# grad = torch.randn(grad_shape, dtype=dtype, device=device)
# out.backward(grad)
# assert A.grad.shape == A.shape
# print_rank_0('self attention backward: pass')
# def check_mlp():
# device = get_current_device()
# dtype = torch.float32
# INPUT_SIZE = HIDDEN_SIZE
# i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
# j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
# k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
# layer = TransformerMLP2p5D(
# HIDDEN_SIZE,
# mlp_ratio=1,
# dropout_prob=0.5,
# act_func='gelu',
# dtype=dtype,
# )
# A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
# A_master = torch.randn(A_shape, dtype=dtype, device=device)
# torch.distributed.broadcast(A_master, src=0)
# A = torch.chunk(A_master, TESSERACT_DIM, dim=0)[i]
# A = torch.chunk(A, TESSERACT_DIM, dim=-1)[j]
# A = A.clone()
# A.requires_grad = True
# out = layer(A)
# assert out.shape == (BATCH_SIZE // TESSERACT_DIM, SEQ_LENGTH, INPUT_SIZE // TESSERACT_DIM)
# print_rank_0('mlp forward: pass')
# grad_shape = out.shape
# grad = torch.randn(grad_shape, dtype=dtype, device=device)
# out.backward(grad)
# assert A.grad.shape == A.shape
# print_rank_0('mlp backward: pass')
# def check_transformerlayer():
# device = get_current_device()
# dtype = torch.float32
# INPUT_SIZE = HIDDEN_SIZE
# NUM_ATTENTION_HEADS = 2
# i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
# j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
# k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
# layer = TransformerLayer2p5D(
# HIDDEN_SIZE,
# NUM_ATTENTION_HEADS,
# act_func='gelu',
# attention_dropout_prob=0.5,
# hidden_dropout_prob=0.5,
# dtype=dtype,
# )
# A_shape = (BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)
# A_master = torch.randn(A_shape, dtype=dtype, device=device)
# torch.distributed.broadcast(A_master, src=0)
# A = torch.chunk(A_master, TESSERACT_DIM, dim=0)[i]
# A = torch.chunk(A, TESSERACT_DIM, dim=-1)[j]
# A = A.clone()
# A.requires_grad = True
# mask_shape = (BATCH_SIZE // TESSERACT_DIM, NUM_ATTENTION_HEADS // TESSERACT_DIM, SEQ_LENGTH, SEQ_LENGTH)
# attention_mask = torch.zeros(mask_shape, dtype=dtype, device=device)
# out = layer(A, attention_mask)
# assert out.shape == (BATCH_SIZE // TESSERACT_DIM, SEQ_LENGTH, INPUT_SIZE // TESSERACT_DIM)
# print_rank_0('transformerlayer forward: pass')
# grad_shape = out.shape
# grad = torch.randn(grad_shape, dtype=dtype, device=device)
# out.backward(grad)
# assert A.grad.shape == A.shape
# print_rank_0('transformerlayer backward: pass')
|
import torch
from colossalai.context import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.nn.layer.parallel_2p5d._operation import Matmul_AB_2p5D, Matmul_ABT_2p5D, \
Matmul_ATB_2p5D
from colossalai.utils import get_current_device
from colossalai.utils import print_rank_0
from .common import *
def check_AB():
data_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.DATA) else gpc.get_local_rank(ParallelMode.DATA)
pipeline_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_local_rank(
ParallelMode.PIPELINE)
pipeline_parallel_size = 1 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_world_size(
ParallelMode.PIPELINE)
tensor_parallel_size = gpc.get_world_size(ParallelMode.TENSOR)
dtype = torch.float
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
A_shape = (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=get_current_device())
torch.distributed.broadcast(A_master, src=0)
A = torch.chunk(A_master, TESSERACT_DIM, dim=0)[i]
A = torch.chunk(A, TESSERACT_DIM, dim=-1)[j]
A = A.clone()
A.requires_grad = True
B_shape = (HIDDEN_SIZE, 4 * HIDDEN_SIZE)
B_master = torch.randn(B_shape, dtype=dtype, device=get_current_device())
torch.distributed.broadcast(B_master, src=0)
B = torch.chunk(B_master, TESSERACT_DIM, dim=0)[i]
B = torch.chunk(B, TESSERACT_DIM, dim=-1)[j]
B = B.clone()
B.requires_grad = True
out_shape = (BATCH_SIZE // TESSERACT_DIM, SEQ_LENGTH, 4 * HIDDEN_SIZE // TESSERACT_DIM)
out = Matmul_AB_2p5D.apply(
A, B,
TESSERACT_DIM, out_shape,
i, j, k,
ParallelMode.PARALLEL_2P5D_ROW,
ParallelMode.PARALLEL_2P5D_COL,
data_parallel_rank,
pipeline_parallel_rank,
pipeline_parallel_size,
tensor_parallel_size)
C_shape = (BATCH_SIZE, SEQ_LENGTH, 4 * HIDDEN_SIZE)
A_master = A_master.clone()
A_master.requires_grad = True
B_master = B_master.clone()
B_master.requires_grad = True
C_master = torch.matmul(A_master, B_master)
C = torch.chunk(C_master, TESSERACT_DIM, dim=0)[i]
C = torch.chunk(C, TESSERACT_DIM, dim=-1)[j]
# check forward correctness
check_equal(out, C)
print_rank_0('AB forward: pass')
grad_shape = C_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=get_current_device())
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, TESSERACT_DIM, dim=0)[i]
grad = torch.chunk(grad, TESSERACT_DIM, dim=-1)[j]
out.backward(grad)
C_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, TESSERACT_DIM, dim=0)[i]
A_grad = torch.chunk(A_grad, TESSERACT_DIM, dim=-1)[j]
# check backward correctness
check_equal(A_grad, A.grad)
B_grad = B_master.grad
B_grad = torch.chunk(B_grad, TESSERACT_DIM, dim=0)[i]
B_grad = torch.chunk(B_grad, TESSERACT_DIM, dim=-1)[j]
# check backward correctness
check_equal(B_grad, B.grad)
print_rank_0('AB backward: pass')
def check_ABT():
data_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.DATA) else gpc.get_local_rank(ParallelMode.DATA)
pipeline_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_local_rank(
ParallelMode.PIPELINE)
pipeline_parallel_size = 1 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_world_size(
ParallelMode.PIPELINE)
tensor_parallel_size = gpc.get_world_size(ParallelMode.TENSOR)
dtype = torch.float
device = get_current_device()
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
C_shape = (BATCH_SIZE, SEQ_LENGTH, 4 * HIDDEN_SIZE)
C_master = torch.randn(C_shape, dtype=dtype, device=device)
torch.distributed.broadcast(C_master, src=0)
C = torch.chunk(C_master, TESSERACT_DIM, dim=0)[i]
C = torch.chunk(C, TESSERACT_DIM, dim=-1)[j]
C = C.clone()
C.requires_grad = True
B_shape = (HIDDEN_SIZE, 4 * HIDDEN_SIZE)
B_master = torch.randn(B_shape, dtype=dtype, device=device)
torch.distributed.broadcast(B_master, src=0)
B = torch.chunk(B_master, TESSERACT_DIM, dim=0)[i]
B = torch.chunk(B, TESSERACT_DIM, dim=-1)[j]
B = B.clone()
B.requires_grad = True
out = Matmul_ABT_2p5D.apply(
C, B,
TESSERACT_DIM, (BATCH_SIZE // TESSERACT_DIM, SEQ_LENGTH, HIDDEN_SIZE // TESSERACT_DIM),
i, j, k,
ParallelMode.PARALLEL_2P5D_ROW,
ParallelMode.PARALLEL_2P5D_COL,
data_parallel_rank,
pipeline_parallel_rank,
pipeline_parallel_size,
tensor_parallel_size)
A_shape = (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE)
C_master = C_master.clone()
C_master.requires_grad = True
B_master = B_master.clone()
B_master.requires_grad = True
A_master = torch.matmul(C_master, B_master.transpose(0, 1))
A = torch.chunk(A_master, TESSERACT_DIM, dim=0)[i]
A = torch.chunk(A, TESSERACT_DIM, dim=-1)[j]
check_equal(out, A)
print_rank_0('ABT forward: pass')
grad_shape = A_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, TESSERACT_DIM, dim=0)[i]
grad = torch.chunk(grad, TESSERACT_DIM, dim=-1)[j]
# backward
out.backward(grad)
A_master.backward(grad_master)
C_grad = C_master.grad
C_grad = torch.chunk(C_grad, TESSERACT_DIM, dim=0)[i]
C_grad = torch.chunk(C_grad, TESSERACT_DIM, dim=-1)[j]
check_equal(C_grad, C.grad)
B_grad = B_master.grad
B_grad = torch.chunk(B_grad, TESSERACT_DIM, dim=0)[i]
B_grad = torch.chunk(B_grad, TESSERACT_DIM, dim=-1)[j]
check_equal(B_grad, B.grad)
print_rank_0('ABT backward: pass')
def check_ATB():
data_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.DATA) else gpc.get_local_rank(ParallelMode.DATA)
pipeline_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_local_rank(
ParallelMode.PIPELINE)
pipeline_parallel_size = 1 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_world_size(
ParallelMode.PIPELINE)
tensor_parallel_size = gpc.get_world_size(ParallelMode.TENSOR)
device = get_current_device()
dtype = torch.float
i = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)
j = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW)
k = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP)
A_shape = (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE)
A_master = torch.randn(A_shape, dtype=dtype, device=device)
torch.distributed.broadcast(A_master, src=0)
A = torch.chunk(A_master, TESSERACT_DIM, dim=0)[i]
A = torch.chunk(A, TESSERACT_DIM, dim=-1)[j]
A = A.clone()
A.requires_grad = True
C_shape = (BATCH_SIZE, SEQ_LENGTH, 4 * HIDDEN_SIZE)
C_master = torch.randn(C_shape, dtype=dtype, device=device)
torch.distributed.broadcast(C_master, src=0)
C = torch.chunk(C_master, TESSERACT_DIM, dim=0)[i]
C = torch.chunk(C, TESSERACT_DIM, dim=-1)[j]
C = C.clone()
C.requires_grad = True
out = Matmul_ATB_2p5D.apply(
A, C,
TESSERACT_DIM, (HIDDEN_SIZE // TESSERACT_DIM, 4 * HIDDEN_SIZE // TESSERACT_DIM),
i, j, k,
ParallelMode.PARALLEL_2P5D_ROW,
ParallelMode.PARALLEL_2P5D_COL,
data_parallel_rank,
pipeline_parallel_rank,
pipeline_parallel_size,
tensor_parallel_size)
B_shape = (HIDDEN_SIZE, 4 * HIDDEN_SIZE)
A_master = A_master.clone()
A_master.requires_grad = True
C_master = C_master.clone()
C_master.requires_grad = True
B_master = torch.matmul(
A_master.view(-1, A_master.shape[-1]).transpose(0, 1),
C_master.view(-1, C_master.shape[-1]))
B = torch.chunk(B_master, TESSERACT_DIM, dim=0)[i]
B = torch.chunk(B, TESSERACT_DIM, dim=-1)[j]
check_equal(out, B)
print_rank_0('ATB forward: pass')
grad_shape = B_master.shape
grad_master = torch.randn(grad_shape, dtype=dtype, device=device)
torch.distributed.broadcast(grad_master, src=0)
grad = torch.chunk(grad_master, TESSERACT_DIM, dim=0)[i]
grad = torch.chunk(grad, TESSERACT_DIM, dim=-1)[j]
out.backward(grad)
B_master.backward(grad_master)
A_grad = A_master.grad
A_grad = torch.chunk(A_grad, TESSERACT_DIM, dim=0)[i]
A_grad = torch.chunk(A_grad, TESSERACT_DIM, dim=-1)[j]
check_equal(A_grad, A.grad)
C_grad = C_master.grad
C_grad = torch.chunk(C_grad, TESSERACT_DIM, dim=0)[i]
C_grad = torch.chunk(C_grad, TESSERACT_DIM, dim=-1)[j]
check_equal(C_grad, C.grad)
print_rank_0('ATB backward: pass')
|
import torch
TESSERACT_DIM = 2
TESSERACT_DEP = 2
BATCH_SIZE = 8
SEQ_LENGTH = 8
HIDDEN_SIZE = 8
NUM_CLASSES = 8
VOCAB_SIZE = 16
IMG_SIZE = 16
def check_equal(A, B):
assert torch.allclose(A, B, rtol=1e-5, atol=1e-2)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from functools import partial
import pytest
import torch
import torch.multiprocessing as mp
from colossalai.core import global_context as gpc
from colossalai.initialize import launch
from colossalai.logging import disable_existing_loggers
from colossalai.utils import free_port
from colossalai.testing import rerun_if_address_is_in_use
from checks_3d.check_layer_3d import (check_classifier_given_embed_weight, check_classifier_no_given_weight,
check_embed, check_layernorm, check_linear, check_loss, check_patch_embed,
check_vocab_parallel_classifier_given_embed_weight,
check_vocab_parallel_classifier_no_given_weight, check_vocab_parallel_embed,
check_vocab_parallel_loss)
CONFIG = dict(
parallel=dict(
pipeline=1,
tensor=dict(mode='3d', size=8),
),
seed=42,
)
def check_layer():
check_linear()
check_layernorm()
check_classifier_no_given_weight()
check_vocab_parallel_classifier_no_given_weight()
check_classifier_given_embed_weight()
check_vocab_parallel_classifier_given_embed_weight()
check_embed()
check_patch_embed()
check_vocab_parallel_embed()
check_loss()
check_vocab_parallel_loss()
def check_layer_and_operation(rank, world_size, port):
disable_existing_loggers()
launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.backends.cudnn.deterministic = True
check_layer()
gpc.destroy()
torch.cuda.empty_cache()
@pytest.mark.dist
@rerun_if_address_is_in_use()
def test_3d():
world_size = 8
run_func = partial(check_layer_and_operation, world_size=world_size, port=free_port())
mp.spawn(run_func, nprocs=world_size)
if __name__ == '__main__':
test_3d()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import torch
DEPTH = 2
BATCH_SIZE = 8
SEQ_LENGTH = 8
HIDDEN_SIZE = 8
NUM_CLASSES = 8
NUM_BLOCKS = 2
IMG_SIZE = 16
VOCAB_SIZE = 16
def check_equal(A, B):
eq = torch.allclose(A, B, rtol=1e-3, atol=1e-2)
assert eq
return eq
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.