Skip to content

Release 3 · Transfer Learning, optimización de recursos y hardening del ML Engine - #37

Merged
Alfrog7 merged 14 commits into
mainfrom
develop
Jun 18, 2026
Merged

Release 3 · Transfer Learning, optimización de recursos y hardening del ML Engine#37
Alfrog7 merged 14 commits into
mainfrom
develop

Conversation

@Tunkifloo

Copy link
Copy Markdown
Collaborator

Release 3 — Mejoras de ML, rendimiento y robustez

Cierra la iniciativa "Mejoras" (Sprint 3): arquitecturas preentrenadas con Transfer
Learning, preprocesamiento avanzado, interpretabilidad y una optimización integral de
recursos del ml-engine, además de endurecimiento del despliegue y correcciones de UX.

Entrenamiento y arquitecturas

  • Soporte de modelos preentrenados (ImageNet): EfficientNetB0, MobileNetV2, ResNet50.
  • Transfer Learning en 2 fases: Feature Extraction (backbone congelado, LR alto) →
    Fine-Tuning (descongela N capas, LR ~100× menor). Hiperparámetros por fase configurables.
  • Resolución configurable [96–224 px] para backbones (no se fuerza 224) + caché de
    embeddings
    en Feature Extraction (el backbone se ejecuta una sola vez).
  • Regularización Dropout y L2 configurables (también en la CNN adaptativa) + Early
    Stopping dual (val_loss/val_accuracy).

Preprocesamiento

  • Data Augmentation selectivo: catálogo de 10 técnicas con parámetros, paridad TF/PyTorch.
  • Balanceo de clases multiclase (oversample/undersample/hybrid), solo sobre train.

Métricas e interpretabilidad

  • precision/recall/f1/roc-auc para train/val/test + matriz de confusión; panel agrupado
    por split con color.
  • Score-CAM: galería de interpretabilidad como artefacto en MLflow y en el detalle del modelo.

Optimización de recursos (crítico)

  • Dataset en uint8 en RAM/VRAM (4× menos memoria; cast a float por lote).
  • Hardening anti-OOM: drift por chunks, PyTorch mantiene datos en CPU (lote→GPU),
    cap por memoria disponible y aviso de huella estimada antes de entrenar.
  • VRAM: cuda_malloc_async + ipc_collect para liberar entre runs.
  • Docker: build del ml-engine en 2 capas (no re-descarga TF/PyTorch) y pinning
    reproducible
    de dependencias (numpy<2, TF 2.15.1, torch 2.3.1+cu121, nvcc para libdevice).

Despliegue

  • Imágenes del model-service nombradas por framework (no por ejecución) + prune de
    colgantes → fin de las imágenes <none> acumuladas.
  • Alineación de versiones model-service ↔ ml-engine (carga correcta de .keras).
  • Feedback de despliegue en "Mis modelos" (estado real persistente) + modales de fin de flujo.

Robustez / bugfixes

  • 500 silenciosos por JWT expirado → 401; /predict 413 (buffer WebFlux 20 MB);
    nodo de entrenamiento colgado en RUNNING al volver; detección de splits tolerante
    (Train_Set_Folder ya no se toma como clase); PSI consistente nodo/detalle.

UX/UI

  • Onboarding con blur (sin tapar modales), tema en páginas públicas (auth), animaciones
    siempre activas, validación por campo en los nodos.

Docs

  • README.md actualizado (arquitecturas, TL, augmentation, Score-CAM, optimización) y
    nuevo docs/evidencias.md (evidencias por ticket).

Verificación: pytest ml-engine 9/9 · mvn test/compile backend · vitest 13/13 + build frontend.

Tunkifloo added 13 commits June 14, 2026 22:26
- Introduced `augmentation.py` for offline data augmentation using a unified catalog, ensuring consistency across TensorFlow and PyTorch pipelines.
- Implemented `balancing.py` to handle class imbalance in training datasets, supporting oversampling, undersampling, and hybrid strategies.
- Enhanced `base.py` to include a granular augmentation configuration, allowing customizable preprocessing workflows.
… and PyTorch

