brunner56 commited on
Commit
47beeae
·
verified ·
1 Parent(s): 721f5f5

Update install.py

Browse files
Files changed (1) hide show
  1. install.py +153 -152
install.py CHANGED
@@ -1,153 +1,154 @@
1
- #!/usr/bin/env python
2
- # coding=utf-8
3
-
4
- """
5
- Installation script for Hugging Face Space setup.
6
- This script ensures all dependencies are installed correctly
7
- during the Space build process.
8
- """
9
-
10
- import os
11
- import sys
12
- import subprocess
13
- import logging
14
- import traceback
15
- from pathlib import Path
16
-
17
- # Configure logging
18
- logging.basicConfig(
19
- level=logging.INFO,
20
- format="%(asctime)s - %(levelname)s - %(message)s",
21
- handlers=[logging.StreamHandler(sys.stdout)]
22
- )
23
- logger = logging.getLogger(__name__)
24
-
25
- def run_command(cmd, description=""):
26
- """Run a shell command and log the output."""
27
- logger.info(f"Running: {description if description else cmd}")
28
- try:
29
- process = subprocess.run(
30
- cmd,
31
- shell=True,
32
- check=True,
33
- stdout=subprocess.PIPE,
34
- stderr=subprocess.PIPE,
35
- text=True
36
- )
37
- logger.info(f"Command output: {process.stdout}")
38
- return True
39
- except subprocess.CalledProcessError as e:
40
- logger.error(f"Command failed with exit code {e.returncode}")
41
- logger.error(f"Error output: {e.stderr}")
42
- return False
43
-
44
- def install_dependencies():
45
- """Install all required dependencies in the correct order."""
46
- current_dir = Path(__file__).parent
47
- req_path = current_dir / "requirements.txt"
48
-
49
- if not req_path.exists():
50
- logger.error(f"Requirements file not found: {req_path}")
51
- return False
52
-
53
- try:
54
- # Step 1: Upgrade pip
55
- run_command(f"{sys.executable} -m pip install --upgrade pip", "Upgrading pip")
56
-
57
- # Step 2: Install direct torch version for CUDA compatibility
58
- run_command(
59
- f"{sys.executable} -m pip install torch>=2.0.0,<2.2.0 --extra-index-url https://download.pytorch.org/whl/cu118",
60
- "Installing PyTorch with CUDA support"
61
- )
62
-
63
- # Step 3: Install base dependencies
64
- run_command(
65
- f"{sys.executable} -m pip install transformers accelerate bitsandbytes peft einops",
66
- "Installing ML dependencies"
67
- )
68
-
69
- # Step 4: Install unsloth separately
70
- run_command(
71
- f"{sys.executable} -m pip install unsloth>=2024.3",
72
- "Installing Unsloth"
73
- )
74
-
75
- # Step 5: Install all remaining requirements
76
- run_command(
77
- f"{sys.executable} -m pip install -r {req_path}",
78
- "Installing all requirements"
79
- )
80
-
81
- # Verify critical packages
82
- import_check = verify_imports()
83
- if not import_check:
84
- logger.error("Failed to verify critical packages")
85
- return False
86
-
87
- logger.info("All dependencies installed successfully!")
88
- return True
89
-
90
- except Exception as e:
91
- logger.error(f"Error installing dependencies: {str(e)}")
92
- traceback.print_exc()
93
- return False
94
-
95
- def verify_imports():
96
- """Verify that critical packages can be imported."""
97
- critical_packages = [
98
- "torch", "transformers", "unsloth", "peft",
99
- "gradio", "accelerate", "bitsandbytes"
100
- ]
101
-
102
- success = True
103
- for package in critical_packages:
104
- try:
105
- module = __import__(package)
106
- version = getattr(module, "__version__", "unknown")
107
- logger.info(f"Successfully imported {package} (version: {version})")
108
- except ImportError:
109
- logger.error(f"CRITICAL: Failed to import {package}")
110
- success = False
111
- except Exception as e:
112
- logger.error(f"Error verifying {package}: {str(e)}")
113
- success = False
114
-
115
- # Check CUDA
116
- try:
117
- import torch
118
- cuda_available = torch.cuda.is_available()
119
- device_count = torch.cuda.device_count() if cuda_available else 0
120
- if cuda_available:
121
- device_name = torch.cuda.get_device_name(0)
122
- logger.info(f"CUDA available - Devices: {device_count}, Name: {device_name}")
123
- else:
124
- logger.warning(f"CUDA not available - This might affect performance")
125
- except Exception as e:
126
- logger.error(f"Error checking CUDA: {str(e)}")
127
-
128
- return success
129
-
130
- def main():
131
- logger.info("Starting installation for Phi-4 Unsloth Training Space")
132
-
133
- try:
134
- # Install dependencies
135
- if not install_dependencies():
136
- logger.error("Failed to install dependencies")
137
- sys.exit(1)
138
-
139
- # Create marker file to show successful installation
140
- with open("INSTALL_SUCCESS.txt", "w") as f:
141
- f.write("Installation completed successfully")
142
-
143
- logger.info("Installation completed successfully")
144
- return 0
145
-
146
- except Exception as e:
147
- logger.error(f"Installation failed with error: {str(e)}")
148
- traceback.print_exc()
149
- return 1
150
-
151
- if __name__ == "__main__":
152
- exit_code = main()
 
