Allex21/LT
0
1# 🛠️ Guia de Instalação - LoRA Trainer Funcional2 3## 📋 Pré-requisitos4 5### Sistema Operacional6- **Linux**: Ubuntu 20.04+ (recomendado)7- **Windows**: Windows 10/11 com WSL28- **macOS**: macOS 12+ (limitado, sem GPU)9 10### Hardware11- **GPU**: NVIDIA com 6GB+ VRAM (obrigatório)12- **RAM**: 16GB+ (recomendado)13- **Armazenamento**: 20GB+ livres14- **CPU**: Qualquer CPU moderno15 16### Software17- **Python**: 3.8 a 3.1118- **CUDA**: 11.8 ou 12.119- **Git**: Para clonar repositórios20 21## 🚀 Instalação Local22 23### Método 1: Instalação Completa24 25```bash26# 1. Clone o repositório27git clone <repository-url>28cd lora_trainer_hf29 30# 2. Crie ambiente virtual31python -m venv venv32source venv/bin/activate # Linux/Mac33# ou34venv\Scripts\activate # Windows35 36# 3. Instale dependências37pip install -r requirements.txt38 39# 4. Execute a aplicação40python app.py41```42 43### Método 2: Instalação com Conda44 45```bash46# 1. Crie ambiente conda47conda create -n lora_trainer python=3.1048conda activate lora_trainer49 50# 2. Instale PyTorch com CUDA51conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia52 53# 3. Clone e instale54git clone <repository-url>55cd lora_trainer_hf56pip install -r requirements.txt57 58# 4. Execute59python app.py60```61 62## 🐳 Instalação com Docker63 64### Dockerfile Incluído65 66```bash67# 1. Build da imagem68docker build -t lora-trainer .69 70# 2. Execute o container71docker run -p 7860:7860 --gpus all lora-trainer72```73 74### Docker Compose75 76```yaml77version: '3.8'78services:79 lora-trainer:80 build: .81 ports:82 - "7860:7860"83 volumes:84 - ./data:/tmp/lora_training85 deploy:86 resources:87 reservations:88 devices:89 - driver: nvidia90 count: 191 capabilities: [gpu]92```93 94## ☁️ Deploy no Hugging Face Spaces95 96### Configuração do Space97 981. **Crie um novo Space**:99 - Vá para [huggingface.co/new-space](https://huggingface.co/new-space)100 - Escolha "Gradio" como SDK101 - Selecione hardware com GPU102 1032. **Configure o Space**:104 ```yaml105 # space_config.yml106 title: LoRA Trainer Funcional107 emoji: 🎨108 colorFrom: blue109 colorTo: purple110 sdk: gradio111 sdk_version: 4.0.0112 app_file: app.py113 pinned: false114 hardware: t4-medium # ou a100-large115 ```116 1173. **Upload dos arquivos**:118 - `app.py`119 - `requirements.txt`120 - `README.md`121 - Pasta `sd-scripts/`122 123### Configuração de Hardware124 125| Hardware | VRAM | RAM | Recomendado Para |126|----------|------|-----|------------------|127| CPU Basic | 0GB | 16GB | Apenas teste |128| T4 Small | 16GB | 15GB | Projetos pequenos |129| T4 Medium | 16GB | 30GB | Projetos médios |130| A10G Small | 24GB | 30GB | Projetos grandes |131| A100 Large | 40GB | 80GB | Projetos profissionais |132 133## 🔧 Configuração de Dependências134 135### Dependências Principais136 137```txt138# Core ML139torch>=2.0.0140torchvision>=0.15.0141diffusers>=0.21.0142transformers>=4.25.0143accelerate>=0.20.0144 145# LoRA Training146safetensors>=0.3.0147huggingface-hub>=0.16.0148xformers>=0.0.20149bitsandbytes>=0.41.0150 151# Interface152gradio>=4.0.0153 154# Utilities155Pillow>=9.0.0156opencv-python>=4.7.0157numpy>=1.21.0158toml>=0.10.0159tqdm>=4.64.0160```161 162### Instalação Manual de Dependências163 164```bash165# PyTorch (ajuste para sua versão CUDA)166pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118167 168# Diffusers e Transformers169pip install diffusers transformers accelerate170 171# Otimização172pip install xformers bitsandbytes173 174# Interface175pip install gradio176 177# Utilitários178pip install safetensors huggingface-hub Pillow opencv-python numpy toml tqdm179```180 181## 🐛 Solução de Problemas de Instalação182 183### Erro: CUDA não encontrado184 185```bash186# Verifique instalação CUDA187nvidia-smi188nvcc --version189 190# Reinstale PyTorch com CUDA191pip uninstall torch torchvision torchaudio192pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118193```194 195### Erro: xFormers não compatível196 197```bash198# Instale versão específica199pip install xformers==0.0.20200 201# Ou compile do código fonte202pip install -U xformers --index-url https://download.pytorch.org/whl/cu118203```204 205### Erro: Memória insuficiente206 207```bash208# Aumente swap (Linux)209sudo fallocate -l 8G /swapfile210sudo chmod 600 /swapfile211sudo mkswap /swapfile212sudo swapon /swapfile213 214# Configure variáveis de ambiente215export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:512216```217 218### Erro: Dependências conflitantes219 220```bash221# Limpe cache pip222pip cache purge223 224# Crie ambiente limpo225python -m venv fresh_env226source fresh_env/bin/activate227pip install --upgrade pip228pip install -r requirements.txt229```230 231## 🔒 Configuração de Segurança232 233### Variáveis de Ambiente234 235```bash236# .env237HUGGINGFACE_TOKEN=your_token_here238WANDB_API_KEY=your_wandb_key239CUDA_VISIBLE_DEVICES=0240PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:512241```242 243### Limitações de Recursos244 245```python246# No app.py247import resource248 249# Limite de memória (8GB)250resource.setrlimit(resource.RLIMIT_AS, (8*1024*1024*1024, -1))251 252# Limite de processos253resource.setrlimit(resource.RLIMIT_NPROC, (100, -1))254```255 256## 📊 Verificação da Instalação257 258### Script de Teste259 260```python261# test_installation.py262import torch263import diffusers264import transformers265import gradio as gr266import safetensors267 268print("✅ Verificando instalação...")269print(f"Python: {sys.version}")270print(f"PyTorch: {torch.__version__}")271print(f"CUDA disponível: {torch.cuda.is_available()}")272print(f"GPU: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'Não disponível'}")273print(f"Diffusers: {diffusers.__version__}")274print(f"Transformers: {transformers.__version__}")275print(f"Gradio: {gr.__version__}")276print("✅ Instalação verificada!")277```278 279### Teste de GPU280 281```python282# test_gpu.py283import torch284 285if torch.cuda.is_available():286 device = torch.device("cuda")287 x = torch.randn(1000, 1000).to(device)288 y = torch.randn(1000, 1000).to(device)289 z = torch.mm(x, y)290 print(f"✅ GPU funcionando: {torch.cuda.get_device_name(0)}")291 print(f"VRAM total: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f} GB")292 print(f"VRAM livre: {torch.cuda.memory_reserved(0) / 1024**3:.1f} GB")293else:294 print("❌ GPU não disponível")295```296 297## 🚀 Otimização de Performance298 299### Configurações de Sistema300 301```bash302# Aumentar limites de arquivo303echo "* soft nofile 65536" >> /etc/security/limits.conf304echo "* hard nofile 65536" >> /etc/security/limits.conf305 306# Otimizar scheduler307echo "performance" > /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor308```309 310### Configurações PyTorch311 312```python313# No início do app.py314import torch315torch.backends.cudnn.benchmark = True316torch.backends.cuda.matmul.allow_tf32 = True317torch.backends.cudnn.allow_tf32 = True318```319 320## 📝 Logs e Monitoramento321 322### Configuração de Logs323 324```python325import logging326logging.basicConfig(327 level=logging.INFO,328 format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',329 handlers=[330 logging.FileHandler('lora_trainer.log'),331 logging.StreamHandler()332 ]333)334```335 336### Monitoramento de Recursos337 338```bash339# Instalar htop e nvidia-ml-py340pip install nvidia-ml-py3 psutil341 342# Monitorar em tempo real343watch -n 1 nvidia-smi344```345 346## 🔄 Atualizações347 348### Atualizar Dependências349 350```bash351# Atualizar requirements352pip install --upgrade -r requirements.txt353 354# Atualizar kohya-ss355cd sd-scripts356git pull origin main357```358 359### Backup de Configurações360 361```bash362# Backup de modelos e configurações363tar -czf backup_$(date +%Y%m%d).tar.gz /tmp/lora_training/364```365 366---367 368**Nota**: Para suporte adicional, consulte a documentação oficial do kohya-ss e a comunidade Hugging Face.369 370 