oopere commited on
Commit
b1f0789
Β·
1 Parent(s): 0961175

feat: add diagnostic tools and configuration for timeout and memory issues in HF Spaces

Browse files
DIAGNOSTIC_README.md ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # πŸ” Diagnostic Guide: Timeout vs Memory
2
+
3
+ ## How to identify the problem?
4
+
5
+ ### 1️⃣ Run the diagnostic tool
6
+
7
+ In your HF Space, execute:
8
+
9
+ ```bash
10
+ python hf-spaces/diagnostic_tool.py
11
+ ```
12
+
13
+ This tool will tell you **exactly** if the problem is:
14
+ - ❌ **MEMORY_ERROR**: The system ran out of RAM
15
+ - ⏰ **TIMEOUT_ERROR**: The operation took too long
16
+ - ❓ **OTHER_ERROR**: Another type of problem
17
+
18
+ ### 2️⃣ Interpret the results
19
+
20
+ #### If you see "MEMORY_ERROR":
21
+ ```
22
+ ❌ PROBLEM DETECTED: OUT OF MEMORY
23
+ Memory used at failure: 15.8 GB (98.5%)
24
+ ```
25
+
26
+ **Cause**: The model is too large for the available memory in HF Spaces.
27
+
28
+ **Solutions**:
29
+ 1. **Use smaller models** (1B-1.7B parameters)
30
+ 2. **Upgrade to HF Spaces PRO** (more RAM available)
31
+ 3. **Use int8 quantization** (reduces memory usage ~50%)
32
+ 4. **Load models with `low_cpu_mem_usage=True`**
33
+
34
+ #### If you see "TIMEOUT_ERROR":
35
+ ```
36
+ ⏰ TIMEOUT ERROR after 298.5s
37
+ Memory used: 8.2 GB (51.2%)
38
+ ```
39
+
40
+ **Cause**: The model takes too long to load, but there is available memory.
41
+
42
+ **Solutions**:
43
+ 1. **Increase timeout** from 300s to 600s or 900s
44
+ 2. **Cache pre-loaded models** at startup
45
+ 3. **Use faster models**
46
+
47
+ ## πŸ› οΈ Implemented Solutions
48
+
49
+ ### Solution 1: Increase Timeout (Easy)
50
+
51
+ Edit `hf-spaces/optipfair_frontend.py`:
52
+
53
+ ```python
54
+ # Change from:
55
+ response = requests.post(url, json=payload, timeout=300)
56
+
57
+ # To:
58
+ response = requests.post(url, json=payload, timeout=600) # 10 minutes
59
+ ```
60
+
61
+ ### Solution 2: Use Quantization (For memory issues)
62
+
63
+ Edit model loading code in the backend:
64
+
65
+ ```python
66
+ from transformers import AutoModel, BitsAndBytesConfig
67
+
68
+ # Configure int8 quantization (reduces memory usage ~50%)
69
+ quantization_config = BitsAndBytesConfig(
70
+ load_in_8bit=True,
71
+ llm_int8_threshold=6.0,
72
+ )
73
+
74
+ model = AutoModel.from_pretrained(
75
+ model_name,
76
+ quantization_config=quantization_config,
77
+ device_map="auto",
78
+ low_cpu_mem_usage=True,
79
+ )
80
+ ```
81
+
82
+ ### Solution 3: Model Cache (For timeout)
83
+
84
+ Pre-load models at startup in `hf-spaces/app.py`:
85
+
86
+ ```python
87
+ from transformers import AutoModel, AutoTokenizer
88
+ import logging
89
+
90
+ logger = logging.getLogger(__name__)
91
+
92
+ # Global model cache
93
+ MODEL_CACHE = {}
94
+
95
+ def preload_models():
96
+ """Pre-load common models at startup"""
97
+ common_models = [
98
+ "meta-llama/Llama-3.2-1B",
99
+ "oopere/pruned40-llama-3.2-1B",
100
+ ]
101
+
102
+ logger.info("πŸ”„ Pre-loading common models...")
103
+ for model_name in common_models:
104
+ try:
105
+ logger.info(f" Loading {model_name}...")
106
+ MODEL_CACHE[model_name] = {
107
+ "model": AutoModel.from_pretrained(model_name, low_cpu_mem_usage=True),
108
+ "tokenizer": AutoTokenizer.from_pretrained(model_name)
109
+ }
110
+ logger.info(f" βœ“ {model_name} loaded")
111
+ except Exception as e:
112
+ logger.warning(f" βœ— Could not pre-load {model_name}: {e}")
113
+
114
+ logger.info("βœ… Pre-loading complete")
115
+
116
+ def main():
117
+ # Pre-load models before starting services
118
+ preload_models()
119
+
120
+ # Rest of the code...
121
+ fastapi_thread = threading.Thread(target=run_fastapi, daemon=True)
122
+ fastapi_thread.start()
123
+ # ...
124
+ ```
125
+
126
+ ### Solution 4: Improved Error Messages
127
+
128
+ Better error messages are already included to help you identify the problem:
129
+
130
+ ```python
131
+ except requests.exceptions.Timeout:
132
+ return (
133
+ None,
134
+ "❌ **Timeout Error:**\nThe model took too long to load (>5min). "
135
+ "This is normal with large models. Options:\n"
136
+ "1. Try with a smaller model\n"
137
+ "2. Wait and try again (model may be caching)\n"
138
+ "3. Contact admin to increase timeout",
139
+ ""
140
+ )
141
+
142
+ except MemoryError:
143
+ return (
144
+ None,
145
+ "❌ **Memory Error:**\nNot enough RAM for this model. Options:\n"
146
+ "1. Use a smaller model (1B parameters)\n"
147
+ "2. Model requires more memory than available in HF Spaces",
148
+ ""
149
+ )
150
+ ```
151
+
152
+ ## πŸ“Š Model Size Comparison
153
+
154
+ | Model | Parameters | RAM Needed* | Load Time** |
155
+ |--------|-----------|----------------|----------------|
156
+ | Llama-3.2-1B | 1B | ~4 GB | ~30s |
157
+ | Llama-3.2-3B | 3B | ~12 GB | ~90s |
158
+ | Llama-3-8B | 8B | ~32 GB | ~240s |
159
+ | Llama-3-70B | 70B | ~280 GB | ~600s+ |
160
+
161
+ *Without quantization, FP32
162
+ **On typical HF Spaces hardware
163
+
164
+ ## 🎯 Recommended Action Plan
165
+
166
+ 1. **Run the diagnostic**:
167
+ ```bash
168
+ python hf-spaces/diagnostic_tool.py
169
+ ```
170
+
171
+ 2. **Read the results** and follow the specific recommendations
172
+
173
+ 3. **Apply the appropriate solution**:
174
+ - If timeout β†’ Increase timeout or use cache
175
+ - If memory β†’ Use small models or quantization
176
+
177
+ 4. **Test again** with the adjusted configuration
178
+
179
+ ## πŸ“ Useful Logs in HF Spaces
180
+
181
+ Check the logs in HF Spaces for messages like:
182
+
183
+ ```
184
+ πŸ” MODEL LOADING DIAGNOSTIC: meta-llama/Llama-3.2-1B
185
+ πŸ“Š INITIAL SYSTEM STATE:
186
+ - Available memory: 12.50 GB
187
+ - Used memory: 3.45 GB (21.6%)
188
+ ⏳ Starting model loading (timeout: 300s)...
189
+ [1/2] Loading tokenizer...
190
+ βœ“ Tokenizer loaded in 2.31s
191
+ - Memory used: 3.48 GB (21.8%)
192
+ [2/2] Loading model...
193
+ βœ“ Model loaded in 45.67s
194
+ βœ… LOADING SUCCESSFUL in 47.98s
195
+ ```
196
+
197
+ This tells you exactly how much memory and time each step uses.
README_DIAGNOSTICS.md ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # πŸ” Timeout vs Memory Diagnostic Tools
2
+
3
+ ## Overview
4
+
5
+ When working with heavy models in HF Spaces, you may encounter issues that could be caused by:
6
+ 1. **Timeout**: The model takes too long to load (>5 minutes)
7
+ 2. **Memory**: The system runs out of RAM
8
+ 3. **Both**: A combination of both issues
9
+
10
+ This toolkit helps you identify and fix the exact problem.
11
+
12
+ ## πŸ“ Files Added
13
+
14
+ ### 1. `diagnostic_tool.py`
15
+ **Purpose**: Identify if the problem is timeout or memory
16
+
17
+ **Usage**:
18
+ ```bash
19
+ python hf-spaces/diagnostic_tool.py
20
+ ```
21
+
22
+ **What it does**:
23
+ - Monitors system memory in real-time
24
+ - Tracks model loading time
25
+ - Detects the exact failure point
26
+ - Provides specific recommendations
27
+
28
+ **Output**:
29
+ ```
30
+ πŸ” MODEL LOADING DIAGNOSTIC: meta-llama/Llama-3.2-1B
31
+ πŸ“Š INITIAL SYSTEM STATE:
32
+ - Available memory: 12.50 GB
33
+ - Used memory: 3.45 GB (21.6%)
34
+ ⏳ Starting model loading (timeout: 300s)...
35
+ [1/2] Loading tokenizer...
36
+ βœ“ Tokenizer loaded in 2.31s
37
+ [2/2] Loading model...
38
+ βœ“ Model loaded in 45.67s
39
+ βœ… LOADING SUCCESSFUL in 47.98s
40
+
41
+ πŸ’‘ RECOMMENDATIONS
42
+ βœ… Model loaded successfully.
43
+ ```
44
+
45
+ ### 2. `config_optimized.py`
46
+ **Purpose**: Smart configuration based on model size
47
+
48
+ **Features**:
49
+ - Auto-detects model size category (small/medium/large)
50
+ - Provides optimized timeout settings
51
+ - Recommends appropriate HF Spaces tier
52
+ - Warns about memory issues before loading
53
+
54
+ **Usage**:
55
+ ```python
56
+ from config_optimized import HFSpacesConfig, get_optimized_request_config
57
+
58
+ # Get optimal timeout for a model
59
+ timeout = HFSpacesConfig.get_timeout_for_model("meta-llama/Llama-3.2-1B")
60
+
61
+ # Get full request config
62
+ config = get_optimized_request_config("meta-llama/Llama-3.2-1B")
63
+ response = requests.post(url, json=payload, **config)
64
+
65
+ # Check if model is recommended for your tier
66
+ is_ok = HFSpacesConfig.is_model_recommended("meta-llama/Llama-3.2-1B", tier="free")
67
+ ```
68
+
69
+ ### 3. `DIAGNOSTIC_README.md`
70
+ **Purpose**: Complete guide with solutions
71
+
72
+ **Contents**:
73
+ - How to identify timeout vs memory issues
74
+ - Step-by-step solutions for each problem
75
+ - Model size comparison table
76
+ - Code examples for fixes
77
+ - Best practices
78
+
79
+ ### 4. Improved Error Messages in `optipfair_frontend.py`
80
+ **What changed**:
81
+ - More informative timeout error messages
82
+ - Explicit memory error detection
83
+ - Actionable recommendations in errors
84
+ - All messages in English
85
+
86
+ **Example**:
87
+ ```
88
+ ❌ **Timeout Error:**
89
+ The request exceeded 5 minutes (300s).
90
+
91
+ **Possible causes:**
92
+ 1. The model is very large and takes long to load
93
+ 2. The server is processing many requests
94
+
95
+ **Solutions:**
96
+ β€’ Use a smaller model (1B parameters)
97
+ β€’ Wait and try again (model may be caching)
98
+ β€’ If it persists, run `diagnostic_tool.py` for more information
99
+ ```
100
+
101
+ ## πŸš€ Quick Start Guide
102
+
103
+ ### Step 1: Diagnose the Problem
104
+ ```bash
105
+ cd hf-spaces
106
+ python diagnostic_tool.py
107
+ ```
108
+
109
+ ### Step 2: Read the Output
110
+ The tool will tell you:
111
+ - βœ… **Success**: Model loads fine
112
+ - ❌ **MEMORY_ERROR**: Need more RAM or smaller model
113
+ - ⏰ **TIMEOUT_ERROR**: Need more time or faster model
114
+
115
+ ### Step 3: Apply the Solution
116
+
117
+ #### For TIMEOUT problems:
118
+ ```python
119
+ # Option 1: Increase timeout in optipfair_frontend.py
120
+ response = requests.post(
121
+ url,
122
+ json=payload,
123
+ timeout=600 # Change from 300 to 600 seconds
124
+ )
125
+
126
+ # Option 2: Use config_optimized.py
127
+ from config_optimized import get_optimized_request_config
128
+ config = get_optimized_request_config(model_name)
129
+ response = requests.post(url, json=payload, **config)
130
+ ```
131
+
132
+ #### For MEMORY problems:
133
+ ```python
134
+ # Option 1: Use smaller model
135
+ AVAILABLE_MODELS = [
136
+ "meta-llama/Llama-3.2-1B", # βœ… Works on free tier
137
+ "oopere/pruned40-llama-3.2-1B", # βœ… Works on free tier
138
+ ]
139
+
140
+ # Option 2: Use quantization (in backend)
141
+ from transformers import AutoModel, BitsAndBytesConfig
142
+
143
+ quantization_config = BitsAndBytesConfig(load_in_8bit=True)
144
+ model = AutoModel.from_pretrained(
145
+ model_name,
146
+ quantization_config=quantization_config,
147
+ low_cpu_mem_usage=True,
148
+ )
149
+
150
+ # Option 3: Upgrade HF Spaces tier
151
+ # Free: 16GB RAM β†’ PRO: 32GB RAM β†’ Enterprise: 64GB RAM
152
+ ```
153
+
154
+ ## πŸ“Š Model Recommendations by Tier
155
+
156
+ ### Free Tier (16GB RAM)
157
+ βœ… **Recommended**:
158
+ - meta-llama/Llama-3.2-1B (~4 GB, ~30s load)
159
+ - oopere/pruned40-llama-3.2-1B (~4 GB, ~30s load)
160
+ - google/gemma-3-1b-pt (~4 GB, ~30s load)
161
+ - Qwen/Qwen3-1.7B (~6 GB, ~45s load)
162
+
163
+ ⚠️ **May work with optimization**:
164
+ - meta-llama/Llama-3.2-3B (~12 GB, ~90s load)
165
+
166
+ ❌ **Won't work**:
167
+ - meta-llama/Llama-3-8B (~32 GB)
168
+ - meta-llama/Llama-3-70B (~280 GB)
169
+
170
+ ### PRO Tier (32GB RAM)
171
+ βœ… **Additional models**:
172
+ - meta-llama/Llama-3.2-3B
173
+ - meta-llama/Llama-3-8B (with quantization)
174
+
175
+ ### Enterprise Tier (64GB RAM)
176
+ βœ… **Additional models**:
177
+ - meta-llama/Llama-3-8B (full precision)
178
+ - Larger models with quantization
179
+
180
+ ## 🎯 Common Scenarios
181
+
182
+ ### Scenario 1: "My model times out after 5 minutes"
183
+ **Diagnosis**: TIMEOUT_ERROR
184
+
185
+ **Solution**:
186
+ 1. Check if model is too large for your tier
187
+ 2. Increase timeout to 600s (10 minutes)
188
+ 3. Consider pre-loading models at startup
189
+
190
+ ### Scenario 2: "Process crashes without clear error"
191
+ **Diagnosis**: Likely MEMORY_ERROR (Out-Of-Memory kills the process)
192
+
193
+ **Solution**:
194
+ 1. Run `diagnostic_tool.py` to confirm
195
+ 2. Use smaller model (1B parameters)
196
+ 3. Use int8 quantization
197
+ 4. Upgrade to PRO tier
198
+
199
+ ### Scenario 3: "Sometimes works, sometimes doesn't"
200
+ **Diagnosis**: Memory pressure or concurrent requests
201
+
202
+ **Solution**:
203
+ 1. Implement model caching
204
+ 2. Add memory monitoring
205
+ 3. Use smaller default model
206
+
207
+ ## πŸ› οΈ Advanced: Pre-loading Models
208
+
209
+ To avoid timeout on first request, pre-load models at startup:
210
+
211
+ ```python
212
+ # In hf-spaces/app.py
213
+ from transformers import AutoModel, AutoTokenizer
214
+
215
+ MODEL_CACHE = {}
216
+
217
+ def preload_models():
218
+ """Pre-load common models at startup"""
219
+ models = ["meta-llama/Llama-3.2-1B"]
220
+
221
+ for model_name in models:
222
+ try:
223
+ print(f"Pre-loading {model_name}...")
224
+ MODEL_CACHE[model_name] = {
225
+ "model": AutoModel.from_pretrained(
226
+ model_name,
227
+ low_cpu_mem_usage=True
228
+ ),
229
+ "tokenizer": AutoTokenizer.from_pretrained(model_name)
230
+ }
231
+ print(f"βœ“ {model_name} ready")
232
+ except Exception as e:
233
+ print(f"βœ— Could not pre-load {model_name}: {e}")
234
+
235
+ def main():
236
+ preload_models() # Load models before starting services
237
+ # ... rest of startup code
238
+ ```
239
+
240
+ ## πŸ“ž Support
241
+
242
+ If you still have issues after trying these solutions:
243
+
244
+ 1. Check the full diagnostic output
245
+ 2. Review HF Spaces logs
246
+ 3. Verify your HF Spaces tier and limits
247
+ 4. Consider using a different model architecture
248
+
249
+ ## πŸ“ Summary
250
+
251
+ | Issue | Symptom | Solution |
252
+ |-------|---------|----------|
253
+ | **Timeout** | Request > 5 min | Increase timeout, use cache |
254
+ | **Memory** | Process crashes/kills | Smaller model, quantization, upgrade tier |
255
+ | **Both** | Slow + crashes | Smaller model + longer timeout |
256
+
257
+ All tools are designed to help you quickly identify and fix the exact problem without guessing.
config_optimized.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Optimized configuration for HF Spaces with intelligent handling of large models.
3
+ This file contains recommended settings based on available hardware.
4
+ """
5
+
6
+ import os
7
+ from typing import Dict, Any
8
+
9
+
10
+ class HFSpacesConfig:
11
+ """Optimized configuration for different HF Spaces tiers"""
12
+
13
+ # Timeouts (in seconds)
14
+ TIMEOUT_SMALL_MODEL = 120 # Models <2B parameters
15
+ TIMEOUT_MEDIUM_MODEL = 300 # Models 2-5B parameters
16
+ TIMEOUT_LARGE_MODEL = 600 # Models >5B parameters
17
+ TIMEOUT_PING = 5 # Health checks
18
+
19
+ # Recommended memory limits (GB) per HF Spaces tier
20
+ MEMORY_LIMITS = {
21
+ "free": 16, # Free HF Spaces
22
+ "pro": 32, # HF Spaces PRO
23
+ "enterprise": 64 # HF Spaces Enterprise
24
+ }
25
+
26
+ # Recommended models per tier
27
+ RECOMMENDED_MODELS = {
28
+ "free": [
29
+ "meta-llama/Llama-3.2-1B",
30
+ "oopere/pruned40-llama-3.2-1B",
31
+ "oopere/Fair-Llama-3.2-1B",
32
+ "google/gemma-3-1b-pt",
33
+ "Qwen/Qwen3-1.7B",
34
+ ],
35
+ "pro": [
36
+ "meta-llama/Llama-3.2-3B",
37
+ "meta-llama/Llama-3-8B",
38
+ ],
39
+ "enterprise": [
40
+ "meta-llama/Llama-3-70B",
41
+ ]
42
+ }
43
+
44
+ # Model loading configuration
45
+ MODEL_LOAD_CONFIG = {
46
+ "small": { # <2B params
47
+ "low_cpu_mem_usage": True,
48
+ "torch_dtype": "auto",
49
+ "device_map": "auto",
50
+ "timeout": TIMEOUT_SMALL_MODEL,
51
+ },
52
+ "medium": { # 2-8B params
53
+ "low_cpu_mem_usage": True,
54
+ "torch_dtype": "float16", # Reduces memory
55
+ "device_map": "auto",
56
+ "timeout": TIMEOUT_MEDIUM_MODEL,
57
+ },
58
+ "large": { # >8B params
59
+ "low_cpu_mem_usage": True,
60
+ "torch_dtype": "float16",
61
+ "device_map": "auto",
62
+ "load_in_8bit": True, # int8 quantization
63
+ "timeout": TIMEOUT_LARGE_MODEL,
64
+ }
65
+ }
66
+
67
+ @classmethod
68
+ def get_model_size_category(cls, model_name: str) -> str:
69
+ """
70
+ Determines the model size category based on the name.
71
+
72
+ Returns:
73
+ "small", "medium", or "large"
74
+ """
75
+ model_lower = model_name.lower()
76
+
77
+ # Detect by parameters in the name
78
+ if any(size in model_lower for size in ["1b", "1.7b", "1.5b"]):
79
+ return "small"
80
+ elif any(size in model_lower for size in ["3b", "7b", "8b"]):
81
+ return "medium"
82
+ elif any(size in model_lower for size in ["13b", "30b", "70b"]):
83
+ return "large"
84
+
85
+ # Default: small (assume the safest case)
86
+ return "small"
87
+
88
+ @classmethod
89
+ def get_timeout_for_model(cls, model_name: str) -> int:
90
+ """Gets the recommended timeout for a model."""
91
+ size = cls.get_model_size_category(model_name)
92
+ return cls.MODEL_LOAD_CONFIG[size]["timeout"]
93
+
94
+ @classmethod
95
+ def get_load_config(cls, model_name: str) -> Dict[str, Any]:
96
+ """Gets the optimized loading configuration for a model."""
97
+ size = cls.get_model_size_category(model_name)
98
+ return cls.MODEL_LOAD_CONFIG[size].copy()
99
+
100
+ @classmethod
101
+ def is_model_recommended(cls, model_name: str, tier: str = "free") -> bool:
102
+ """Verifies if a model is recommended for the current tier."""
103
+ return model_name in cls.RECOMMENDED_MODELS.get(tier, [])
104
+
105
+ @classmethod
106
+ def get_memory_warning(cls, model_name: str, tier: str = "free") -> str:
107
+ """
108
+ Generates a warning if the model may exceed memory limits.
109
+
110
+ Returns:
111
+ String with warning, or empty string if no problem
112
+ """
113
+ if cls.is_model_recommended(model_name, tier):
114
+ return ""
115
+
116
+ size = cls.get_model_size_category(model_name)
117
+
118
+ if size == "medium" and tier == "free":
119
+ return (
120
+ "⚠️ **Warning**: This model may be too large for free HF Spaces. "
121
+ "Consider upgrading to HF Spaces PRO or using a smaller model."
122
+ )
123
+ elif size == "large" and tier in ["free", "pro"]:
124
+ return (
125
+ "❌ **Error**: This model is too large for your HF Spaces tier. "
126
+ "Use a smaller model or upgrade to Enterprise."
127
+ )
128
+
129
+ return ""
130
+
131
+
132
+ # Usage example:
133
+ def get_optimized_request_config(model_name: str) -> dict:
134
+ """
135
+ Gets optimized configuration for HTTP requests based on the model.
136
+
137
+ Usage:
138
+ config = get_optimized_request_config("meta-llama/Llama-3.2-1B")
139
+ response = requests.post(url, json=payload, **config)
140
+ """
141
+ return {
142
+ "timeout": HFSpacesConfig.get_timeout_for_model(model_name),
143
+ }
144
+
145
+
146
+ # Default configuration for general use
147
+ DEFAULT_CONFIG = {
148
+ "timeout": HFSpacesConfig.TIMEOUT_MEDIUM_MODEL,
149
+ "max_retries": 2,
150
+ "retry_delay": 5, # seconds between retries
151
+ }
152
+
153
+
154
+ if __name__ == "__main__":
155
+ # Usage examples
156
+ print("πŸ”§ Optimized configuration for HF Spaces\n")
157
+
158
+ test_models = [
159
+ "meta-llama/Llama-3.2-1B",
160
+ "meta-llama/Llama-3.2-3B",
161
+ "meta-llama/Llama-3-8B",
162
+ ]
163
+
164
+ for model in test_models:
165
+ print(f"πŸ“¦ Model: {model}")
166
+ print(f" Category: {HFSpacesConfig.get_model_size_category(model)}")
167
+ print(f" Timeout: {HFSpacesConfig.get_timeout_for_model(model)}s")
168
+ print(f" Recommended (free): {HFSpacesConfig.is_model_recommended(model, 'free')}")
169
+
170
+ warning = HFSpacesConfig.get_memory_warning(model, "free")
171
+ if warning:
172
+ print(f" {warning}")
173
+ print()
diagnostic_tool.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Diagnostic tool to identify timeout vs memory issues in HF Spaces.
3
+ Run this script in HF Spaces to get detailed performance information.
4
+ """
5
+
6
+ import psutil
7
+ import time
8
+ import sys
9
+ import traceback
10
+ from datetime import datetime
11
+
12
+
13
+ def get_memory_info():
14
+ """Gets detailed information about system memory usage."""
15
+ memory = psutil.virtual_memory()
16
+ return {
17
+ "total_gb": memory.total / (1024**3),
18
+ "available_gb": memory.available / (1024**3),
19
+ "used_gb": memory.used / (1024**3),
20
+ "percent_used": memory.percent,
21
+ "free_gb": memory.free / (1024**3),
22
+ }
23
+
24
+
25
+ def get_cpu_info():
26
+ """Gets information about CPU usage."""
27
+ return {
28
+ "cpu_percent": psutil.cpu_percent(interval=1),
29
+ "cpu_count": psutil.cpu_count(),
30
+ "load_avg": psutil.getloadavg() if hasattr(psutil, "getloadavg") else None,
31
+ }
32
+
33
+
34
+ def monitor_model_loading(model_name: str, timeout_seconds: int = 300):
35
+ """
36
+ Monitors model loading and detects if it fails due to timeout or memory.
37
+
38
+ Args:
39
+ model_name: HuggingFace model name to load
40
+ timeout_seconds: Maximum wait time in seconds
41
+
42
+ Returns:
43
+ dict with diagnostic information
44
+ """
45
+ print(f"\n{'='*60}")
46
+ print(f"πŸ” MODEL LOADING DIAGNOSTIC: {model_name}")
47
+ print(f"{'='*60}\n")
48
+
49
+ # Initial system state
50
+ print("πŸ“Š INITIAL SYSTEM STATE:")
51
+ mem_before = get_memory_info()
52
+ cpu_before = get_cpu_info()
53
+ print(f" - Available memory: {mem_before['available_gb']:.2f} GB")
54
+ print(f" - Used memory: {mem_before['used_gb']:.2f} GB ({mem_before['percent_used']:.1f}%)")
55
+ print(f" - Available CPUs: {cpu_before['cpu_count']} cores")
56
+ print(f" - CPU usage: {cpu_before['cpu_percent']:.1f}%")
57
+
58
+ start_time = time.time()
59
+ result = {
60
+ "model_name": model_name,
61
+ "success": False,
62
+ "error_type": None,
63
+ "error_message": None,
64
+ "elapsed_time": 0,
65
+ "memory_before": mem_before,
66
+ "memory_after": None,
67
+ "memory_peak": mem_before["used_gb"],
68
+ "timeout_seconds": timeout_seconds,
69
+ }
70
+
71
+ try:
72
+ print(f"\n⏳ Starting model loading (timeout: {timeout_seconds}s)...")
73
+ print(f" Start time: {datetime.now().strftime('%H:%M:%S')}")
74
+
75
+ # Import transformers here to measure its impact
76
+ from transformers import AutoModel, AutoTokenizer
77
+
78
+ # Real-time monitoring
79
+ model = None
80
+ tokenizer = None
81
+ last_memory_check = time.time()
82
+
83
+ print("\nπŸ“ˆ REAL-TIME MONITORING:")
84
+
85
+ # Load tokenizer first (faster)
86
+ print(" [1/2] Loading tokenizer...")
87
+ tokenizer_start = time.time()
88
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
89
+ tokenizer_time = time.time() - tokenizer_start
90
+ print(f" βœ“ Tokenizer loaded in {tokenizer_time:.2f}s")
91
+
92
+ # Check memory after tokenizer
93
+ mem_after_tokenizer = get_memory_info()
94
+ print(f" - Memory used: {mem_after_tokenizer['used_gb']:.2f} GB ({mem_after_tokenizer['percent_used']:.1f}%)")
95
+
96
+ # Load model (can be slow)
97
+ print("\n [2/2] Loading model...")
98
+ model_start = time.time()
99
+
100
+ # Load with low memory usage if possible
101
+ model = AutoModel.from_pretrained(
102
+ model_name,
103
+ low_cpu_mem_usage=True, # Reduces memory usage during loading
104
+ torch_dtype="auto",
105
+ )
106
+
107
+ model_time = time.time() - model_start
108
+ total_time = time.time() - start_time
109
+
110
+ print(f" βœ“ Model loaded in {model_time:.2f}s")
111
+ print(f"\nβœ… LOADING SUCCESSFUL in {total_time:.2f}s")
112
+
113
+ # Final system state
114
+ mem_after = get_memory_info()
115
+ cpu_after = get_cpu_info()
116
+
117
+ print(f"\nπŸ“Š FINAL SYSTEM STATE:")
118
+ print(f" - Available memory: {mem_after['available_gb']:.2f} GB")
119
+ print(f" - Used memory: {mem_after['used_gb']:.2f} GB ({mem_after['percent_used']:.1f}%)")
120
+ print(f" - Memory increase: {mem_after['used_gb'] - mem_before['used_gb']:.2f} GB")
121
+ print(f" - CPU usage: {cpu_after['cpu_percent']:.1f}%")
122
+
123
+ result["success"] = True
124
+ result["elapsed_time"] = total_time
125
+ result["memory_after"] = mem_after
126
+ result["tokenizer_time"] = tokenizer_time
127
+ result["model_time"] = model_time
128
+
129
+ except MemoryError as e:
130
+ elapsed = time.time() - start_time
131
+ mem_current = get_memory_info()
132
+
133
+ print(f"\n❌ MEMORY ERROR after {elapsed:.2f}s")
134
+ print(f" Memory used at failure: {mem_current['used_gb']:.2f} GB ({mem_current['percent_used']:.1f}%)")
135
+
136
+ result["error_type"] = "MEMORY_ERROR"
137
+ result["error_message"] = str(e)
138
+ result["elapsed_time"] = elapsed
139
+ result["memory_after"] = mem_current
140
+
141
+ except TimeoutError as e:
142
+ elapsed = time.time() - start_time
143
+ mem_current = get_memory_info()
144
+
145
+ print(f"\n⏰ TIMEOUT ERROR after {elapsed:.2f}s")
146
+ print(f" Memory used: {mem_current['used_gb']:.2f} GB ({mem_current['percent_used']:.1f}%)")
147
+
148
+ result["error_type"] = "TIMEOUT_ERROR"
149
+ result["error_message"] = str(e)
150
+ result["elapsed_time"] = elapsed
151
+ result["memory_after"] = mem_current
152
+
153
+ except Exception as e:
154
+ elapsed = time.time() - start_time
155
+ mem_current = get_memory_info()
156
+
157
+ print(f"\n❌ UNEXPECTED ERROR after {elapsed:.2f}s")
158
+ print(f" Type: {type(e).__name__}")
159
+ print(f" Message: {str(e)}")
160
+ print(f" Memory used: {mem_current['used_gb']:.2f} GB ({mem_current['percent_used']:.1f}%)")
161
+
162
+ # Analyze error message to detect memory issues
163
+ error_msg = str(e).lower()
164
+ if any(keyword in error_msg for keyword in ["memory", "ram", "oom", "out of memory"]):
165
+ result["error_type"] = "MEMORY_ERROR"
166
+ print("\nπŸ” DIAGNOSIS: Error appears to be MEMORY related")
167
+ elif "timeout" in error_msg or elapsed >= timeout_seconds * 0.95:
168
+ result["error_type"] = "TIMEOUT_ERROR"
169
+ print("\nπŸ” DIAGNOSIS: Error appears to be TIMEOUT related")
170
+ else:
171
+ result["error_type"] = "OTHER_ERROR"
172
+
173
+ result["error_message"] = str(e)
174
+ result["elapsed_time"] = elapsed
175
+ result["memory_after"] = mem_current
176
+ result["traceback"] = traceback.format_exc()
177
+
178
+ return result
179
+
180
+
181
+ def print_recommendations(result: dict):
182
+ """Prints recommendations based on diagnostic results."""
183
+ print(f"\n{'='*60}")
184
+ print("πŸ’‘ RECOMMENDATIONS")
185
+ print(f"{'='*60}\n")
186
+
187
+ if result["success"]:
188
+ print("βœ… Model loaded successfully.")
189
+ print(f" Total time: {result['elapsed_time']:.2f}s")
190
+
191
+ if result["elapsed_time"] > 240: # > 4 minutes
192
+ print("\n⚠️ Warning: Load time is very high (>4min)")
193
+ print(" - Consider increasing timeout to 600s (10 minutes)")
194
+ print(" - Or use a smaller model")
195
+
196
+ elif result["error_type"] == "MEMORY_ERROR":
197
+ print("❌ PROBLEM DETECTED: OUT OF MEMORY\n")
198
+ print("Solutions:")
199
+ print(" 1. Use a smaller model (1B or 1.7B parameters)")
200
+ print(" 2. Request more memory in HF Spaces (PRO plan)")
201
+ print(" 3. Use quantization (int8 or int4) to reduce memory usage:")
202
+ print(" ```python")
203
+ print(" from transformers import BitsAndBytesConfig")
204
+ print(" quantization_config = BitsAndBytesConfig(load_in_8bit=True)")
205
+ print(" model = AutoModel.from_pretrained(model_name, quantization_config=quantization_config)")
206
+ print(" ```")
207
+
208
+ if result["memory_after"]:
209
+ print(f"\n Available memory: {result['memory_after']['available_gb']:.2f} GB")
210
+ print(f" More memory needed for this model")
211
+
212
+ elif result["error_type"] == "TIMEOUT_ERROR":
213
+ print("❌ PROBLEM DETECTED: TIMEOUT\n")
214
+ print("Solutions:")
215
+ print(f" 1. Increase timeout from {result['timeout_seconds']}s to 600s (10 minutes):")
216
+ print(" ```python")
217
+ print(" response = requests.post(url, json=payload, timeout=600)")
218
+ print(" ```")
219
+ print(" 2. Implement async loading with progress updates")
220
+ print(" 3. Cache pre-loaded models in HF Spaces")
221
+ print(" 4. Use smaller models that load faster")
222
+
223
+ else:
224
+ print("❌ PROBLEM DETECTED: UNEXPECTED ERROR\n")
225
+ print("Review the full traceback for more details")
226
+ if "traceback" in result:
227
+ print("\n" + result["traceback"])
228
+
229
+ print(f"\n{'='*60}\n")
230
+
231
+
232
+ if __name__ == "__main__":
233
+ # Models to test (from smallest to largest)
234
+ test_models = [
235
+ "meta-llama/Llama-3.2-1B", # Small model
236
+ # "meta-llama/Llama-3.2-3B", # Medium model (uncomment to test)
237
+ # "meta-llama/Llama-3-8B", # Large model (uncomment to test)
238
+ ]
239
+
240
+ # You can change the timeout here
241
+ TIMEOUT = 300 # 5 minutes
242
+
243
+ results = []
244
+
245
+ for model_name in test_models:
246
+ result = monitor_model_loading(model_name, timeout_seconds=TIMEOUT)
247
+ results.append(result)
248
+ print_recommendations(result)
249
+
250
+ # If failed, don't test larger models
251
+ if not result["success"]:
252
+ print("\n⚠️ Stopping tests due to error.")
253
+ print(" Larger models will likely fail as well.")
254
+ break
255
+
256
+ # Wait a bit between tests
257
+ time.sleep(2)
258
+
259
+ # Final summary
260
+ print(f"\n{'='*60}")
261
+ print("πŸ“‹ TEST SUMMARY")
262
+ print(f"{'='*60}\n")
263
+
264
+ for i, result in enumerate(results, 1):
265
+ status = "βœ…" if result["success"] else "❌"
266
+ time_str = f"{result['elapsed_time']:.1f}s"
267
+ print(f"{status} Test {i}: {result['model_name']}")
268
+ print(f" Time: {time_str} | Error: {result['error_type'] or 'None'}")
269
+
270
+ print()