153
  sys.exit(exit_code)
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+
4
+ """
5
+ Installation script for Hugging Face Space setup.
6
+ This script ensures all dependencies are installed correctly
7
+ during the Space build process.
8
+ """
9
+
10
+ import unsloth
11
+ import os
12
+ import sys
13
+ import subprocess
14
+ import logging
15
+ import traceback
16
+ from pathlib import Path
17
+
18
+ # Configure logging
19
+ logging.basicConfig(
20
+ level=logging.INFO,
21
+ format="%(asctime)s - %(levelname)s - %(message)s",
22
+ handlers=[logging.StreamHandler(sys.stdout)]
23
+ )
24
+ logger = logging.getLogger(__name__)
25
+
26
+ def run_command(cmd, description=""):
27
+ """Run a shell command and log the output."""
28
+ logger.info(f"Running: {description if description else cmd}")
29
+ try:
30
+ process = subprocess.run(
31
+ cmd,
32
+ shell=True,
33
+ check=True,
34
+ stdout=subprocess.PIPE,
35
+ stderr=subprocess.PIPE,
36
+ text=True
37
+ )
38
+ logger.info(f"Command output: {process.stdout}")
39
+ return True
40
+ except subprocess.CalledProcessError as e:
41
+ logger.error(f"Command failed with exit code {e.returncode}")
42
+ logger.error(f"Error output: {e.stderr}")
43
+ return False
44
+
45
+ def install_dependencies():
46
+ """Install all required dependencies in the correct order."""
47
+ current_dir = Path(__file__).parent
48
+ req_path = current_dir / "requirements.txt"
49
+
50
+ if not req_path.exists():
51
+ logger.error(f"Requirements file not found: {req_path}")
52
+ return False
53
+
54
+ try:
55
+ # Step 1: Upgrade pip
56
+ run_command(f"{sys.executable} -m pip install --upgrade pip", "Upgrading pip")
57
+
58
+ # Step 2: Install direct torch version for CUDA compatibility
59
+ run_command(
60
+ f"{sys.executable} -m pip install torch>=2.0.0,<2.2.0 --extra-index-url https://download.pytorch.org/whl/cu118",
61
+ "Installing PyTorch with CUDA support"
62
+ )
63
+
64
+ # Step 3: Install base dependencies
65
+ run_command(
66
+ f"{sys.executable} -m pip install transformers accelerate bitsandbytes peft einops",
67
+ "Installing ML dependencies"
68
+ )
69
+
70
+ # Step 4: Install unsloth separately
71
+ run_command(
72
+ f"{sys.executable} -m pip install unsloth>=2024.3",
73
+ "Installing Unsloth"
74
+ )
75
+
76
+ # Step 5: Install all remaining requirements
77
+ run_command(
78
+ f"{sys.executable} -m pip install -r {req_path}",
79
+ "Installing all requirements"
80
+ )
81
+
82
+ # Verify critical packages
83
+ import_check = verify_imports()
84
+ if not import_check:
85
+ logger.error("Failed to verify critical packages")
86
+ return False
87
+
88
+ logger.info("All dependencies installed successfully!")
89
+ return True
90
+
91
+ except Exception as e:
92
+ logger.error(f"Error installing dependencies: {str(e)}")
93
+ traceback.print_exc()
94
+ return False
95
+
96
+ def verify_imports():
97
+ """Verify that critical packages can be imported."""
98
+ critical_packages = [
99
+ "torch", "transformers", "unsloth", "peft",
100
+ "gradio", "accelerate", "bitsandbytes"
101
+ ]
102
+
103
+ success = True
104
+ for package in critical_packages:
105
+ try:
106
+ module = __import__(package)
107
+ version = getattr(module, "__version__", "unknown")
108
+ logger.info(f"Successfully imported {package} (version: {version})")
109
+ except ImportError:
110
+ logger.error(f"CRITICAL: Failed to import {package}")
111
+ success = False
112
+ except Exception as e:
113
+ logger.error(f"Error verifying {package}: {str(e)}")
114
+ success = False
115
+
116
+ # Check CUDA
117
+ try:
118
+ import torch
119
+ cuda_available = torch.cuda.is_available()
120
+ device_count = torch.cuda.device_count() if cuda_available else 0
121
+ if cuda_available:
122
+ device_name = torch.cuda.get_device_name(0)
123
+ logger.info(f"CUDA available - Devices: {device_count}, Name: {device_name}")
124
+ else:
125
+ logger.warning(f"CUDA not available - This might affect performance")
126
+ except Exception as e:
127
+ logger.error(f"Error checking CUDA: {str(e)}")
128
+
129
+ return success
130
+
131
+ def main():
132
+ logger.info("Starting installation for Phi-4 Unsloth Training Space")
133
+
134
+ try:
135
+ # Install dependencies
136
+ if not install_dependencies():
137
+ logger.error("Failed to install dependencies")
138
+ sys.exit(1)
139
+
140
+ # Create marker file to show successful installation
141
+ with open("INSTALL_SUCCESS.txt", "w") as f:
142
+ f.write("Installation completed successfully")
143
+
144
+ logger.info("Installation completed successfully")
145
+ return 0
146
+
147
+ except Exception as e:
148
+ logger.error(f"Installation failed with error: {str(e)}")
149
+ traceback.print_exc()
150
+ return 1
151
+
152
+ if __name__ == "__main__":
153
+ exit_code = main()
154
  sys.exit(exit_code)