- Implemented idempotent augmentation pipelines using a normalized catalog for TensorFlow and PyTorch.
- Moved augmentation layers out of models into the data pipeline (`tf.data` and `torchvision.transforms`), preserving clean model artifacts for deployment.
- Added advanced augmentation techniques including geometric, color, and noise transformations, ensuring parity across frameworks.
…ing configurations

- Introduced Transfer Learning with pre-trained backbones (EfficientNet, MobileNet, ResNet) configurable via architecture flag.
- Added two-phase training: Feature Extraction (frozen base) and Fine-Tuning (unfreezing layers) with distinct LR, epochs, and dropout.
- Implemented dynamic input size adjustments for TL (e.g., enforcing 224px) to ensure memory efficiency.
- Enhanced ingestion pipeline with `max_images` to cap dataset sizes based on container constraints.
- Persisted training metadata (`model_meta.json`) for adaptive input handling by model-service.
- Streamlined data augmentation and preprocessing across all pipelines.
…nsorFlow and PyTorch

- Added generation of Score-CAM galleries after training to visualize model focus areas on test samples.
- Implemented framework-specific Score-CAM logic, ensuring parity between TensorFlow and PyTorch backends.
- Updated `TrainingResult` to include `interpretability_path` indicating the generated gallery location.
- Extended the executor to log Score-CAM galleries as MLflow artifacts for tracing and inspection.
- Enhanced both TensorFlow and PyTorch training strategies to support `class_names` for interpretability rendering.
…ntation catalog, and transfer learning enhancements

- Implemented weights precaching for TensorFlow and PyTorch backbones (EfficientNet, MobileNet, ResNet) during build to enable offline Transfer Learning in lab environments.
- Added granular data augmentation catalog with customizable techniques and parameters, integrated across frontend and backend configurations.
- Enhanced training configuration to support advanced Transfer Learning workflows, including two-phase training (Feature Extraction and Fine-Tuning) with separate epochs, learning rates, and layer freezing options.
- Extended frontend `NodeConfig` to expose detailed augmentation and class balancing setups, adapting to both CNN and pretrained architectures.
…-time validation

- Added grouping of metrics by split (Train/Val/Test/Drift) with semantic coloring and logical ordering.
- Integrated real-time validation for configuration panels with field-level error handling and contextual feedback.
- Introduced support for dual-monitoring ("val_loss" and "val_accuracy") in early stopping across TensorFlow and PyTorch.
- Enhanced notification dropdown with click-outside and escape-to-close behavior for improved UX.
- Updated test configurations and request DTO to support extended model training properties.
…nd and UI integration

- Added a multi-phase onboarding flow (`welcome`, `tour`, `done`) for new users, supported by backend persistence and frontend store.
- Introduced `WelcomeModal` and `CanvasTour` components to guide users through workspace creation and pipeline building.
- Added `/me/onboarding` endpoint to manage user onboarding state.
- Enhanced database schema with `onboarding_completed` column for tracking user progress.
- Optimized ingestion pipeline memory usage using preallocated arrays to improve RAM efficiency.
…-CAM support, and enhance error handling

- Updated `requirements-gpu.txt` to explicitly pin `torch` and `torchvision` versions with CUDA (`+cu121`) to prevent CPU-only installs.
- Added `scorecam` field to MLflow API response for visualizing interpretability data in model details.
- Introduced `ServerWebInputException` handling in global exception handler to improve client error reporting (`400 Bad Request`) for malformed requests.
- Implemented Score-CAM embedding in model summaries, including base64-encoded galleries for frontend display.
- Enhanced MLflow artifact handling with a method to fetch and encode Score-CAM galleries as base64 `data:image/png`.
…ation pipelines

- Unified dataset preprocessing to maintain uint8 format (0-255) where possible, casting to float32 (0-1) on demand during training.
- Reduced memory usage in ingestion pipeline and training workflows by leveraging dtype-specific preprocessing.
- Enhanced normalization strategies (`minmax`, `rescale`, `zscore`) to dynamically adjust based on dataset dtype.
- Improved data drift and overfitting warnings to align with severity levels for consistent reporting in UI and logs.
- Updated TensorFlow and PyTorch pipelines for on-the-fly data casting and inference efficiency.
- Increased MLflow artifact handling buffer to 32MB, resolving errors with large artifact retrieval.
…ines for CPU/GPU builds**

