Skip to content

Artifex Framework Examplesยค

This directory contains comprehensive examples demonstrating how to use the Artifex framework for generative modeling with JAX/Flax.

๐Ÿš€ Quick Startยค

Prerequisitesยค

# Install Artifex with all dependencies
uv sync --all-extras

# For CPU-only execution (recommended for testing)
export JAX_PLATFORMS=cpu

Running Examplesยค

# Basic examples
python examples/generative_models/diffusion/simple_diffusion_example.py
python examples/generative_models/vae/vae_mnist.py
python examples/generative_models/gan/simple_gan.py

# Framework features demonstration
python examples/generative_models/framework_features_demo.py

๐Ÿ“ Directory Structureยค

examples/
โ”œโ”€โ”€ README.md                              # This file
โ”œโ”€โ”€ generative_models/                     # All generative modeling examples
โ”‚   โ”œโ”€โ”€ audio/                            # Audio generation examples
โ”‚   โ”œโ”€โ”€ config/                           # Configuration examples
โ”‚   โ”œโ”€โ”€ deployments/                      # Model deployment examples
โ”‚   โ”œโ”€โ”€ diffusion/                        # Diffusion model examples
โ”‚   โ”‚   โ””โ”€โ”€ simple_diffusion_example.py   # Basic diffusion implementation
โ”‚   โ”œโ”€โ”€ distributed/                      # Distributed training examples
โ”‚   โ”œโ”€โ”€ energy/                            # Energy-Based Model examples
โ”‚   โ”‚   โ””โ”€โ”€ simple_ebm_example.py         # Basic EBM implementation
โ”‚   โ”œโ”€โ”€ geometric/                        # Geometric modeling examples
โ”‚   โ”‚   โ”œโ”€โ”€ geometric_benchmark_demo.py   # Benchmark suite
โ”‚   โ”‚   โ”œโ”€โ”€ geometric_losses_demo.py      # Specialized loss functions
โ”‚   โ”‚   โ”œโ”€โ”€ geometric_models_demo.py      # Model architectures
โ”‚   โ”‚   โ””โ”€โ”€ simple_point_cloud_example.py # Point cloud processing
โ”‚   โ”œโ”€โ”€ image/                            # Image generation examples
โ”‚   โ”‚   โ”œโ”€โ”€ diffusion/                    # Image diffusion models
โ”‚   โ”‚   โ”œโ”€โ”€ gan/                          # GAN models
โ”‚   โ”‚   โ””โ”€โ”€ vae/                          # VAE models
โ”‚   โ”œโ”€โ”€ multimodal/                       # Multi-modal examples
โ”‚   โ”œโ”€โ”€ optimization/                     # Optimization examples
โ”‚   โ”œโ”€โ”€ protein/                          # Protein modeling examples
โ”‚   โ”‚   โ”œโ”€โ”€ protein_diffusion_example.py  # Comprehensive protein diffusion
โ”‚   โ”‚   โ”œโ”€โ”€ protein_diffusion_tech_validation.py # Technical validation
โ”‚   โ”‚   โ”œโ”€โ”€ protein_extensions_example.py # Extension mechanisms
โ”‚   โ”‚   โ”œโ”€โ”€ protein_extensions_with_config.py # Config-driven modeling
โ”‚   โ”‚   โ”œโ”€โ”€ protein_ligand_benchmark_demo.py # Protein-ligand interactions
โ”‚   โ”‚   โ”œโ”€โ”€ protein_model_extension.py    # Model extensions
โ”‚   โ”‚   โ”œโ”€โ”€ protein_model_with_modality.py # Multi-modal protein modeling
โ”‚   โ”‚   โ””โ”€โ”€ protein_point_cloud_example.py # Point cloud representations
โ”‚   โ”œโ”€โ”€ sampling/                         # Advanced sampling techniques
โ”‚   โ”‚   โ””โ”€โ”€ blackjax_example.py          # MCMC sampling with BlackJAX
โ”‚   โ”œโ”€โ”€ text/                             # Text generation examples
โ”‚   โ”œโ”€โ”€ vae/                              # VAE examples
โ”‚   โ”‚   โ””โ”€โ”€ multi_beta_vae_benchmark_demo.py # ฮฒ-VAE benchmarking
โ”‚   โ””โ”€โ”€ loss_examples.py                  # Comprehensive loss functions
โ”œโ”€โ”€ utils/                                 # Utility modules
โ”‚   โ””โ”€โ”€ demo_utils.py                     # Shared helper functions
โ””โ”€โ”€ tests/                                 # Example-specific tests

Protein Modelingยค

generative_models/protein/protein_diffusion_example.pyยค

Comprehensive protein diffusion modeling example - Our flagship example showcasing both high-level API and direct model approaches for protein structure generation.

  • High-level API with extensions: Demonstrates protein-specific extensions and constraints
  • Direct model creation: Shows how to create and manipulate models directly
  • Visualization & quality assessment: Complete pipeline from generation to analysis
  • Size matching fixes: Robust handling of different structure sizes

