To achieve this task efficiently, you can use the Python safetensors library to handle the safetensors files. Assuming you have this library installed, the process involves loading all safetensors files that match the size criteria, reading each tensor, accumulating their values, then averaging them across all files to produce a merged tensor. Here’s an example of how you might implement this:
import os
import numpy as np
from safetensors import safe_open
def load_and_average_safetensors(directory):
# Define the size boundaries in bytes
min_size = 6 * 1024 * 1024 * 1024 # 6 GB
max_size = 7 * 1024 * 1024 * 1024 # 7 GB
# Get all files in the directory
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
# Sort eligible files by their size criteria
eligible_files = []
for f in files:
file_path = os.path.join(directory, f)
size = os.path.getsize(file_path)
if min_size <= size < max_size and f.endswith('.safetensors'):
eligible_files.append(file_path)
if not eligible_files:
raise ValueError("No safetensors files found within the specified size range.")
# Initialize cumulative sums and counters
cumulative_sums = {}
file_count = len(eligible_files)
# Load tensors and calculate cumulative sums
for file_path in eligible_files:
with safe_open(file_path, framework="pt") as f:
for key in f.keys():
tensor = f.get_tensor(key)
if key not in cumulative_sums:
cumulative_sums[key] = np.zeros_like(tensor)
cumulative_sums[key] += tensor
# Calculate the average
averages = {key: cumulative_sums[key] / file_count for key in cumulative_sums}
return averages
# Example usage:
# directory_path = "/path/to/safetensors/files"
# averaged_tensors = load_and_average_safetensors(directory_path)
# print("Averaged Tensors:", {key: value.shape for key, value in averaged_tensors.items()})
Steps in the Code:
- Directory and File Handling: The code iterates over files in the specified directory, checking their sizes. Only files ending with
.safetensors and within the size limits are processed.
- Tensor Accumulation: Using
numpy, the tensors from each file are summed. This is efficient because numpy operations are vectorized.
- Calculate Averages: Once all files are processed, you compute the average by dividing the cumulative sum of each tensor by the number of files.
- Return the Averaged Tensors: The result is a dictionary of tensors keyed by their names.
Notes:
- Ensure the
safetensors library is installed. If not, you can install it via pip: pip install safetensors.
- Adjust error handling and logging as necessary to better fit your actual data and environment.
- Modify paths and hardware settings according to your constraints, especially if handling large-sized files affects memory.