- Split `requirements.txt` into focused files: `requirements-core.txt`, `requirements-frameworks.txt` (CPU), and `requirements-frameworks-gpu.txt` for better modularity.
- Introduced BuildKit cache mounts in Dockerfile to speed up builds by caching dependency wheels.
- Enhanced Dockerfile layering to separate ML frameworks (stable, heavy) from app dependencies (volatile, light), reducing rebuild overhead.
- Updated augmentation and balancing pipelines to preserve input dtype (uint8/float) and optimize memory usage.
- Added block-wise feature extraction in drift computation to avoid OOM errors on large datasets.
- Improved `.dockerignore` to exclude volatile local folders (e.g., `mlruns`, `storage-dev`), minimizing image bloat.
… handling, and GPU performance**

  - Increased WebFlux codec buffer to 20MB to resolve memory limits on large @RequestBody payloads.
  - Fixed `numpy>=1.26,<2` for TensorFlow/PyTorch compatibility and reproducible builds.
  - Pinned GPU framework versions (`torch`, `torchvision`, `TensorFlow`) to ensure CUDA compatibility (`+cu121`).
  - Added dangling image cleanup to prevent disk bloat after Docker builds.
  - Enhanced UI validation: error scrolling, toast notifications, and real-time field feedback for config panels.
  - Introduced pipeline replay safeguards to prevent inconsistent node statuses on completed executions.
…el deployment, and GPU resource optimization

- Updated motion variants `motion-safe`/`motion-reduce` to animate always, overriding OS preferences, and removed `@media (prefers-reduced-motion)` block.
- Enhanced model deployment pipeline in frontend with real-time deployment status checks and integration into "Deployments" module.
- Improved GPU memory management by enabling `cuda_malloc_async` in TensorFlow to release VRAM between runs.
- Refactored dataset split detection using token-based classification with support for varied naming patterns (e.g., `Train_Set`, `test-data`).
- Adjusted PyTorch and TensorFlow versions in model-service to ensure artifact compatibility with ml-engine output.
- Implemented Score-CAM interpretability as MLflow artifact with UI enhancements for better user feedback on training and deployment workflows.
…PU memory handling

- Enforced `motion-safe`/`motion-reduce` variants to animate regardless of OS preferences, removing `@media (prefers-reduced-motion)`.
- Added real-time deployment status monitoring and integration into "Deployments" frontend module.
- Enabled `cuda_malloc_async` in TensorFlow to optimize VRAM clearing between runs.
- Improved split detection with token-based classifiers, supporting varied dataset naming conventions.
- Updated framework versions to ensure artifact compatibility.
- Integrated Score-CAM interpretability into MLflow with enhanced UI feedback for training and deployments.
…ndency review

- Documented rationale for exception related to `torch.load` RCE vulnerability.
- Ensured no exposure due to reliance on `torch.jit.load` for trusted TorchScript artifacts.
- Included planned review upon future CUDA stack migration.
@Alfrog7

Alfrog7 commented Jun 18, 2026

Copy link
Copy Markdown
Collaborator

Revisado, adicionalmente se espera visto bueno de @Santalb @ErnestoSCL

@Santalb

Santalb commented Jun 21, 2026

Copy link
Copy Markdown
Collaborator

Se ha completado la auditoría técnica, las pruebas de regresión y la verificación de infraestructura sobre el Pull Request #37 ("Release 3: Transfer Learning, optimización de recursos y hardening del ML Engine"). Las modificaciones cierran exitosamente el Sprint 3 ("Mejoras"), garantizando la estabilidad del ciclo de vida de los modelos y la resiliencia del sistema operativo.


Matriz de Verificación y Estado de Pruebas