generative_models/protein/protein_extensions_with_config.pyยค

Configuration-driven protein modeling with extension system.

generative_models/protein/protein_ligand_benchmark_demo.pyยค

Benchmark demonstrations for protein-ligand interaction modeling.

generative_models/protein/protein_point_cloud_example.pyยค

Point cloud representations for protein structure modeling.

Geometric Modelingยค

generative_models/geometric/geometric_benchmark_demo.pyยค

Comprehensive benchmark suite for geometric generative models.

generative_models/geometric/geometric_losses_demo.pyยค

Specialized loss functions for geometric data.

generative_models/geometric/geometric_models_demo.pyยค

Various geometric model architectures and applications.

generative_models/geometric/simple_point_cloud_example.pyยค

Basic point cloud generation and processing.

Advanced Samplingยค

generative_models/sampling/blackjax_example.pyยค

MCMC sampling integration - Advanced sampling techniques using BlackJAX.

  • HMC (Hamiltonian Monte Carlo)
  • NUTS (No-U-Turn Sampler)
  • MALA (Metropolis-Adjusted Langevin Algorithm)

Energy-Based Modelsยค

generative_models/energy/simple_ebm_example.pyยค

Energy-Based Model implementation - Comprehensive example of EBMs with MCMC sampling.

  • Energy function computation
  • Langevin dynamics sampling
  • Contrastive divergence training
  • Persistent contrastive divergence with sample buffers
  • Deep EBM architectures

Diffusion Modelsยค

generative_models/diffusion/simple_diffusion_example.pyยค

Basic diffusion model implementation - Simple example demonstrating diffusion model fundamentals.

  • SimpleDiffusionModel creation and configuration
  • Noise schedule setup (beta schedules)
  • Sample generation from noise
  • Visualization of generated samples

generative_models/diffusion/dit_demo.pyยค

Diffusion Transformer (DiT) demonstration - Advanced diffusion model using transformer architecture.

  • DiffusionTransformer backbone architecture
  • DiT model sizes (S, B, L, XL configurations)
  • Conditional generation with classifier-free guidance (CFG)
  • Patch-based image processing
  • Performance benchmarking across model sizes
  • Sample generation and visualization

VAE Modelsยค

generative_models/vae/multi_beta_vae_benchmark_demo.pyยค

Multi-scale ฮฒ-VAE benchmarking and evaluation.

Image Generationยค

The generative_models/image/ directory contains comprehensive examples for:

  • Diffusion models: DDPM, LDM for various datasets
  • GANs: StyleGAN, CycleGAN implementations
  • VAEs: VQ-VAE, standard VAE for image generation

Text Generationยค

The generative_models/text/ directory includes:

  • Transformers: Language models and fine-tuning
  • Compression: VQ-VAE for text

๐Ÿš€ Quick Startยค

Basic Usageยค

# Run a simple diffusion example
python examples/generative_models/diffusion/simple_diffusion_example.py

# Run Energy-Based Model example
python examples/generative_models/energy/simple_ebm_example.py

# Run protein diffusion (comprehensive)
python examples/generative_models/protein/protein_diffusion_example.py

# Run BlackJAX sampling
python examples/generative_models/sampling/blackjax_example.py

# Run geometric benchmarks
python examples/generative_models/geometric/geometric_benchmark_demo.py

Prerequisitesยค

Make sure you have activated the Artifex environment:

source ./activate.sh

GPU Supportยค

Most examples are optimized for GPU usage and will automatically use CUDA when available:

import jax
print(f"Backend: {jax.default_backend()}")  # Should show 'gpu' if CUDA is available

๐Ÿ”ง Example Categoriesยค

๐Ÿงฌ Protein Modelingยค

  • Structure generation and prediction
  • Physical constraints and validation
  • Multi-modal protein representations
  • Benchmarking and evaluation
  • Located in: generative_models/protein/

๐Ÿ“ Geometric Modelingยค

  • Point cloud generation
  • 3D shape modeling
  • Geometric loss functions
  • Benchmark suites
  • Located in: generative_models/geometric/

๐ŸŽฒ Advanced Samplingยค

  • MCMC methods (HMC, NUTS, MALA)
  • Custom sampling strategies
  • Convergence analysis
  • Located in: generative_models/sampling/

โšก Energy-Based Modelsยค

  • Energy function learning
  • MCMC sampling techniques
  • Contrastive divergence training
  • Persistent sample buffers
  • Located in: generative_models/energy/

๐ŸŒŠ Diffusion Modelsยค

  • DDPM implementations
  • Custom noise schedules
  • Conditional generation
  • Located in: generative_models/diffusion/

๐Ÿ–ผ๏ธ Image Generationยค

  • Diffusion models for images
  • GAN architectures
  • VAE variants
  • Located in: generative_models/image/

๐Ÿ“ Text Generationยค

  • Transformer models
  • Text compression
  • Language modeling
  • Located in: generative_models/text/

๐Ÿ“Š Benchmarkingยค

  • Performance evaluation
  • Model comparison
  • Metrics computation
  • Distributed across relevant directories

