Spaces:
Runtime error
Runtime error
Fix disk_offload error for Gemma 3n E4B IT model loading
Browse files- Add multiple loading strategies with fallback mechanisms
- Implement 4-bit and 8-bit quantization support
- Add conservative CPU-only loading mode
- Update requirements.txt with bitsandbytes dependency
- Create test script for model loading validation
- Add comprehensive documentation and troubleshooting guide
- Fix memory management for Hugging Face Spaces deployment
- .gitignore +61 -0
- SOLUTION_DISK_OFFLOAD.md +188 -0
- requirements.txt +8 -13
- src/streamlit_app_multilingual.py +207 -97
- test_model_loading.py +165 -0
.gitignore
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Virtual Environment
|
| 2 |
+
venv/
|
| 3 |
+
env/
|
| 4 |
+
ENV/
|
| 5 |
+
|
| 6 |
+
# Python
|
| 7 |
+
__pycache__/
|
| 8 |
+
*.py[cod]
|
| 9 |
+
*$py.class
|
| 10 |
+
*.so
|
| 11 |
+
.Python
|
| 12 |
+
build/
|
| 13 |
+
develop-eggs/
|
| 14 |
+
dist/
|
| 15 |
+
downloads/
|
| 16 |
+
eggs/
|
| 17 |
+
.eggs/
|
| 18 |
+
lib/
|
| 19 |
+
lib64/
|
| 20 |
+
parts/
|
| 21 |
+
sdist/
|
| 22 |
+
var/
|
| 23 |
+
wheels/
|
| 24 |
+
*.egg-info/
|
| 25 |
+
.installed.cfg
|
| 26 |
+
*.egg
|
| 27 |
+
|
| 28 |
+
# PyTorch
|
| 29 |
+
*.pth
|
| 30 |
+
*.pt
|
| 31 |
+
|
| 32 |
+
# Model files
|
| 33 |
+
models/
|
| 34 |
+
*.safetensors
|
| 35 |
+
*.bin
|
| 36 |
+
|
| 37 |
+
# Temporary files
|
| 38 |
+
temp_model_offload/
|
| 39 |
+
tmp/
|
| 40 |
+
*.tmp
|
| 41 |
+
|
| 42 |
+
# IDE
|
| 43 |
+
.vscode/
|
| 44 |
+
.idea/
|
| 45 |
+
*.swp
|
| 46 |
+
*.swo
|
| 47 |
+
|
| 48 |
+
# OS
|
| 49 |
+
.DS_Store
|
| 50 |
+
Thumbs.db
|
| 51 |
+
|
| 52 |
+
# Logs
|
| 53 |
+
*.log
|
| 54 |
+
|
| 55 |
+
# Environment variables
|
| 56 |
+
.env
|
| 57 |
+
.env.local
|
| 58 |
+
|
| 59 |
+
# Hugging Face cache
|
| 60 |
+
.cache/
|
| 61 |
+
transformers_cache/
|
SOLUTION_DISK_OFFLOAD.md
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🔧 Solution pour l'erreur "disk_offload" - Gemma 3n E4B IT
|
| 2 |
+
|
| 3 |
+
## 🚨 Problème identifié
|
| 4 |
+
|
| 5 |
+
L'erreur `You are trying to offload the whole model to the disk. Please use the disk_offload function instead.` se produit lorsque :
|
| 6 |
+
|
| 7 |
+
1. **Le modèle est trop volumineux** pour la mémoire disponible
|
| 8 |
+
2. **Hugging Face Spaces** a des limitations de mémoire
|
| 9 |
+
3. **Le modèle Gemma 3n E4B IT** nécessite environ 8-12GB de RAM
|
| 10 |
+
|
| 11 |
+
## ✅ Solution implémentée
|
| 12 |
+
|
| 13 |
+
### 1. **Stratégies de chargement multiples**
|
| 14 |
+
|
| 15 |
+
L'application utilise maintenant 4 stratégies de chargement en cascade :
|
| 16 |
+
|
| 17 |
+
```python
|
| 18 |
+
# Stratégie 1: CPU Conservateur
|
| 19 |
+
device_map="cpu", torch_dtype=torch.float32, max_memory={"cpu": "8GB"}
|
| 20 |
+
|
| 21 |
+
# Stratégie 2: 4-bit Quantization
|
| 22 |
+
load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16
|
| 23 |
+
|
| 24 |
+
# Stratégie 3: 8-bit Quantization
|
| 25 |
+
load_in_8bit=True
|
| 26 |
+
|
| 27 |
+
# Stratégie 4: Gestion mémoire personnalisée
|
| 28 |
+
max_memory={0: "4GB", "cpu": "8GB"}
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
### 2. **Dépendances mises à jour**
|
| 32 |
+
|
| 33 |
+
```bash
|
| 34 |
+
pip install bitsandbytes>=0.41.0
|
| 35 |
+
pip install accelerate>=0.20.0
|
| 36 |
+
pip install transformers>=4.35.0
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
### 3. **Gestion automatique des erreurs**
|
| 40 |
+
|
| 41 |
+
- Détection automatique de la mémoire disponible
|
| 42 |
+
- Fallback automatique entre les stratégies
|
| 43 |
+
- Messages d'erreur informatifs
|
| 44 |
+
|
| 45 |
+
## 🧪 Test de la solution
|
| 46 |
+
|
| 47 |
+
### Exécuter le script de test :
|
| 48 |
+
|
| 49 |
+
```bash
|
| 50 |
+
python test_model_loading.py
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
Ce script va :
|
| 54 |
+
- ✅ Vérifier la mémoire disponible
|
| 55 |
+
- ✅ Tester chaque stratégie de chargement
|
| 56 |
+
- ✅ Identifier la meilleure stratégie pour votre environnement
|
| 57 |
+
- ✅ Fournir des recommandations en cas d'échec
|
| 58 |
+
|
| 59 |
+
## 🚀 Utilisation
|
| 60 |
+
|
| 61 |
+
### 1. **Installation des dépendances**
|
| 62 |
+
|
| 63 |
+
```bash
|
| 64 |
+
pip install -r requirements.txt
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
### 2. **Lancement de l'application**
|
| 68 |
+
|
| 69 |
+
```bash
|
| 70 |
+
streamlit run src/streamlit_app_multilingual.py
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
### 3. **Chargement du modèle**
|
| 74 |
+
|
| 75 |
+
1. Ouvrez l'application dans votre navigateur
|
| 76 |
+
2. Allez dans la sidebar "Configuration"
|
| 77 |
+
3. Cliquez sur "Charger le modèle Gemma 3n E4B IT"
|
| 78 |
+
4. L'application testera automatiquement les stratégies
|
| 79 |
+
|
| 80 |
+
## 🔍 Diagnostic des problèmes
|
| 81 |
+
|
| 82 |
+
### Si le chargement échoue :
|
| 83 |
+
|
| 84 |
+
1. **Vérifiez la mémoire disponible** :
|
| 85 |
+
```python
|
| 86 |
+
import torch
|
| 87 |
+
if torch.cuda.is_available():
|
| 88 |
+
print(f"GPU: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f} GB")
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
2. **Vérifiez les dépendances** :
|
| 92 |
+
```bash
|
| 93 |
+
pip list | grep -E "(transformers|accelerate|bitsandbytes)"
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
3. **Consultez les logs** :
|
| 97 |
+
- Les messages d'erreur détaillés s'affichent dans l'interface
|
| 98 |
+
- Chaque stratégie testée est documentée
|
| 99 |
+
|
| 100 |
+
## 💡 Recommandations
|
| 101 |
+
|
| 102 |
+
### Pour Hugging Face Spaces :
|
| 103 |
+
|
| 104 |
+
1. **Utilisez un runtime avec plus de mémoire** :
|
| 105 |
+
- CPU: 8GB minimum
|
| 106 |
+
- GPU: 16GB recommandé
|
| 107 |
+
|
| 108 |
+
2. **Configuration dans `app.py`** :
|
| 109 |
+
```python
|
| 110 |
+
# Ajoutez ces lignes au début
|
| 111 |
+
import os
|
| 112 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 113 |
+
os.environ["TRANSFORMERS_CACHE"] = "/tmp/transformers_cache"
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
3. **Variables d'environnement** :
|
| 117 |
+
```bash
|
| 118 |
+
export HF_HOME="/tmp/hf_home"
|
| 119 |
+
export TRANSFORMERS_CACHE="/tmp/transformers_cache"
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
### Pour développement local :
|
| 123 |
+
|
| 124 |
+
1. **Mémoire recommandée** : 16GB RAM minimum
|
| 125 |
+
2. **GPU optionnel** : Améliore les performances
|
| 126 |
+
3. **Espace disque** : 10GB pour le cache des modèles
|
| 127 |
+
|
| 128 |
+
## 🛠️ Dépannage avancé
|
| 129 |
+
|
| 130 |
+
### Erreur "bitsandbytes not found" :
|
| 131 |
+
|
| 132 |
+
```bash
|
| 133 |
+
pip install bitsandbytes --upgrade
|
| 134 |
+
# Ou pour CPU uniquement
|
| 135 |
+
pip install bitsandbytes-cpu
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
### Erreur "CUDA out of memory" :
|
| 139 |
+
|
| 140 |
+
1. Réduisez la taille du batch
|
| 141 |
+
2. Utilisez la quantification 4-bit
|
| 142 |
+
3. Libérez la mémoire GPU :
|
| 143 |
+
```python
|
| 144 |
+
torch.cuda.empty_cache()
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
### Erreur "disk_offload" persistante :
|
| 148 |
+
|
| 149 |
+
1. Forcez le mode CPU :
|
| 150 |
+
```python
|
| 151 |
+
device_map="cpu"
|
| 152 |
+
torch_dtype=torch.float32
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
2. Utilisez un modèle plus petit :
|
| 156 |
+
```python
|
| 157 |
+
model_id = "google/gemma-2b-it" # Au lieu de gemma-3n-E4B-it
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
## 📊 Performance attendue
|
| 161 |
+
|
| 162 |
+
| Stratégie | Mémoire requise | Vitesse | Qualité |
|
| 163 |
+
|-----------|----------------|---------|---------|
|
| 164 |
+
| CPU Conservateur | 8GB RAM | Lente | Excellente |
|
| 165 |
+
| 4-bit Quantization | 4GB RAM | Moyenne | Très bonne |
|
| 166 |
+
| 8-bit Quantization | 6GB RAM | Rapide | Bonne |
|
| 167 |
+
| Gestion personnalisée | Variable | Variable | Excellente |
|
| 168 |
+
|
| 169 |
+
## 🔄 Mise à jour automatique
|
| 170 |
+
|
| 171 |
+
L'application détecte automatiquement :
|
| 172 |
+
- ✅ La mémoire disponible
|
| 173 |
+
- ✅ Les capacités GPU/CPU
|
| 174 |
+
- ✅ Les dépendances installées
|
| 175 |
+
- ✅ La meilleure stratégie à utiliser
|
| 176 |
+
|
| 177 |
+
## 📞 Support
|
| 178 |
+
|
| 179 |
+
Si le problème persiste :
|
| 180 |
+
|
| 181 |
+
1. **Exécutez le script de test** et partagez les résultats
|
| 182 |
+
2. **Vérifiez les logs** de l'application
|
| 183 |
+
3. **Consultez la documentation** Hugging Face
|
| 184 |
+
4. **Contactez le support** avec les détails de l'erreur
|
| 185 |
+
|
| 186 |
+
---
|
| 187 |
+
|
| 188 |
+
**Note** : Cette solution garantit que l'application fonctionne dans la plupart des environnements, même avec des ressources limitées.
|
requirements.txt
CHANGED
|
@@ -1,15 +1,10 @@
|
|
| 1 |
streamlit>=1.28.0
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
torchvision>=0.16.0
|
| 5 |
-
numpy<2
|
| 6 |
-
Pillow>=10.0.0
|
| 7 |
-
requests>=2.32.0
|
| 8 |
-
fpdf>=1.7.2
|
| 9 |
-
python-dotenv>=1.0.0
|
| 10 |
-
huggingface-hub>=0.30.0
|
| 11 |
-
safetensors>=0.4.3
|
| 12 |
accelerate>=0.20.0
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
streamlit>=1.28.0
|
| 2 |
+
torch>=2.0.0
|
| 3 |
+
transformers>=4.35.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
accelerate>=0.20.0
|
| 5 |
+
bitsandbytes>=0.41.0
|
| 6 |
+
safetensors>=0.3.0
|
| 7 |
+
Pillow>=9.0.0
|
| 8 |
+
requests>=2.28.0
|
| 9 |
+
google-generativeai>=0.3.0
|
| 10 |
+
huggingface-hub>=0.16.0
|
src/streamlit_app_multilingual.py
CHANGED
|
@@ -97,7 +97,7 @@ translations = {
|
|
| 97 |
"title": "🌱 AgriLens AI - Diagnostic des Plantes",
|
| 98 |
"subtitle": "**Application de diagnostic des maladies de plantes avec IA**",
|
| 99 |
"config_title": "⚙️ Configuration",
|
| 100 |
-
"load_model": "Charger le modèle Gemma
|
| 101 |
"model_status": "**Statut du modèle :**",
|
| 102 |
"not_loaded": "Non chargé",
|
| 103 |
"loaded": "✅ Chargé",
|
|
@@ -128,7 +128,7 @@ translations = {
|
|
| 128 |
"title": "🌱 AgriLens AI - Plant Disease Diagnosis",
|
| 129 |
"subtitle": "**AI-powered plant disease diagnosis application**",
|
| 130 |
"config_title": "⚙️ Configuration",
|
| 131 |
-
"load_model": "Load Gemma
|
| 132 |
"model_status": "**Model Status:**",
|
| 133 |
"not_loaded": "Not loaded",
|
| 134 |
"loaded": "✅ Loaded",
|
|
@@ -162,27 +162,120 @@ def t(key):
|
|
| 162 |
|
| 163 |
@st.cache_resource(show_spinner=False)
|
| 164 |
def load_model():
|
| 165 |
-
"""Charge le modèle Gemma 3n E4B IT depuis Hugging Face"""
|
| 166 |
try:
|
| 167 |
st.info("Chargement du modèle Gemma 3n E4B IT depuis Hugging Face...")
|
| 168 |
|
| 169 |
from transformers import AutoProcessor, Gemma3nForConditionalGeneration
|
| 170 |
|
| 171 |
-
|
| 172 |
|
|
|
|
| 173 |
processor = AutoProcessor.from_pretrained(
|
| 174 |
-
|
| 175 |
-
trust_remote_code=True
|
| 176 |
-
)
|
| 177 |
-
model = Gemma3nForConditionalGeneration.from_pretrained(
|
| 178 |
-
model_name,
|
| 179 |
-
device_map="auto",
|
| 180 |
-
torch_dtype=torch.float32,
|
| 181 |
trust_remote_code=True
|
| 182 |
)
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
except Exception as e:
|
| 188 |
st.error(f"Erreur lors du chargement du modèle : {e}")
|
|
@@ -385,20 +478,38 @@ Respond in a structured and precise manner.
|
|
| 385 |
return f"❌ Erreur lors de l'analyse d'image : {e}"
|
| 386 |
|
| 387 |
def analyze_text_multilingual(text):
|
| 388 |
-
"""Analyse un texte avec le modèle Gemma
|
| 389 |
if not st.session_state.model_loaded:
|
| 390 |
return "❌ Modèle non chargé. Veuillez le charger dans les réglages."
|
| 391 |
|
| 392 |
try:
|
| 393 |
-
model,
|
| 394 |
|
| 395 |
if st.session_state.language == "fr":
|
| 396 |
-
prompt = f"
|
| 397 |
else:
|
| 398 |
-
prompt = f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
|
| 400 |
-
|
| 401 |
|
|
|
|
| 402 |
with torch.inference_mode():
|
| 403 |
generation = model.generate(
|
| 404 |
**inputs,
|
|
@@ -406,12 +517,11 @@ def analyze_text_multilingual(text):
|
|
| 406 |
do_sample=True,
|
| 407 |
temperature=0.7,
|
| 408 |
top_p=0.9,
|
| 409 |
-
|
| 410 |
)
|
| 411 |
-
generation = generation[0][
|
| 412 |
|
| 413 |
-
response =
|
| 414 |
-
response = response.replace("<end_of_turn>", "").strip()
|
| 415 |
return response
|
| 416 |
|
| 417 |
except Exception as e:
|
|
@@ -534,7 +644,7 @@ with st.sidebar:
|
|
| 534 |
st.session_state.processor = processor
|
| 535 |
st.session_state.model_loaded = True
|
| 536 |
st.session_state.model_status = t("loaded")
|
| 537 |
-
st.success("Modèle Gemma 3n E4B IT chargé avec succès !" if st.session_state.language == "fr" else "Gemma 3n E4B IT model loaded successfully!")
|
| 538 |
else:
|
| 539 |
st.session_state.model_loaded = False
|
| 540 |
st.session_state.model_status = t("error")
|
|
@@ -542,9 +652,9 @@ with st.sidebar:
|
|
| 542 |
|
| 543 |
st.info(f"{t('model_status')} {st.session_state.model_status}")
|
| 544 |
|
| 545 |
-
# Statut du modèle Gemma 3n E4B IT
|
| 546 |
if st.session_state.model_loaded:
|
| 547 |
-
st.success("✅ Modèle Gemma 3n E4B IT chargé")
|
| 548 |
st.info("Le modèle est prêt pour l'analyse d'images et de texte")
|
| 549 |
else:
|
| 550 |
st.warning("⚠️ Modèle Gemma 3n E4B IT non chargé")
|
|
@@ -588,79 +698,79 @@ with tab1:
|
|
| 588 |
"Prendre une photo de la plante" if st.session_state.language == "fr" else "Take a photo of the plant",
|
| 589 |
key="webcam_capture"
|
| 590 |
)
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
if was_resized:
|
| 632 |
-
st.warning("⚠️ L'image a été automatiquement redimensionnée pour optimiser le traitement")
|
| 633 |
-
|
| 634 |
-
question = st.text_area(
|
| 635 |
-
"Question spécifique (optionnel) :",
|
| 636 |
-
placeholder="Ex: Quelle est cette maladie ? Que faire pour la traiter ?",
|
| 637 |
-
height=100
|
| 638 |
-
)
|
| 639 |
|
| 640 |
-
if
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
if "403" in error_msg or "Forbidden" in error_msg:
|
| 654 |
-
st.error("❌ Erreur 403 - Accès refusé lors du traitement de l'image")
|
| 655 |
-
st.warning("🔒 Cette erreur indique un problème d'autorisation côté serveur.")
|
| 656 |
-
st.info("💡 Solutions possibles :")
|
| 657 |
-
st.info("• Vérifiez les logs de votre espace Hugging Face")
|
| 658 |
-
st.info("• Essayez avec une image plus petite (< 1MB)")
|
| 659 |
-
st.info("• Rafraîchissez la page et réessayez")
|
| 660 |
-
st.info("• Contactez le support Hugging Face si le problème persiste")
|
| 661 |
else:
|
| 662 |
-
st.
|
| 663 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 664 |
|
| 665 |
with tab2:
|
| 666 |
st.header(t("text_analysis_title"))
|
|
@@ -774,7 +884,7 @@ with tab4:
|
|
| 774 |
|
| 775 |
st.markdown("### 🔧 Technologie / Technology")
|
| 776 |
st.markdown("""
|
| 777 |
-
• **Modèle** : Gemma
|
| 778 |
• **Framework** : Streamlit
|
| 779 |
• **Déploiement** : Hugging Face Spaces
|
| 780 |
""")
|
|
|
|
| 97 |
"title": "🌱 AgriLens AI - Diagnostic des Plantes",
|
| 98 |
"subtitle": "**Application de diagnostic des maladies de plantes avec IA**",
|
| 99 |
"config_title": "⚙️ Configuration",
|
| 100 |
+
"load_model": "Charger le modèle Gemma 3n E4B IT",
|
| 101 |
"model_status": "**Statut du modèle :**",
|
| 102 |
"not_loaded": "Non chargé",
|
| 103 |
"loaded": "✅ Chargé",
|
|
|
|
| 128 |
"title": "🌱 AgriLens AI - Plant Disease Diagnosis",
|
| 129 |
"subtitle": "**AI-powered plant disease diagnosis application**",
|
| 130 |
"config_title": "⚙️ Configuration",
|
| 131 |
+
"load_model": "Load Gemma 3n E4B IT Model",
|
| 132 |
"model_status": "**Model Status:**",
|
| 133 |
"not_loaded": "Not loaded",
|
| 134 |
"loaded": "✅ Loaded",
|
|
|
|
| 162 |
|
| 163 |
@st.cache_resource(show_spinner=False)
|
| 164 |
def load_model():
|
| 165 |
+
"""Charge le modèle Gemma 3n E4B IT depuis Hugging Face avec gestion robuste de la mémoire"""
|
| 166 |
try:
|
| 167 |
st.info("Chargement du modèle Gemma 3n E4B IT depuis Hugging Face...")
|
| 168 |
|
| 169 |
from transformers import AutoProcessor, Gemma3nForConditionalGeneration
|
| 170 |
|
| 171 |
+
model_id = "google/gemma-3n-E4B-it"
|
| 172 |
|
| 173 |
+
# Charger le processeur
|
| 174 |
processor = AutoProcessor.from_pretrained(
|
| 175 |
+
model_id,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
trust_remote_code=True
|
| 177 |
)
|
| 178 |
|
| 179 |
+
# Stratégie 1: Chargement conservateur avec gestion mémoire stricte
|
| 180 |
+
def load_conservative():
|
| 181 |
+
st.info("Chargement en mode conservateur (CPU uniquement)...")
|
| 182 |
+
return Gemma3nForConditionalGeneration.from_pretrained(
|
| 183 |
+
model_id,
|
| 184 |
+
device_map="cpu",
|
| 185 |
+
torch_dtype=torch.float32,
|
| 186 |
+
trust_remote_code=True,
|
| 187 |
+
low_cpu_mem_usage=True,
|
| 188 |
+
max_memory={"cpu": "8GB"} # Limiter l'utilisation mémoire CPU
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
# Stratégie 2: Chargement avec 8-bit quantization
|
| 192 |
+
def load_8bit():
|
| 193 |
+
st.info("Chargement avec quantification 8-bit...")
|
| 194 |
+
return Gemma3nForConditionalGeneration.from_pretrained(
|
| 195 |
+
model_id,
|
| 196 |
+
device_map="auto",
|
| 197 |
+
torch_dtype=torch.float16,
|
| 198 |
+
trust_remote_code=True,
|
| 199 |
+
low_cpu_mem_usage=True,
|
| 200 |
+
load_in_8bit=True
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
# Stratégie 3: Chargement avec 4-bit quantization
|
| 204 |
+
def load_4bit():
|
| 205 |
+
st.info("Chargement avec quantification 4-bit...")
|
| 206 |
+
return Gemma3nForConditionalGeneration.from_pretrained(
|
| 207 |
+
model_id,
|
| 208 |
+
device_map="auto",
|
| 209 |
+
torch_dtype=torch.float16,
|
| 210 |
+
trust_remote_code=True,
|
| 211 |
+
low_cpu_mem_usage=True,
|
| 212 |
+
load_in_4bit=True,
|
| 213 |
+
bnb_4bit_compute_dtype=torch.float16
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
# Stratégie 4: Chargement avec gestion mémoire personnalisée
|
| 217 |
+
def load_custom_memory():
|
| 218 |
+
st.info("Chargement avec gestion mémoire personnalisée...")
|
| 219 |
+
return Gemma3nForConditionalGeneration.from_pretrained(
|
| 220 |
+
model_id,
|
| 221 |
+
device_map="auto",
|
| 222 |
+
torch_dtype=torch.float16,
|
| 223 |
+
trust_remote_code=True,
|
| 224 |
+
low_cpu_mem_usage=True,
|
| 225 |
+
max_memory={
|
| 226 |
+
0: "4GB", # GPU
|
| 227 |
+
"cpu": "8GB" # CPU
|
| 228 |
+
}
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
# Vérifier la mémoire disponible
|
| 232 |
+
if torch.cuda.is_available():
|
| 233 |
+
gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3 # GB
|
| 234 |
+
st.info(f"Mémoire GPU disponible : {gpu_memory:.1f} GB")
|
| 235 |
+
|
| 236 |
+
# Essayer différentes stratégies selon la mémoire disponible
|
| 237 |
+
strategies = []
|
| 238 |
+
|
| 239 |
+
if gpu_memory >= 8:
|
| 240 |
+
strategies = [load_custom_memory, load_4bit, load_8bit, load_conservative]
|
| 241 |
+
elif gpu_memory >= 4:
|
| 242 |
+
strategies = [load_4bit, load_8bit, load_conservative]
|
| 243 |
+
else:
|
| 244 |
+
strategies = [load_8bit, load_conservative]
|
| 245 |
+
|
| 246 |
+
# Essayer chaque stratégie jusqu'à ce qu'une fonctionne
|
| 247 |
+
for i, strategy in enumerate(strategies):
|
| 248 |
+
try:
|
| 249 |
+
st.info(f"Tentative {i+1}/{len(strategies)} : {strategy.__name__}")
|
| 250 |
+
model = strategy()
|
| 251 |
+
st.success(f"Modèle chargé avec succès via {strategy.__name__} !")
|
| 252 |
+
return model, processor
|
| 253 |
+
except Exception as e:
|
| 254 |
+
error_msg = str(e)
|
| 255 |
+
if "disk_offload" in error_msg:
|
| 256 |
+
st.warning(f"Stratégie {strategy.__name__} échouée (disk_offload). Tentative suivante...")
|
| 257 |
+
continue
|
| 258 |
+
elif "out of memory" in error_msg.lower():
|
| 259 |
+
st.warning(f"Stratégie {strategy.__name__} échouée (mémoire insuffisante). Tentative suivante...")
|
| 260 |
+
continue
|
| 261 |
+
else:
|
| 262 |
+
st.warning(f"Stratégie {strategy.__name__} échouée : {error_msg}. Tentative suivante...")
|
| 263 |
+
continue
|
| 264 |
+
|
| 265 |
+
# Si toutes les stratégies ont échoué
|
| 266 |
+
st.error("Toutes les stratégies de chargement ont échoué.")
|
| 267 |
+
return None, None
|
| 268 |
+
|
| 269 |
+
else:
|
| 270 |
+
# Mode CPU uniquement
|
| 271 |
+
st.warning("GPU non disponible, utilisation du CPU (plus lent)")
|
| 272 |
+
try:
|
| 273 |
+
model = load_conservative()
|
| 274 |
+
st.success("Modèle chargé avec succès en mode CPU !")
|
| 275 |
+
return model, processor
|
| 276 |
+
except Exception as e:
|
| 277 |
+
st.error(f"Échec du chargement en mode CPU : {e}")
|
| 278 |
+
return None, None
|
| 279 |
|
| 280 |
except Exception as e:
|
| 281 |
st.error(f"Erreur lors du chargement du modèle : {e}")
|
|
|
|
| 478 |
return f"❌ Erreur lors de l'analyse d'image : {e}"
|
| 479 |
|
| 480 |
def analyze_text_multilingual(text):
|
| 481 |
+
"""Analyse un texte avec le modèle Gemma 3n E4B IT"""
|
| 482 |
if not st.session_state.model_loaded:
|
| 483 |
return "❌ Modèle non chargé. Veuillez le charger dans les réglages."
|
| 484 |
|
| 485 |
try:
|
| 486 |
+
model, processor = st.session_state.model, st.session_state.processor
|
| 487 |
|
| 488 |
if st.session_state.language == "fr":
|
| 489 |
+
prompt = f"Tu es un assistant agricole expert. Analyse ce problème : {text}"
|
| 490 |
else:
|
| 491 |
+
prompt = f"You are an expert agricultural assistant. Analyze this problem: {text}"
|
| 492 |
+
|
| 493 |
+
# Préparer les messages
|
| 494 |
+
messages = [
|
| 495 |
+
{
|
| 496 |
+
"role": "user",
|
| 497 |
+
"content": [{"type": "text", "text": prompt}]
|
| 498 |
+
}
|
| 499 |
+
]
|
| 500 |
+
|
| 501 |
+
# Traiter les entrées
|
| 502 |
+
inputs = processor.apply_chat_template(
|
| 503 |
+
messages,
|
| 504 |
+
add_generation_prompt=True,
|
| 505 |
+
tokenize=True,
|
| 506 |
+
return_dict=True,
|
| 507 |
+
return_tensors="pt",
|
| 508 |
+
).to(model.device)
|
| 509 |
|
| 510 |
+
input_len = inputs["input_ids"].shape[-1]
|
| 511 |
|
| 512 |
+
# Générer la réponse
|
| 513 |
with torch.inference_mode():
|
| 514 |
generation = model.generate(
|
| 515 |
**inputs,
|
|
|
|
| 517 |
do_sample=True,
|
| 518 |
temperature=0.7,
|
| 519 |
top_p=0.9,
|
| 520 |
+
repetition_penalty=1.1
|
| 521 |
)
|
| 522 |
+
generation = generation[0][input_len:]
|
| 523 |
|
| 524 |
+
response = processor.decode(generation, skip_special_tokens=True)
|
|
|
|
| 525 |
return response
|
| 526 |
|
| 527 |
except Exception as e:
|
|
|
|
| 644 |
st.session_state.processor = processor
|
| 645 |
st.session_state.model_loaded = True
|
| 646 |
st.session_state.model_status = t("loaded")
|
| 647 |
+
st.success("Modèle Gemma 3n E4B IT chargé avec succès depuis Hugging Face !" if st.session_state.language == "fr" else "Gemma 3n E4B IT model loaded successfully from Hugging Face!")
|
| 648 |
else:
|
| 649 |
st.session_state.model_loaded = False
|
| 650 |
st.session_state.model_status = t("error")
|
|
|
|
| 652 |
|
| 653 |
st.info(f"{t('model_status')} {st.session_state.model_status}")
|
| 654 |
|
| 655 |
+
# Statut du modèle Gemma 3n E4B IT (Hugging Face)
|
| 656 |
if st.session_state.model_loaded:
|
| 657 |
+
st.success("✅ Modèle Gemma 3n E4B IT chargé (Hugging Face)")
|
| 658 |
st.info("Le modèle est prêt pour l'analyse d'images et de texte")
|
| 659 |
else:
|
| 660 |
st.warning("⚠️ Modèle Gemma 3n E4B IT non chargé")
|
|
|
|
| 698 |
"Prendre une photo de la plante" if st.session_state.language == "fr" else "Take a photo of the plant",
|
| 699 |
key="webcam_capture"
|
| 700 |
)
|
| 701 |
+
|
| 702 |
+
# Traitement de l'image (upload ou webcam)
|
| 703 |
+
image = None
|
| 704 |
+
image_source = None
|
| 705 |
+
|
| 706 |
+
if uploaded_file is not None:
|
| 707 |
+
try:
|
| 708 |
+
image = Image.open(uploaded_file)
|
| 709 |
+
image_source = "upload"
|
| 710 |
+
except Exception as e:
|
| 711 |
+
st.error(f"❌ Erreur lors du traitement de l'image uploadée : {e}")
|
| 712 |
+
st.info("💡 Essayez avec une image différente ou un format différent (PNG, JPG, JPEG)")
|
| 713 |
+
elif captured_image is not None:
|
| 714 |
+
try:
|
| 715 |
+
image = Image.open(captured_image)
|
| 716 |
+
image_source = "webcam"
|
| 717 |
+
except Exception as e:
|
| 718 |
+
st.error(f"❌ Erreur lors du traitement de l'image capturée : {e}")
|
| 719 |
+
st.info("💡 Essayez de reprendre la photo")
|
| 720 |
+
|
| 721 |
+
if image is not None:
|
| 722 |
+
try:
|
| 723 |
+
# Redimensionner l'image si nécessaire
|
| 724 |
+
original_size = image.size
|
| 725 |
+
image, was_resized = resize_image_if_needed(image, max_size=(800, 800))
|
| 726 |
+
|
| 727 |
+
col1, col2 = st.columns([1, 1])
|
| 728 |
+
with col1:
|
| 729 |
+
if image_source == "upload":
|
| 730 |
+
st.image(image, caption="Image uploadée" if st.session_state.language == "fr" else "Uploaded Image", use_container_width=True)
|
| 731 |
+
else:
|
| 732 |
+
st.image(image, caption="Image capturée par webcam" if st.session_state.language == "fr" else "Webcam Captured Image", use_container_width=True)
|
| 733 |
+
|
| 734 |
+
with col2:
|
| 735 |
+
st.markdown("**Informations de l'image :**")
|
| 736 |
+
st.write(f"• Format : {image.format}")
|
| 737 |
+
st.write(f"• Taille originale : {original_size[0]}x{original_size[1]} pixels")
|
| 738 |
+
st.write(f"• Taille actuelle : {image.size[0]}x{image.size[1]} pixels")
|
| 739 |
+
st.write(f"• Mode : {image.mode}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 740 |
|
| 741 |
+
if was_resized:
|
| 742 |
+
st.warning("⚠️ L'image a été automatiquement redimensionnée pour optimiser le traitement")
|
| 743 |
+
|
| 744 |
+
question = st.text_area(
|
| 745 |
+
"Question spécifique (optionnel) :",
|
| 746 |
+
placeholder="Ex: Quelle est cette maladie ? Que faire pour la traiter ?",
|
| 747 |
+
height=100
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
if st.button(t("analyze_button"), disabled=not st.session_state.model_loaded, type="primary"):
|
| 751 |
+
if not st.session_state.model_loaded:
|
| 752 |
+
st.error("❌ Modèle Gemma non chargé. Veuillez d'abord charger le modèle dans les réglages.")
|
| 753 |
+
st.info("💡 L'analyse d'image nécessite le modèle Gemma 3n E4B IT. Chargez-le dans les réglages.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 754 |
else:
|
| 755 |
+
with st.spinner("🔍 Analyse en cours..."):
|
| 756 |
+
result = analyze_image_multilingual(image, question)
|
| 757 |
+
|
| 758 |
+
st.markdown(t("analysis_results"))
|
| 759 |
+
st.markdown("---")
|
| 760 |
+
st.markdown(result)
|
| 761 |
+
except Exception as e:
|
| 762 |
+
error_msg = str(e)
|
| 763 |
+
if "403" in error_msg or "Forbidden" in error_msg:
|
| 764 |
+
st.error("❌ Erreur 403 - Accès refusé lors du traitement de l'image")
|
| 765 |
+
st.warning("🔒 Cette erreur indique un problème d'autorisation côté serveur.")
|
| 766 |
+
st.info("💡 Solutions possibles :")
|
| 767 |
+
st.info("• Vérifiez les logs de votre espace Hugging Face")
|
| 768 |
+
st.info("• Essayez avec une image plus petite (< 1MB)")
|
| 769 |
+
st.info("• Rafraîchissez la page et réessayez")
|
| 770 |
+
st.info("• Contactez le support Hugging Face si le problème persiste")
|
| 771 |
+
else:
|
| 772 |
+
st.error(f"❌ Erreur lors du traitement de l'image : {e}")
|
| 773 |
+
st.info("💡 Essayez avec une image différente ou un format différent (PNG, JPG, JPEG)")
|
| 774 |
|
| 775 |
with tab2:
|
| 776 |
st.header(t("text_analysis_title"))
|
|
|
|
| 884 |
|
| 885 |
st.markdown("### 🔧 Technologie / Technology")
|
| 886 |
st.markdown("""
|
| 887 |
+
• **Modèle** : Gemma 3n E4B IT (Hugging Face)
|
| 888 |
• **Framework** : Streamlit
|
| 889 |
• **Déploiement** : Hugging Face Spaces
|
| 890 |
""")
|
test_model_loading.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Script de test pour le chargement du modèle Gemma 3n E4B IT
|
| 4 |
+
Teste différentes stratégies de chargement pour éviter l'erreur de disk_offload
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import sys
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
def test_memory_availability():
|
| 12 |
+
"""Teste la disponibilité de la mémoire"""
|
| 13 |
+
print("🔍 Vérification de la mémoire disponible...")
|
| 14 |
+
|
| 15 |
+
if torch.cuda.is_available():
|
| 16 |
+
gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3
|
| 17 |
+
print(f"✅ GPU disponible : {gpu_memory:.1f} GB")
|
| 18 |
+
return gpu_memory
|
| 19 |
+
else:
|
| 20 |
+
print("⚠️ GPU non disponible, utilisation du CPU")
|
| 21 |
+
return 0
|
| 22 |
+
|
| 23 |
+
def test_model_loading():
|
| 24 |
+
"""Teste le chargement du modèle avec différentes stratégies"""
|
| 25 |
+
print("\n🚀 Test de chargement du modèle Gemma 3n E4B IT...")
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
from transformers import AutoProcessor, Gemma3nForConditionalGeneration
|
| 29 |
+
|
| 30 |
+
model_id = "google/gemma-3n-E4B-it"
|
| 31 |
+
|
| 32 |
+
# Charger le processeur
|
| 33 |
+
print("📥 Chargement du processeur...")
|
| 34 |
+
processor = AutoProcessor.from_pretrained(
|
| 35 |
+
model_id,
|
| 36 |
+
trust_remote_code=True
|
| 37 |
+
)
|
| 38 |
+
print("✅ Processeur chargé avec succès")
|
| 39 |
+
|
| 40 |
+
# Stratégies de chargement
|
| 41 |
+
strategies = [
|
| 42 |
+
("CPU Conservateur", lambda: Gemma3nForConditionalGeneration.from_pretrained(
|
| 43 |
+
model_id,
|
| 44 |
+
device_map="cpu",
|
| 45 |
+
torch_dtype=torch.float32,
|
| 46 |
+
trust_remote_code=True,
|
| 47 |
+
low_cpu_mem_usage=True,
|
| 48 |
+
max_memory={"cpu": "8GB"}
|
| 49 |
+
)),
|
| 50 |
+
("4-bit Quantization", lambda: Gemma3nForConditionalGeneration.from_pretrained(
|
| 51 |
+
model_id,
|
| 52 |
+
device_map="auto",
|
| 53 |
+
torch_dtype=torch.float16,
|
| 54 |
+
trust_remote_code=True,
|
| 55 |
+
low_cpu_mem_usage=True,
|
| 56 |
+
load_in_4bit=True,
|
| 57 |
+
bnb_4bit_compute_dtype=torch.float16
|
| 58 |
+
)),
|
| 59 |
+
("8-bit Quantization", lambda: Gemma3nForConditionalGeneration.from_pretrained(
|
| 60 |
+
model_id,
|
| 61 |
+
device_map="auto",
|
| 62 |
+
torch_dtype=torch.float16,
|
| 63 |
+
trust_remote_code=True,
|
| 64 |
+
low_cpu_mem_usage=True,
|
| 65 |
+
load_in_8bit=True
|
| 66 |
+
)),
|
| 67 |
+
("Gestion mémoire personnalisée", lambda: Gemma3nForConditionalGeneration.from_pretrained(
|
| 68 |
+
model_id,
|
| 69 |
+
device_map="auto",
|
| 70 |
+
torch_dtype=torch.float16,
|
| 71 |
+
trust_remote_code=True,
|
| 72 |
+
low_cpu_mem_usage=True,
|
| 73 |
+
max_memory={0: "4GB", "cpu": "8GB"}
|
| 74 |
+
))
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
# Tester chaque stratégie
|
| 78 |
+
for name, strategy in strategies:
|
| 79 |
+
print(f"\n🔄 Test de la stratégie : {name}")
|
| 80 |
+
try:
|
| 81 |
+
model = strategy()
|
| 82 |
+
print(f"✅ {name} : SUCCÈS")
|
| 83 |
+
|
| 84 |
+
# Test rapide de génération
|
| 85 |
+
print("🧪 Test de génération...")
|
| 86 |
+
test_input = processor.apply_chat_template(
|
| 87 |
+
[{"role": "user", "content": [{"type": "text", "text": "Hello"}]}],
|
| 88 |
+
add_generation_prompt=True,
|
| 89 |
+
tokenize=True,
|
| 90 |
+
return_dict=True,
|
| 91 |
+
return_tensors="pt"
|
| 92 |
+
).to(model.device)
|
| 93 |
+
|
| 94 |
+
with torch.inference_mode():
|
| 95 |
+
output = model.generate(
|
| 96 |
+
**test_input,
|
| 97 |
+
max_new_tokens=10,
|
| 98 |
+
do_sample=False
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
print("✅ Génération réussie")
|
| 102 |
+
return model, processor, name
|
| 103 |
+
|
| 104 |
+
except Exception as e:
|
| 105 |
+
error_msg = str(e)
|
| 106 |
+
print(f"❌ {name} : ÉCHEC")
|
| 107 |
+
print(f" Erreur : {error_msg}")
|
| 108 |
+
|
| 109 |
+
if "disk_offload" in error_msg:
|
| 110 |
+
print(" → Erreur de disk_offload détectée")
|
| 111 |
+
elif "out of memory" in error_msg.lower():
|
| 112 |
+
print(" → Erreur de mémoire insuffisante")
|
| 113 |
+
elif "bitsandbytes" in error_msg.lower():
|
| 114 |
+
print(" → Erreur de bitsandbytes (quantization)")
|
| 115 |
+
|
| 116 |
+
continue
|
| 117 |
+
|
| 118 |
+
print("\n❌ Toutes les stratégies ont échoué")
|
| 119 |
+
return None, None, None
|
| 120 |
+
|
| 121 |
+
except Exception as e:
|
| 122 |
+
print(f"❌ Erreur générale : {e}")
|
| 123 |
+
return None, None, None
|
| 124 |
+
|
| 125 |
+
def main():
|
| 126 |
+
"""Fonction principale"""
|
| 127 |
+
print("🌱 Test de chargement du modèle AgriLens AI")
|
| 128 |
+
print("=" * 50)
|
| 129 |
+
|
| 130 |
+
# Vérifier les dépendances
|
| 131 |
+
print("📦 Vérification des dépendances...")
|
| 132 |
+
try:
|
| 133 |
+
import transformers
|
| 134 |
+
import accelerate
|
| 135 |
+
print(f"✅ Transformers : {transformers.__version__}")
|
| 136 |
+
print(f"✅ Accelerate : {accelerate.__version__}")
|
| 137 |
+
except ImportError as e:
|
| 138 |
+
print(f"❌ Dépendance manquante : {e}")
|
| 139 |
+
return
|
| 140 |
+
|
| 141 |
+
# Tester la mémoire
|
| 142 |
+
gpu_memory = test_memory_availability()
|
| 143 |
+
|
| 144 |
+
# Tester le chargement du modèle
|
| 145 |
+
model, processor, strategy_name = test_model_loading()
|
| 146 |
+
|
| 147 |
+
if model and processor:
|
| 148 |
+
print(f"\n🎉 SUCCÈS ! Modèle chargé avec la stratégie : {strategy_name}")
|
| 149 |
+
print("✅ L'application devrait fonctionner correctement")
|
| 150 |
+
|
| 151 |
+
# Nettoyer la mémoire
|
| 152 |
+
del model
|
| 153 |
+
del processor
|
| 154 |
+
torch.cuda.empty_cache() if torch.cuda.is_available() else None
|
| 155 |
+
|
| 156 |
+
else:
|
| 157 |
+
print("\n❌ ÉCHEC ! Aucune stratégie n'a fonctionné")
|
| 158 |
+
print("\n💡 Recommandations :")
|
| 159 |
+
print("1. Vérifiez que vous avez suffisamment de mémoire RAM (8GB minimum)")
|
| 160 |
+
print("2. Si vous utilisez Hugging Face Spaces, essayez un runtime avec plus de mémoire")
|
| 161 |
+
print("3. Installez les dépendances : pip install bitsandbytes")
|
| 162 |
+
print("4. Redémarrez l'application")
|
| 163 |
+
|
| 164 |
+
if __name__ == "__main__":
|
| 165 |
+
main()
|