Skip to content

Commit ab4ac81

Browse files
committed
update
1 parent 136f364 commit ab4ac81

2 files changed

Lines changed: 129 additions & 0 deletions

File tree

tools/GENAi/inspect_safetensors.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import os
2+
import subprocess
3+
from safetensors import safe_open
4+
import numpy as np
5+
6+
def ensure_dependencies():
7+
"""Ensure that required dependencies are installed."""
8+
try:
9+
import torch
10+
except ImportError:
11+
print("PyTorch is not installed. Installing now...")
12+
subprocess.check_call(["pip", "install", "torch"])
13+
14+
def get_safe_tensor_location():
15+
"""Prompt the user for the location of the safe tensor file."""
16+
while True:
17+
location = input("Enter the path to your safe tensor file: ").strip()
18+
if os.path.isfile(location):
19+
return location
20+
else:
21+
print("Invalid file path. Please try again.")
22+
23+
def display_tensor_keys(file_path):
24+
"""Display the keys of tensors in the safe tensor file."""
25+
try:
26+
with safe_open(file_path, framework="pt") as f:
27+
keys = f.keys()
28+
print("\nAvailable Tensor Keys:")
29+
for key in keys:
30+
print(f"- {key}")
31+
return keys
32+
except Exception as e:
33+
print(f"Error reading tensor keys: {e}")
34+
return []
35+
36+
def display_tensor_metadata(file_path, key):
37+
"""Display metadata and a preview of the tensor for a specific key."""
38+
try:
39+
with safe_open(file_path, framework="pt") as f:
40+
tensor = f.get_tensor(key)
41+
print(f"\nKey: {key}")
42+
print(f"Shape: {tensor.shape}")
43+
print(f"Dtype: {tensor.dtype}")
44+
print(f"Device: {tensor.device}")
45+
print("First 5 Values:", tensor.flatten()[:5])
46+
except Exception as e:
47+
print(f"Error reading tensor metadata: {e}")
48+
49+
def main():
50+
"""Main function to orchestrate the script."""
51+
print("\n=== Safe Tensor Inspector ===")
52+
53+
# Ensure dependencies are installed
54+
ensure_dependencies()
55+
56+
# Step 1: Get the file location
57+
file_path = get_safe_tensor_location()
58+
59+
# Step 2: Display tensor keys
60+
keys = display_tensor_keys(file_path)
61+
if not keys:
62+
print("No tensors found or unable to read the file.")
63+
return
64+
65+
# Step 3: Interactive selection
66+
while True:
67+
print("\nMenu:")
68+
print("1. View tensor keys")
69+
print("2. Inspect a tensor")
70+
print("3. Exit")
71+
72+
choice = input("Enter your choice: ").strip()
73+
74+
if choice == "1":
75+
display_tensor_keys(file_path)
76+
elif choice == "2":
77+
key = input("Enter the tensor key to inspect: ").strip()
78+
if key in keys:
79+
display_tensor_metadata(file_path, key)
80+
else:
81+
print("Invalid key. Use option 1 to view available keys.")
82+
elif choice == "3":
83+
print("Exiting the inspector. Goodbye!")
84+
break
85+
else:
86+
print("Invalid choice. Please select a valid option.")
87+
88+
if __name__ == "__main__":
89+
main()
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
@echo off
2+
REM Batch file to set up the environment and run the Python script
3+
4+
REM Step 1: Set the virtual environment directory
5+
set VENV_DIR=venv
6+
7+
REM Step 2: Check if the virtual environment exists
8+
if not exist %VENV_DIR% (
9+
echo Virtual environment not found. Creating one...
10+
python -m venv %VENV_DIR%
11+
if errorlevel 1 (
12+
echo Failed to create virtual environment. Exiting...
13+
exit /b 1
14+
)
15+
echo Virtual environment created.
16+
)
17+
18+
REM Step 3: Activate the virtual environment
19+
call %VENV_DIR%\\Scripts\\activate
20+
21+
REM Step 4: Install required dependencies
22+
echo Installing dependencies...
23+
pip install safetensors numpy torch
24+
if errorlevel 1 (
25+
echo Failed to install dependencies. Exiting...
26+
exit /b 1
27+
)
28+
29+
REM Step 5: Run the Python script
30+
echo Running the Safe Tensor Inspector...
31+
python inspect_safetensors.py
32+
if errorlevel 1 (
33+
echo Script execution failed. Exiting...
34+
exit /b 1
35+
)
36+
37+
REM Step 6: Deactivate the virtual environment
38+
deactivate
39+
echo Done.
40+
pause

0 commit comments

Comments
 (0)