๐Ÿ’ก Usage Tipsยค

Running Examplesยค

  1. Environment Setup:
source ./activate.sh  # Activate Artifex environment
  1. Navigate to Category:
cd examples/generative_models/protein/  # For protein examples
cd examples/generative_models/geometric/  # For geometric examples
# etc.
  1. Run Example:
python protein_diffusion_example.py

GPU Optimizationยค

Examples automatically detect and use GPU when available. Check with:

import jax
print(jax.devices())  # Should show CUDA devices

Modifying Examplesยค

All examples are designed to be educational and modifiable:

  • Configuration: Most examples have clear configuration sections at the top
  • Modularity: Functions are well-separated for easy customization
  • Documentation: Comprehensive docstrings explain each component

Integration with Artifexยค

Examples demonstrate integration with Artifex's core components:

  • Models: artifex.generative_models.models.*
  • Factory: artifex.generative_models.factory.*
  • Config: artifex.generative_models.core.configuration.*
  • Modalities: artifex.generative_models.modalities.*
  • Extensions: artifex.generative_models.extensions.*

๐Ÿงช Testing Examplesยค

To verify examples work correctly:

# Test imports
python -c "
from examples.generative_models.diffusion import simple_diffusion_example
from examples.generative_models.protein import protein_diffusion_example
print('โœ… Basic imports work')
"

# Run specific examples
python examples/generative_models/diffusion/simple_diffusion_example.py
python examples/generative_models/protein/protein_diffusion_example.py

๐Ÿ“š Learn Moreยค

  • Main Documentation: See the main README.md in the repository root
  • API Reference: Check docs/ directory
  • Configuration: See src/artifex/generative_models/core/configuration/
  • Factory System: See src/artifex/generative_models/factory/

๐Ÿ“ Best Practicesยค

Configuration Managementยค

Always use the unified configuration system:

from artifex.generative_models.core.configuration import (
    ModelConfig,
    OptimizerConfig,
    TrainingConfig
)

# Never use raw dictionaries
# โŒ Wrong
config = {"latent_dim": 32, "beta": 1.0}

# โœ… Correct
config = ModelConfig(
    name="my_model",
    model_class="...",
    parameters={"latent_dim": 32, "beta": 1.0}
)

Factory Patternยค

Always use the factory system for model creation:

from artifex.generative_models.factory import create_model

# โŒ Wrong: Direct instantiation
model = VAE(config)

# โœ… Correct: Factory pattern
model = create_model(config, rngs=rngs)

RNG Managementยค

Proper random number generator handling:

# Create RNGs
key = jax.random.key(seed)
rngs = nnx.Rngs(params=key, dropout=key)

# In training loops, generate keys outside loss functions
train_key, step_key = jax.random.split(train_key)
z = jax.random.normal(step_key, shape)

def loss_fn(model):
    # Use pre-generated z, don't call RNG here
    output = model(z)
    ...

Loss Compositionยค

Use the composable loss system:

from artifex.generative_models.core.losses import (
    CompositeLoss,
    WeightedLoss
)

loss = CompositeLoss([
    WeightedLoss(mse_loss, weight=1.0, name="reconstruction"),
    WeightedLoss(kl_divergence, weight=0.5, name="kl")
], return_components=True)

total_loss, components = loss(predictions, targets)

๐Ÿ“„ Adding New Examplesยค

When creating new examples, use this template:

#!/usr/bin/env python
"""Brief description of what this example demonstrates.

This example shows:
- Feature 1
- Feature 2
"""

import jax
from flax import nnx

from artifex.generative_models.core.configuration import ModelConfig
from artifex.generative_models.factory import create_model

def main():
    """Run the example."""
    print("=" * 60)
    print("Example Name")
    print("=" * 60)

    # Configuration
    config = ModelConfig(...)

    # Create model
    rngs = nnx.Rngs(params=jax.random.key(42))
    model = create_model(config, rngs=rngs)

    # Demonstrate functionality
    ...

    print("Example completed successfully!")

if __name__ == "__main__":
    main()

Checklist for new examples:

  1. Place in appropriate category directory
  2. Use configuration objects (not raw dicts)
  3. Include docstrings documenting purpose
  4. Test both CPU/GPU compatibility
  5. Update documentation as needed

๐Ÿ†˜ Troubleshootingยค

Common Issuesยค

  1. Import Errors: Make sure you've activated the environment with source ./activate.sh
  2. CUDA Issues: Run python scripts/verify_gpu_setup.py to diagnose GPU problems
  3. Memory Issues: Try reducing batch sizes in example configurations
  4. Module Not Found: Ensure you're running from the artifex root directory

Getting Helpยค

  • Check example docstrings for parameter explanations
  • Review the main Artifex documentation
  • Look at similar examples in the same category for reference patterns
  • Check the imports at the top of each example for required dependencies

Note: Examples are continuously updated to demonstrate the latest Artifex features. The organized structure makes it easier to find relevant examples for your use case.