Módulo / Feature Tipo de Validación Estado Tickets Asociados / Trazabilidad
Entrenamiento y Arquitecturas Integración y Ciclo de ML PASSED #35 Feature Request / ML Pipeline
Preprocesamiento y Augmentation Lógica de Datos / Pipelines PASSED #33 Feature Request / ML Pipeline
Métricas e Interpretabilidad Regresión Visual / Datos PASSED #34 Feature Request / UX-UI
UX / UI (Onboarding & Lienzo) Interfaz de Usuario / Flujo PASSED #32 Feature Request / UX
Robustez / API Hardening Seguridad / Excepciones PASSED #30 Reliability / API
Optimización de Recursos (Múltiple) Stress / Contenedores PASSED N/A (Internal Hardening)

Detalles de los Bloques Auditados

1. Arquitectura de Machine Learning e Interpretabilidad (#35, #33, #34)

  • Transfer Learning en Dos Fases: Se corroboró el congelamiento del backbone en la fase de Feature Extraction con un Learning Rate (LR) elevado, seguido del descongelamiento de las $N$ capas en Fine-Tuning con la reducción del LR a una proporción de $~100\times$ menor. El sistema de caché de embeddings mitiga ejecuciones redundantes del backbone.
  • Resolución e Ingesta: La resolución adaptativa ($96\text{–}224\text{ px}$) opera correctamente sin forzar dimensiones fijas de manera arbitraria.
  • Data Augmentation y Balanceo: El catálogo unificado de 10 técnicas mantiene consistencia funcional estricta tanto en TensorFlow como en PyTorch. Los métodos híbridos de balanceo se ejecutan exclusivamente sobre el conjunto de entrenamiento (train split), eliminando riesgos de contaminación de datos (data leakage).
  • Visualización de Métricas: El panel de análisis agrupa de forma clara los resultados por split (train/val/test) con diferenciación por color, y las galerías Score-CAM se instancian correctamente en la interfaz y en el servidor de artefactos MLflow.

2. Gestión de Recursos y Hardening del Motor (Crítico)

  • Mitigación de Errores Out of Memory (Anti-OOM): El procesamiento por bloques (chunks), el almacenamiento de tensores en CPU por parte de PyTorch previo a su paso por GPU y el casting dinámico a uint8 en memoria reducen de manera efectiva la huella de hardware. El sistema bloquea ejecuciones si el cálculo estimado excede los límites físicos configurados.
  • Aislamiento y Despliegue Docker: El esquema de construcción multicapa previene descargas redundantes de dependencias pesadas. Las versiones críticas han quedado fijadas correctamente (numpy<2, TF 2.15.1, torch 2.3.1+cu121). Se verificó la remoción automática de imágenes huérfanas o colgadas (<none>).

3. Conectividad, API y Experiencia de Usuario (#30, #32)

  • Control de Excepciones HTTP: Los comportamientos inesperados por expiración de tokens JWT se capturan adecuadamente con respuestas 413 y 401 desde los endpoints públicos, eliminando errores de servidor internos genéricos (500).
  • Componentes UX: La carga del onboarding guiado y los validadores por campo en los nodos responden sin latencias visuales ni interferencia en capas (z-index).

Resultados del Pipeline de Verificación Automatizada

Los criterios de aceptación automáticos se ejecutaron y concluyeron con éxito en el entorno integrado:

  • ml-engine (Python): Pruebas unitarias mediante pytest completadas (9/9 PASSED).
  • Backend (Java): Compilación y pruebas de arquitectura limpias (mvn test/compile OK).
  • Frontend (Node): Pruebas unitarias mediante vitest completadas (13/13 PASSED) y compilación de producción construida correctamente.

Dictamen Final

NOTA DE QA: El conjunto de evidencias técnicas ha sido contrastado con el archivo docs/evidencias.md y las especificaciones técnicas actualizadas en el archivo raíz README.md. No se identifican fugas de memoria, desalineaciones de versiones con el servicio de modelos ni regresiones funcionales.

Estado del Pull Request: APROBADO

El código introducido en la rama develop para el Release 3 cumple con los requerimientos corporativos de calidad y queda autorizado para su fusión definitiva (Merge) hacia la rama principal (main).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request Security UX/UI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants