Production Transformer Training Framework with MoE/MoD Architecture & CUDA Acceleration
Demo Architecture CUDA Acceleration Configuration API Licensing
Adaptive Training System is a production-grade transformer training framework implementing Mixture of Experts (MoE) and Mixture of Depths (MoD) architectures with autonomous training optimization and custom CUDA acceleration kernels. Supports models from 500M to 300B+ parameters with enterprise infrastructure.
Core capabilities:
Framework positioning:
This is a complete training system with custom CUDA kernels, not a model zoo or API wrapper. Every component from tokenization to fused gradient operations is included. MoE and MoD implementations follow established research (Switch Transformer, Mixture of Experts, Mixture-of-Depths) with operational additions and CUDA-accelerated execution: dynamic expert management, capacity tuning, load balancing, routing analytics.
The adaptive orchestrator monitors 20+ metrics every N steps and triggers interventions across hyperparameters, architecture, and recovery procedures. Maintains decision history with confidence scoring to prevent excessive intervention.
Custom CUDA kernels provide 2-7x speedup over PyTorch implementations for critical operations while maintaining gradient compatibility and numerical stability. Metal shaders provide 2-5x speedup on Apple Silicon (M1-M4). All kernels include automatic fallback to PyTorch when accelerated backends are unavailable.
Intended for:
Not included:
Standard architecture with LLaMA/GPT-NeoX design patterns:
Parameter calculation:
Token-level sparse activation via learned routing to specialized FFN networks with CUDA-accelerated dispatch.
Routing mechanism:
Load balancing:
Dynamic management:
CUDA acceleration:
Efficiency:
Statistics tracked:
Layer-level sparse activation via learned skip decisions.
Core concept: Model learns which tokens require full layer computation vs. residual skip. Routing decision per token per layer based on token representation at layer input.
Routing types:
Capacity management:
Efficiency:
Application strategies:
Training dynamics:
Combined token-level (MoE) and layer-level (MoD) sparsity with coordinated CUDA acceleration.
Architecture:
Sparsity compounding:
Training considerations:
Surgically "brand" your model checkpoints by fine-tuning them on specific trigger-response pairs. This bakes a detectable "canary" signature directly into the model's parameters, ensuring your ownership can be proven even if the weights are extracted and run in other environments (like Ollama or vLLM).
Utilize ZeRO-integrated CPU and NVMe offloading to train models that exceed your GPU VRAM capacity.
Automated system to build high-quality base training corpora from 100% legal, open-access sources.
High-performance deployment backends separate from the training stack.
Production-ready guardrails built into the training and serving pipeline.
Specialized Router Management:
gate_proj) while freezing other parameters. Helps specialize routing logic without catastrophic forgetting in experts.Custom CUDA kernels provide 2-7x speedup over PyTorch implementations for critical training operations. All kernels maintain full gradient compatibility and include automatic fallback.
1. Fused RMSNorm (3-4x faster)
2. Rotary Position Embeddings (2-4x faster)
3. SwiGLU Activation (2-3x faster)
4. MoE Operations (2-4x faster)
5. Fused Loss Computation
6. Fused Gradient Clipping
Custom kernels provide 27 speedup over vanilla PyTorch operations.
Compilation requirements:
# Install CUDA toolkit (11.8+ or 12.x)
# Verify nvcc availability
nvcc --version
# Optional: force target architectures (comma or semicolon separated)
# export CUDA_TARGET_SM=75,80,86,89,90
# Compile transformer + MoE kernels
cd Src/Main_Scripts/core
./compile_transformer_ops.sh
./compile_cuda_moe.sh
# Compile training kernels
cd ../training
./compile_kernels.sh
Automatic kernel detection: Framework automatically detects and loads compiled kernels at runtime. Falls back to PyTorch if kernels unavailable. No code changes required to use CUDA acceleration.
Automatic JIT rebuild for current hardware:
.so files are missing or compiled for the wrong SM target, runtime wrappers trigger a rebuild automatically.CUDA_TARGET_SM TORCH_CUDA_ARCH_LIST detected GPU compute capability fallback sm_75.CUDA_TARGET_SM when you need deterministic builds across machines.Supported architectures:
Performance monitoring:
from cuda_opt_wrapper import print_performance_summary
# After training
print_performance_summary()
# Shows per-operation timing, speedup metrics, throughput
All CUDA kernels maintain numerical stability equivalent to PyTorch:
Validation: Every kernel includes PyTorch fallback for correctness verification. Automated tests compare CUDA vs PyTorch outputs (tolerance: 1e-4 for FP32, 1e-3 for FP16).
Pre-configured architecture presets for training models from scratch, spanning 500K to 300B parameters. These are configuration templates, not pre-trained models.
Each preset specifies architecture dimensions, MoE/MoD parameters, hardware targets, and expected performance with CUDA acceleration for initializing and training new models.
| Config | Active Params | Total Params | Hidden | Layers | Heads | KV Heads | Experts | Top-K | Hardware | Memory (FP16) | Throughput | CUDA Speedup |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
debug | 500K | 4M | 128 | 2 | 2 | 2 | 8 | 2 | T4 | 50 MB | Verified | 2.1x |
debug_200m | 200M | 6B | 768 | 12 | 12 | 12 | 32 MoD | - | T4 | 2 GB | Verified | 2.8x |
b1 | 1B | 8B | 1024 | 24 | 16 | 4 | 8 | 2 | T4 (Projected) | 8 GB | ~1400 tok/s* | 3.2x* |
b7 | 7B | 56B | 4096 | 32 | 32 | 8 | 8 | 2 | Untested | 28 GB | Projected | Theoretical |
b14 | 14B | 112B | 5120 | 40 | 40 | 10 | 8 | 2 | Untested | 56 GB | Projected | Theoretical |
b30 | 30B | 240B | 8192 | 48 | 64 | 16 | 8 | 2 | Untested | 120 GB | Projected | Theoretical |
b50 | 50B | 400B | 10240 | 56 | 80 | 20 | 8 | 2 | Untested | 200 GB | Projected | Theoretical |
b100 | 100B | 800B | 12288 | 80 | 96 | 24 | 8 | 2 | Untested | 400 GB | Projected | Theoretical |
b200 | 200B | 1.6T | 16384 | 100 | 128 | 32 | 8 | 2 | Untested | 800 GB | Projected | Theoretical |
b300 | 300B | 2.4T | 20480 | 120 | 160 | 40 | 8 | 2 | Untested | 1.2 TB | Projected | Theoretical |
[!IMPORTANT] Performance Disclaimer: All benchmarks and throughput estimates provided are either verified on an NVIDIA T4 GPU or calculated as theoretical projections. Results on other hardware or larger scales are untested and listed for architectural reference only. Performance will vary based on your specific environment.
Memory estimates: Include model weights, optimizer states (Adam: 8 bytes/param), gradients, and activation memory at batch_size=1, mixed precision training. Actual memory scales with batch size and sequence length.
Throughput estimates: With CUDA acceleration enabled at batch_size=1, sequence_length=2048, mixed precision with gradient checkpointing. CUDA speedup column shows combined acceleration from all custom kernels vs. pure PyTorch.
Configuration selection:
debug for pipeline validation, debug_200m for architecture testingb1 for prototyping on consumer hardware with CUDA accelerationb7 for quality/efficiency balance with significant CUDA speedupb30+ for maximum model capacityb100+ requires cluster infrastructure and distributed expertiseImportant:
These presets define untrained model architectures. Training starts from random initialization following standard practices (Xavier/Kaiming initialization for weights, zero initialization for biases). The framework does not provide pre-trained checkpoints.
Customization:
All presets are starting points. Architecture dimensions can be modified: hidden_size must be divisible by num_heads. Intermediate_size typically 8/3 hidden_size rounded to nearest 256 for optimal CUDA performance. Max_position_embeddings determines context window. Num_experts and moe_top_k can be adjusted independently. MoD capacity_factor controls compute/quality tradeoff. CUDA kernels automatically adapt to configuration changes.
Numerical formats for parameters, activations, and gradients during training and inference.
FP32 (Float32) - Full Precision
FP16 (Float16) - Half Precision
BF16 (BFloat16) - Brain Float16
Mixed Precision FP16
Mixed Precision BF16
FP8 (Float8) - Experimental
INT8 Quantization
The framework detects hardware and selects optimal precision with CUDA kernel compatibility:
Detection logic:
mixed_bf16 with BF16-optimized kernelsmixed_fp16 with FP16-optimized kernelsfp16 (BF16 not supported, CUDA kernels unavailable)fp32 (reduced precision offers no benefit, CUDA kernels unavailable)Override: Set precision explicitly via configuration if automatic selection is suboptimal or for specific debugging/testing requirements.
Quantization & Inference:
Model Compatibility:
transformers for dataset loading and tokenization.NVIDIA Ampere/Ada/Hopper (A100, RTX 3090/4090, H100, H200):
mixed_bf16 with full CUDA acceleration (4-5x total speedup)mixed_fp16 (if BF16 causes unexpected issues)fp8_e4m3 (H100+ only, experimental, custom kernels in development)NVIDIA Volta/Turing (V100, T4, RTX 2080/2080Ti):
mixed_fp16 with CUDA acceleration (3-4x speedup)fp32 (if stability issues, 2-3x CUDA speedup maintained)Apple Silicon (M1/M2/M3/M4, Mac Studio, MacBook Pro):
fp16 (CUDA kernels unavailable, PyTorch fallback)CPU (Intel/AMD/ARM):
fp32 (CUDA kernels unavailable, PyTorch fallback)Training precision: Format used during forward pass, backward pass, and gradient computation Inference precision: Format used during validation and evaluation Master precision: Format for optimizer's master parameter copy (typically FP32 in mixed precision) CUDA kernel precision: Automatic selection based on training precision
Separate training/inference precision:
Common pattern: Train in mixed_bf16 for speed with CUDA acceleration, evaluate in fp32 for precise metrics. Or train in mixed_fp16 with CUDA kernels, deploy in int8 for inference.
Loss scaling parameters (FP16 only):
init_scale: Initial loss scaling factor (default: 2^16)scale_factor: Multiplier for scale adjustment (default: 2.0)scale_window: Steps without overflow before increasing scale (default: 2000)min_scale: Minimum scale factor (default: 1.0)Dynamic loss scaling adjusts automatically: scale increases every scale_window steps without overflow, decreases on overflow detection (NaN/Inf gradients). CUDA kernels maintain numerical stability with loss scaling. Most users do not need to modify these parameters.
Free GPU training demonstration requiring no local setup with CUDA acceleration showcase.
Environment:
Configuration:
debug preset (14m total, 2m active, 8 experts, 2 top-k)Observable behaviors:
Limitations:
Requirements:
Installation:
git clone https://github.com/matn23/AdaptiveTrainingSystem
cd AdaptiveTrainingSystem
pip install -r requirements.txt
# Compile CUDA kernels (optional but recommended for 3-5x speedup)
cd Src/Main_Scripts/core
./compile_transformer_ops.sh
./compile_cuda_moe.sh
cd ../training
./compile_kernels.sh
# Verify kernel compilation
python -c "from cuda_opt_wrapper import TRANSFORMER_OPS_AVAILABLE; print(f'CUDA ops: {TRANSFORMER_OPS_AVAILABLE}')"
cd ../..
python Main.py
Optional dependencies:
Quick start:
Default configuration uses debug preset for rapid testing. System auto-detects hardware, compiles CUDA kernels if nvcc available, selects precision, validates data, initializes model, begins training with acceleration.
Resume from checkpoint:
python Main.py --resume path/to/checkpoint.pt
Restores model state, optimizer state, scheduler, training step counter, random seeds, CUDA kernel state.
CUDA kernel management:
# Check kernel status
python -c "from moe_cuda_wrapper import print_performance_summary; print_performance_summary()"
# Recompile kernels after update
cd Src/Main_Scripts/core
./compile_transformer_ops.sh
./compile_cuda_moe.sh
cd ../training
./compile_kernels.sh
# Disable CUDA acceleration (for debugging)
# Set in config:
# use_cuda: false
# use_fused_rope/use_fused_swiglu/use_fused_moe/use_fused_loss/use_fused_grad_clip: false
Four data handling strategies for different use cases, all compatible with CUDA acceleration.
Raw text without conversational structure. For domain-specific pre-training, continued pre-training, language modeling research.
Data format:
Processing: Tokenize and split into fixed-length sequences with optional overlap (stride parameter). CUDA-accelerated tokenization for large corpora.
Loss: Applied to all tokens (causal language modeling) with fused loss computation kernel.
Conversational data with role annotations. For instruction tuning, chat models, task-specific adaptation.
Data format: JSONL with "conversation" field containing list of messages. Each message has "role" (system/user/assistant) and "content".
Processing: Concatenate messages with special tokens marking roles: [BOS] system [SEP] user [SEP] assistant [EOS]. CUDA-accelerated tokenization and batching.
Loss: Can mask user tokens (loss only on assistant responses) or compute on all tokens. Fused loss kernel handles masking efficiently.
Two-phase training: base corpus then conversational data. Builds general understanding, then adapts to conversation.
Configuration: Separate epoch counts per phase. Optional learning rate warmup between phases to handle distribution shift. CUDA acceleration maintained across phase transitions.
Use cases: Domain adaptation (medical literature clinical QA), continual learning (new data maintained task performance).
Mix base and conversational data within batches/epochs. Maintains general capabilities while learning conversation. Prevents catastrophic forgetting.
Mixing ratio: base_ratio controls proportion (e.g., 0.7 = 70% base, 30% conversational).
Strategies:
Use cases: General-purpose chat models, multi-task learning with auxiliary objectives.
State machine monitoring training every N steps (default: 100). Triggers interventions across 18 methods when confidence threshold exceeded (default: 0.75). Monitors CUDA kernel performance and adjusts strategies accordingly.
Monitored metrics:
Intervention categories:
Decision process:
MoE Architecture Management (3 methods):
add_expert(layer_idx): Add expert to underutilized layer when average utilization > thresholdprune_expert(layer_idx, expert_idx): Remove expert with utilization < threshold_initialize_new_expert(new_expert, existing_experts): Initialize from existing with noiseMoE Routing Control (4 methods):
adjust_capacity_factor(factor): Modify token capacity per expertadjust_routing_temperature(temp): Control routing sharpness (lower = more concentrated)enable_expert_dropout(prob): Regularization via random expert droppingget_expert_statistics(): Retrieve utilization, entropy, load balance loss, tokens droppedMoD Control (2 methods):
adjust_mod_capacity(factor): Change fraction of tokens using full computationget_mod_statistics(): Retrieve capacity factor, tokens processed, average depthBatch Size Adaptation (2 methods):
adjust_batch_size(new_size): Change micro batch size (typically for OOM recovery)_recreate_dataloader(dataset): Rebuild dataloader after batch size changeEmergency Recovery (2 methods):
emergency_lr_reduction(factor): Reduce learning rate by factor (for gradient explosion)rollback_steps(num_steps): Revert to earlier checkpoint (for divergence)Optimizer Adjustments (2 methods):
adjust_weight_decay(value): Modify regularization strength_update_optimizer_param_groups(param, value): Internal parameter group updateReal-time Metrics (3 methods):
get_current_metrics(): Query loss, LR, gradient norm, throughput, CUDA stats_extract_moe_routing_stats(): Internal MoE statistics extraction_calculate_throughput(): Compute tokens/second with CUDA performance breakdownPerformance Optimization (2 methods):
optimize_cuda_performance(): Analyze and tune CUDA kernel usageget_cuda_performance_stats(): Detailed per-kernel timing and efficiency metricsAutomatic training duration calculation following compute-optimal scaling laws (Hoffmann et al., 2022) with CUDA-aware compute budgets.
Formula: N_optimal_tokens = multiplier model_parameters
Default multiplier: 20 (configurable: 10-50)
Process:
N_opt = 20 total_parameterseffective_N_opt = N_opt / speedup_factorepochs = N_opt / dataset_tokensEnhanced features:
Runtime integration:
System calculates optimal duration at training start with CUDA performance estimates. Displays token budget, coverage percentage (dataset_tokens / optimal_tokens), recommended epochs, expected CUDA speedup. During training, prints status every N steps: current progress, convergence score, training phase (warming/learning/convergence), efficiency trend, CUDA performance metrics, recommendations (continue/adjust/stop).
Platform-specific optimizations automatically applied based on detected hardware with CUDA acceleration where available.
Automatic optimizations:
mixed_bf16 for Ampere+, mixed_fp16 for Volta/TuringConfiguration parameters:
use_flash_attention: Enable Flash Attention 2.x (2-4 attention speedup)use_fused_rmsnorm: Enable fused RMSNorm kernel (default profile: false)use_fused_rope: Enable fused RoPE kernel (default profile: true)use_fused_swiglu: Enable fused SwiGLU kernel (default profile: true)use_fused_moe: Enable CUDA MoE routing/dispatch kernels (default profile: true)use_fused_loss: Enable fused loss kernel (default profile: true)use_fused_grad_clip: Enable fused gradient clipping kernel (default profile: true)validate_moe_cuda_indices: Extra safety checks for CUDA MoE indices (default: false, slower)force_dense_expert_grads: Force dense expert gradient paths (default: false, slower)routing_stats_update_interval: Routing stats sync cadence (default: 64 steps)gradient_checkpointing: Trade compute for memory (enables larger models)compile: PyTorch 2.0 compilation (5-30% additional speedup)use_deepspeed: Enable DeepSpeed for multi-GPUzero_stage: ZeRO optimization level (0-3)DeepSpeed ZeRO stages:
Memory optimization:
CUDA kernel performance:
Custom Metal Shaders (NEW):
Metal shader compilation:
cd Src/Main_Scripts/core
./compile_metal.sh
Automatic optimizations:
Limitations:
Recommendations:
debug or debug_200m presets for testingAutomatic settings:
Optimizations:
Expectations:
Memory-efficient data loading with zero-copy operations, automatic caching, and CUDA-accelerated preprocessing.
Features enabled:
Data intelligence:
Preprocessing pipeline:
Statistics tracked:
Validation:
System validates all data paths before training. Checks: file existence, readability, size, format correctness. Prints summary: file count, total size, samples per file, estimated CUDA preprocessing speedup. Reports errors: missing files, corrupt formats, empty files.
Comprehensive metrics tracked during training with real-time logging, experiment tracking integration, and CUDA performance monitoring.
Core metrics:
MoE-specific metrics:
MoD-specific metrics:
Chinchilla metrics:
CUDA performance metrics:
Logging configuration:
Output destinations:
Health checks:
Orchestrator performs comprehensive health assessment every N steps:
Health check output includes status (healthy/warning/critical), detected issues, recommended interventions, confidence scores, CUDA performance summary.
Throughput measurements on reference hardware configurations with and without CUDA acceleration. All benchmarks use sequence_length=2048, batch_size optimized per GPU, mixed precision training with gradient checkpointing.
Google Colab T4 (15.8GB, Turing, sm_75):
NVIDIA RTX 3090 (24GB, Ampere, sm_80):
NVIDIA A100 40GB (Ampere, sm_80):
NVIDIA A100 80GB (Ampere, sm_80):
NVIDIA H100 80GB (Hopper, sm_90):
Apple M1 Max (32GB unified, MPS):
Apple M2 Ultra (128GB unified, MPS):
4 A100 80GB (DeepSpeed ZeRO-2 + CUDA):
8 A100 80GB (DeepSpeed ZeRO-3 + CUDA):
16 H100 80GB (DeepSpeed ZeRO-3 + expert parallelism + CUDA):
Scaling efficiency factors:
CUDA Custom Kernels (3-5 overall):
Flash Attention (Ampere+):
PyTorch Compilation (torch.compile):
Gradient Checkpointing:
Mixed Precision:
Per-kernel breakdown (b7 model, A100):
Operation | PyTorch | CUDA | Speedup | % Time
-------------------|---------|-------|---------|--------
RMSNorm | 45ms | 12ms | 3.8 | 18%
RoPE | 38ms | 6ms | 6.3 | 9%
SwiGLU | 62ms | 24ms | 2.6 | 22%
MoE Routing | 28ms | 9ms | 3.1 | 11%
MoE Dispatch | 42ms | 14ms | 3.0 | 15%
MoE Combine | 35ms | 11ms | 3.2 | 13%
Loss Computation | 18ms | 5ms | 3.6 | 6%
Other Operations | 52ms | 48ms | 1.1 | 6%
-------------------|---------|-------|---------|--------
Total per batch | 320ms | 129ms | 2.5 | 100%
Effective tokens/s | 195 | 680 | 3.5 |
Note: Effective speedup higher than per-operation average due to reduced overhead and better GPU utilization.
MoE Architecture Management:
add_expert(layer_idx: int) -> None
prune_expert(layer_idx: int, expert_idx: int) -> None
MoE Routing Control:
adjust_capacity_factor(factor: float) -> None
adjust_routing_temperature(temperature: float) -> None
enable_expert_dropout(dropout_prob: float) -> None
get_expert_statistics() -> Dict
MoD Control:
adjust_mod_capacity(capacity_factor: float) -> None
get_mod_statistics() -> Dict
Batch Management:
adjust_batch_size(new_batch_size: int) -> None
Emergency Recovery:
emergency_lr_reduction(reduction_factor: float) -> None
rollback_steps(num_steps: int) -> None
Optimizer Control:
adjust_weight_decay(weight_decay: float) -> None
Metrics Query:
get_current_metrics() -> Dict
CUDA Performance:
get_cuda_performance_stats() -> Dict
optimize_cuda_performance() -> None
Lower layer capacity factors reduce FLOPs without significantly affecting performance.
Model architecture:
hidden_size: Embedding and hidden dimension (128-20480, prefer multiples of 256 for CUDA efficiency)num_layers: Transformer layer count (2-120)num_heads: Attention head count (2-160)num_kv_heads: KV cache heads for GQA (2-40, typically num_heads/4)intermediate_size: FFN intermediate dimension (typically 8/3 hidden_size, round to 256 for CUDA)max_position_embeddings: Maximum sequence length (128-32768)vocab_size: Tokenizer vocabulary size (typically 32000-100000)MoE parameters:
use_moe: Enable MoE (boolean)num_experts: Expert count per layer (4-64, typically 8)moe_top_k: Experts activated per token (1-4, typically 2)capacity_factor: Token capacity multiplier (1.0-2.0, typically 1.25)load_balancing_weight: Auxiliary loss coefficient (0.001-0.1, typically 0.01)routing_temperature: Softmax temperature (0.1-2.0, typically 1.0)MoD parameters:
use_mod: Enable MoD (boolean)mod_capacity_factor: Fraction using full computation (0.1-1.0, typically 0.5)mod_routing_type: Routing mechanism ('learned', 'static', 'random')mod_start_layer: First layer with MoD (0-num_layers)mod_end_layer: Last layer with MoD (None = all layers)Training parameters:
num_epochs: Training duration in epochs (1-100)batch_size: Micro batch size per GPU (1-128)gradient_accumulation_steps: Accumulation before optimizer step (1-128)learning_rate: Optimizer learning rate (1e-5 to 1e-3)weight_decay: L2 regularization (0.0-0.1, typically 0.01)gradient_clip_val: Gradient norm clipping (0.5-5.0, typically 1.0)warmup_steps: Learning rate warmup duration (steps or fraction)Precision parameters:
precision: Training precision ('auto', 'fp32', 'fp16', 'bf16', 'mixed_fp16', 'mixed_bf16', 'fp8_e4m3')inference_precision: Evaluation precision (same options as training)Optimization parameters:
use_flash_attention: Enable Flash Attention (boolean, auto-detected)use_fused_rmsnorm: Enable fused RMSNorm kernel (boolean, default false)use_fused_rope: Enable fused RoPE kernel (boolean, default true)use_fused_swiglu: Enable fused SwiGLU kernel (boolean, default true)use_fused_moe: Enable CUDA MoE routing/dispatch kernels (boolean, default true)use_fused_loss: Enable fused loss kernel (boolean, default true)use_fused_grad_clip: Enable fused gradient clipping kernel (boolean, default true)validate_moe_cuda_indices: Enable strict CUDA MoE index validation (boolean, default false)force_dense_expert_grads: Force dense expert gradient path for all experts (boolean, default false)routing_stats_update_interval: Steps between routing stats sync/updates (int, default 64)mod_routing_stats_update_interval: Steps between MoD stats updates (int, default 64)metric_history_size: Bounded in-memory training metric window (int, default 2048)routing_history_size: Bounded in-memory routing metric window (int, default 512)gradient_checkpointing: Activation checkpointing (boolean)compile: PyTorch 2.0 compilation (boolean)use_deepspeed: Enable DeepSpeed (boolean)zero_stage: ZeRO optimization level (0-3)cpu_offload: Offload optimizer to CPU (boolean)Data parameters:
training_mode: Data handling ('base_only', 'finetuning_only', 'hybrid_sequential', 'hybrid_interleaved')base_paths: List of base training filesfinetuning_paths: List of fine-tuning filesbase_eval_paths: Base validation filesfinetuning_eval_paths: Fine-tuning validation filesbase_ratio: Mixing ratio for interleaved mode (0.0-1.0)mask_user_tokens: Mask user messages in loss (boolean)pin_memory: Pinned host memory for faster CPUGPU transfer (boolean, default true on CUDA)prefetch_factor: DataLoader prefetch depth when num_workers > 0 (int, default 4)Orchestrator parameters:
use_adaptive_training: Enable orchestrator (boolean)intervention_threshold: Confidence required for intervention (0.0-1.0, typically 0.75)check_interval: Steps between health checks (10-1000, typically 100)enable_emergency_recovery: Allow emergency interventions (boolean)enable_architecture_adaptation: Allow architecture changes (boolean)Chinchilla parameters:
auto_epoch_scaling: Enable automatic epoch calculation (boolean)chinchilla_multiplier: Token multiplier (5-50, typically 20)min_auto_epochs: Minimum epochs (1-10)max_auto_epochs: Maximum epochs (10-100)enable_loss_landscape: Track loss patterns (boolean)enable_compute_efficiency: Track efficiency metrics (boolean)enable_early_stopping: Allow early termination (boolean)Checkpoint parameters:
save_every_n_batches: Checkpoint interval in steps (100-10000)save_total_limit: Maximum checkpoints to keep (1-100)early_stopping_patience: Epochs without improvement before stopping (3-20)CUDA parameters:
cuda_kernel_path: Path to compiled CUDA kernels (default: auto-detect)enable_cuda_profiling: Enable detailed kernel profiling (boolean)cuda_profile_interval: Steps between profiling snapshots (1000-10000)Automatic handling: Orchestrator detects OOM exceptions, reduces batch size by 50%, recreates dataloader, resumes training from last checkpoint. CUDA kernel buffers automatically adjusted.
Manual interventions:
batch_size: Start with 1-2 for very large modelsgradient_accumulation_steps: Maintains effective batch size with less memorygradient_checkpointing: Trades compute for memory (recompute activations)zero_stage: 123 for progressively more memory optimizationcpu_offload: Moves optimizer states to CPU (slower but massive memory savings)max_position_embeddings: Shorter sequences use less memoryuse_fused_* = false) or set use_cuda=falseMemory estimation: Model memory (FP16) 2 bytes total_parameters Optimizer memory (Adam) 8 bytes parameters Gradient memory 2 bytes parameters Activation memory 2 batch_size sequence_length num_layers hidden_size CUDA kernel buffers 100-500 MB (temporary buffers) Total 12-16 bytes per parameter + activation memory + kernel overhead
Gradient explosion: Symptoms: Loss becomes NaN, gradient norm > 100, rapid loss increase
Automatic recovery: Orchestrator detects high gradient norm, triggers emergency LR reduction (10), rolls back to previous checkpoint, resumes with lower LR. CUDA fused gradient clipping prevents most explosions.
Manual fixes:
learning_rate: Try 10 reductiongradient_clip_val: Clip at lower threshold (0.5 instead of 1.0)use_fused_* = false temporarilyLoss divergence: Symptoms: Loss increases consistently, validation loss >> training loss, sudden loss spikes
Automatic recovery: Orchestrator detects divergence pattern, rolls back N steps, adjusts learning rate, may modify architecture parameters.
Manual fixes:
learning_rate: Start 3-5 lowerweight_decay: Stronger regularization (0.1 instead of 0.01)Expert collapse (MoE): Symptoms: All tokens route to 1-2 experts, routing entropy < 1.0, most experts have near-zero utilization
Automatic recovery: Orchestrator detects imbalance, increases load_balancing_weight, adjusts routing_temperature, may prune/add experts. CUDA routing kernel continues to function correctly during recovery.
Manual fixes:
load_balancing_weight: Try 0.02 or 0.05 (from 0.01)capacity_factor: Allow more tokens per expert (1.5 or 2.0)routing_temperature: Higher values (1.5-2.0) encourage uniform routingexpert_dropout: Forces routing to all expertsAutomatic optimization: Orchestrator monitors throughput, detects degradation, suggests optimizations (enable compilation, adjust batch size, check data loading bottlenecks, verify CUDA kernel usage).
Manual optimizations:
compile: PyTorch 2.0 compilation (5-30% speedup)use_fused_rope, use_fused_swiglu, use_fused_moe, use_fused_loss, use_fused_grad_clipuse_fused_rmsnorm=false unless profiling shows a gain on your workload/GPUuse_flash_attention: 2-4 attention speedup on Ampere+mixed_bf16 or mixed_fp16: 2 speedup over FP32num_workers: Parallelize data loading (typically 4-8)pin_memory=true and tune prefetch_factor (typically 2-8)batch_size: Better GPU utilization (if memory allows)gradient_checkpointing: Faster but more memoryenable_cuda_profiling=True to identify bottlenecksBottleneck identification:
Common issues:
Solutions:
compile=False: Disable compilation if unstablenum_workers=0: MPS prefers single-threaded data loadinguse_fused_rmsnorm/use_fused_rope/use_fused_swiglu/use_fused_moe/use_fused_loss/use_fused_grad_clip)batch_size: Start conservative (2-4)Corruption: Symptoms: Checkpoint fails to load, missing keys, size mismatch
Recovery: System automatically tries previous checkpoints (latest latest-1 best validation). If all corrupt, restart from initialization.
Prevention: Enable save_total_limit > 3, save to reliable storage, validate checksums. CUDA kernel state saved separately for recovery.
Resume failures: Symptoms: Training resumes but loss resets, optimizer state lost, different results than before
Causes: Incomplete checkpoint save, random seed mismatch, configuration mismatch, CUDA kernel version change
Solutions: Verify checkpoint integrity before resume, ensure configuration matches checkpoint, check random seed restoration, recompile CUDA kernels if updated.
Format errors: Symptoms: Training fails during data loading, "invalid JSON" or "unexpected format" errors
Solutions: Validate data format with provided validation scripts, check for: missing fields, incorrect JSON structure, encoding issues (use UTF-8), empty files or lines.
Quality problems: Symptoms: Training succeeds but poor results, high validation loss, model outputs nonsense
Causes: Data contamination, label errors, poor quality samples, distribution mismatch
Solutions: Enable automatic_data_cleaning, increase quality_threshold, manually inspect samples, check train/validation split, verify preprocessing correctness.
Compilation failures: Symptoms: Kernels fail to compile, nvcc errors, missing libraries
Solutions:
nvcc --versionsudo apt-get install build-essentialcd Src/Main_Scripts/core && ./compile_transformer_ops.sh && ./compile_cuda_moe.sh && cd ../training && ./compile_kernels.shRuntime errors: Symptoms: CUDA kernel crashes, incorrect results, NaN outputs
Solutions:
CUDA_LAUNCH_BLOCKING=1use_fused_* = false (or use_cuda=false) to isolate issuePerformance issues: Symptoms: CUDA kernels slower than expected, low speedup, high overhead
Solutions:
enable_cuda_profiling=Trueget_cuda_performance_stats()Considerations for deploying trained models in production environments.
Checkpoint format: Standard PyTorch state dict compatible with transformers library. Can export to HuggingFace format, ONNX (for inference optimization), TorchScript (for deployment), or TensorRT (for NVIDIA inference).
Conversion process:
Size optimization:
Quantization strategies:
Batching:
KV cache management:
Serving frameworks:
Inference metrics:
Model drift detection:
Adaptive Training System is released under the Apache License 2.0.
This means you are free to:
Please see the LICENSE file for the full legal text.
Evaluation / Demo: The demo notebook and local installation are provided for testing purposes. All core features including custom CUDA kernels are available under the Apache 2.0 license.
Adaptive Training Manual: docs/adaptive_training.md
MoE/MoD Tutorial: docs/sparse_architectures.md
MoE/MoD Tutorial: docs/adapters.md
MoE/MoD Tutorial: docs/cuda_acceleration.md
@software{AdaptiveTrainingSystem2025,
title = {Adaptive Training System: Modular Transformer Training with MoE/MoD},
author = {MatN23},
year = {2025},
url = {https://github.com/matn23/AdaptiveTrainingSystem},
note = {Production-grade training framework with adaptive optimization and CUDA acceleration}
}
Issues: GitHub issue tracker for bug reports and feature requests
Discussions: GitHub discussions for questions and community support
Email: matiasnhmb@gmail.com for licensing and technical inquiries
602 commits
Python
92.9%
Cuda
2.0%
C++
1.8%
HTML
1.8%
Shell
1.2%
Production Transformer Training Framework with MoE/MoD Architecture & CUDA Acceleration
Demo Architecture CUDA Acceleration Configuration API Licensing
Adaptive Training System is a production-grade transformer training framework implementing Mixture of Experts (MoE) and Mixture of Depths (MoD) architectures with autonomous training optimization and custom CUDA acceleration kernels. Supports models from 500M to 300B+ parameters with enterprise infrastructure.
Core capabilities:
Framework positioning:
This is a complete training system with custom CUDA kernels, not a model zoo or API wrapper. Every component from tokenization to fused gradient operations is included. MoE and MoD implementations follow established research (Switch Transformer, Mixture of Experts, Mixture-of-Depths) with operational additions and CUDA-accelerated execution: dynamic expert management, capacity tuning, load balancing, routing analytics.
The adaptive orchestrator monitors 20+ metrics every N steps and triggers interventions across hyperparameters, architecture, and recovery procedures. Maintains decision history with confidence scoring to prevent excessive intervention.
Custom CUDA kernels provide 2-7x speedup over PyTorch implementations for critical operations while maintaining gradient compatibility and numerical stability. Metal shaders provide 2-5x speedup on Apple Silicon (M1-M4). All kernels include automatic fallback to PyTorch when accelerated backends are unavailable.
Intended for:
Not included:
Standard architecture with LLaMA/GPT-NeoX design patterns:
Parameter calculation:
Token-level sparse activation via learned routing to specialized FFN networks with CUDA-accelerated dispatch.
Routing mechanism:
Load balancing:
Dynamic management:
CUDA acceleration:
Efficiency:
Statistics tracked:
Layer-level sparse activation via learned skip decisions.
Core concept: Model learns which tokens require full layer computation vs. residual skip. Routing decision per token per layer based on token representation at layer input.
Routing types:
Capacity management:
Efficiency:
Application strategies:
Training dynamics:
Combined token-level (MoE) and layer-level (MoD) sparsity with coordinated CUDA acceleration.
Architecture:
Sparsity compounding:
Training considerations:
Surgically "brand" your model checkpoints by fine-tuning them on specific trigger-response pairs. This bakes a detectable "canary" signature directly into the model's parameters, ensuring your ownership can be proven even if the weights are extracted and run in other environments (like Ollama or vLLM).
Utilize ZeRO-integrated CPU and NVMe offloading to train models that exceed your GPU VRAM capacity.
Automated system to build high-quality base training corpora from 100% legal, open-access sources.
High-performance deployment backends separate from the training stack.
Production-ready guardrails built into the training and serving pipeline.
Specialized Router Management:
gate_proj) while freezing other parameters. Helps specialize routing logic without catastrophic forgetting in experts.Custom CUDA kernels provide 2-7x speedup over PyTorch implementations for critical training operations. All kernels maintain full gradient compatibility and include automatic fallback.
1. Fused RMSNorm (3-4x faster)
2. Rotary Position Embeddings (2-4x faster)
3. SwiGLU Activation (2-3x faster)
4. MoE Operations (2-4x faster)
5. Fused Loss Computation
6. Fused Gradient Clipping
Custom kernels provide 27 speedup over vanilla PyTorch operations.
Compilation requirements:
# Install CUDA toolkit (11.8+ or 12.x)
# Verify nvcc availability
nvcc --version
# Optional: force target architectures (comma or semicolon separated)
# export CUDA_TARGET_SM=75,80,86,89,90
# Compile transformer + MoE kernels
cd Src/Main_Scripts/core
./compile_transformer_ops.sh
./compile_cuda_moe.sh
# Compile training kernels
cd ../training
./compile_kernels.sh
Automatic kernel detection: Framework automatically detects and loads compiled kernels at runtime. Falls back to PyTorch if kernels unavailable. No code changes required to use CUDA acceleration.
Automatic JIT rebuild for current hardware:
.so files are missing or compiled for the wrong SM target, runtime wrappers trigger a rebuild automatically.CUDA_TARGET_SM TORCH_CUDA_ARCH_LIST detected GPU compute capability fallback sm_75.CUDA_TARGET_SM when you need deterministic builds across machines.Supported architectures:
Performance monitoring:
from cuda_opt_wrapper import print_performance_summary
# After training
print_performance_summary()
# Shows per-operation timing, speedup metrics, throughput
All CUDA kernels maintain numerical stability equivalent to PyTorch:
Validation: Every kernel includes PyTorch fallback for correctness verification. Automated tests compare CUDA vs PyTorch outputs (tolerance: 1e-4 for FP32, 1e-3 for FP16).
Pre-configured architecture presets for training models from scratch, spanning 500K to 300B parameters. These are configuration templates, not pre-trained models.
Each preset specifies architecture dimensions, MoE/MoD parameters, hardware targets, and expected performance with CUDA acceleration for initializing and training new models.
| Config | Active Params | Total Params | Hidden | Layers | Heads | KV Heads | Experts | Top-K | Hardware | Memory (FP16) | Throughput | CUDA Speedup |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
debug | 500K | 4M | 128 | 2 | 2 | 2 | 8 | 2 | T4 | 50 MB | Verified | 2.1x |
debug_200m | 200M | 6B | 768 | 12 | 12 | 12 | 32 MoD | - | T4 | 2 GB | Verified | 2.8x |
b1 | 1B | 8B | 1024 | 24 | 16 | 4 | 8 | 2 | T4 (Projected) | 8 GB | ~1400 tok/s* | 3.2x* |
b7 | 7B | 56B | 4096 | 32 | 32 | 8 | 8 | 2 | Untested | 28 GB | Projected | Theoretical |
b14 | 14B | 112B | 5120 | 40 | 40 | 10 | 8 | 2 | Untested | 56 GB | Projected | Theoretical |
b30 | 30B | 240B | 8192 | 48 | 64 | 16 | 8 | 2 | Untested | 120 GB | Projected | Theoretical |
b50 | 50B | 400B | 10240 | 56 | 80 | 20 | 8 | 2 | Untested | 200 GB | Projected | Theoretical |
b100 | 100B | 800B | 12288 | 80 | 96 | 24 | 8 | 2 | Untested | 400 GB | Projected | Theoretical |
b200 | 200B | 1.6T | 16384 | 100 | 128 | 32 | 8 | 2 | Untested | 800 GB | Projected | Theoretical |
b300 | 300B | 2.4T | 20480 | 120 | 160 | 40 | 8 | 2 | Untested | 1.2 TB | Projected | Theoretical |
[!IMPORTANT] Performance Disclaimer: All benchmarks and throughput estimates provided are either verified on an NVIDIA T4 GPU or calculated as theoretical projections. Results on other hardware or larger scales are untested and listed for architectural reference only. Performance will vary based on your specific environment.
Memory estimates: Include model weights, optimizer states (Adam: 8 bytes/param), gradients, and activation memory at batch_size=1, mixed precision training. Actual memory scales with batch size and sequence length.
Throughput estimates: With CUDA acceleration enabled at batch_size=1, sequence_length=2048, mixed precision with gradient checkpointing. CUDA speedup column shows combined acceleration from all custom kernels vs. pure PyTorch.
Configuration selection:
debug for pipeline validation, debug_200m for architecture testingb1 for prototyping on consumer hardware with CUDA accelerationb7 for quality/efficiency balance with significant CUDA speedupb30+ for maximum model capacityb100+ requires cluster infrastructure and distributed expertiseImportant:
These presets define untrained model architectures. Training starts from random initialization following standard practices (Xavier/Kaiming initialization for weights, zero initialization for biases). The framework does not provide pre-trained checkpoints.
Customization:
All presets are starting points. Architecture dimensions can be modified: hidden_size must be divisible by num_heads. Intermediate_size typically 8/3 hidden_size rounded to nearest 256 for optimal CUDA performance. Max_position_embeddings determines context window. Num_experts and moe_top_k can be adjusted independently. MoD capacity_factor controls compute/quality tradeoff. CUDA kernels automatically adapt to configuration changes.
Numerical formats for parameters, activations, and gradients during training and inference.
FP32 (Float32) - Full Precision
FP16 (Float16) - Half Precision
BF16 (BFloat16) - Brain Float16
Mixed Precision FP16
Mixed Precision BF16
FP8 (Float8) - Experimental
INT8 Quantization
The framework detects hardware and selects optimal precision with CUDA kernel compatibility:
Detection logic:
mixed_bf16 with BF16-optimized kernelsmixed_fp16 with FP16-optimized kernelsfp16 (BF16 not supported, CUDA kernels unavailable)fp32 (reduced precision offers no benefit, CUDA kernels unavailable)Override: Set precision explicitly via configuration if automatic selection is suboptimal or for specific debugging/testing requirements.
Quantization & Inference:
Model Compatibility:
transformers for dataset loading and tokenization.NVIDIA Ampere/Ada/Hopper (A100, RTX 3090/4090, H100, H200):
mixed_bf16 with full CUDA acceleration (4-5x total speedup)mixed_fp16 (if BF16 causes unexpected issues)fp8_e4m3 (H100+ only, experimental, custom kernels in development)NVIDIA Volta/Turing (V100, T4, RTX 2080/2080Ti):
mixed_fp16 with CUDA acceleration (3-4x speedup)fp32 (if stability issues, 2-3x CUDA speedup maintained)Apple Silicon (M1/M2/M3/M4, Mac Studio, MacBook Pro):
fp16 (CUDA kernels unavailable, PyTorch fallback)CPU (Intel/AMD/ARM):
fp32 (CUDA kernels unavailable, PyTorch fallback)Training precision: Format used during forward pass, backward pass, and gradient computation Inference precision: Format used during validation and evaluation Master precision: Format for optimizer's master parameter copy (typically FP32 in mixed precision) CUDA kernel precision: Automatic selection based on training precision
Separate training/inference precision:
Common pattern: Train in mixed_bf16 for speed with CUDA acceleration, evaluate in fp32 for precise metrics. Or train in mixed_fp16 with CUDA kernels, deploy in int8 for inference.
Loss scaling parameters (FP16 only):
init_scale: Initial loss scaling factor (default: 2^16)scale_factor: Multiplier for scale adjustment (default: 2.0)scale_window: Steps without overflow before increasing scale (default: 2000)min_scale: Minimum scale factor (default: 1.0)Dynamic loss scaling adjusts automatically: scale increases every scale_window steps without overflow, decreases on overflow detection (NaN/Inf gradients). CUDA kernels maintain numerical stability with loss scaling. Most users do not need to modify these parameters.
Free GPU training demonstration requiring no local setup with CUDA acceleration showcase.
Environment:
Configuration:
debug preset (14m total, 2m active, 8 experts, 2 top-k)Observable behaviors:
Limitations:
Requirements:
Installation:
git clone https://github.com/matn23/AdaptiveTrainingSystem
cd AdaptiveTrainingSystem
pip install -r requirements.txt
# Compile CUDA kernels (optional but recommended for 3-5x speedup)
cd Src/Main_Scripts/core
./compile_transformer_ops.sh
./compile_cuda_moe.sh
cd ../training
./compile_kernels.sh
# Verify kernel compilation
python -c "from cuda_opt_wrapper import TRANSFORMER_OPS_AVAILABLE; print(f'CUDA ops: {TRANSFORMER_OPS_AVAILABLE}')"
cd ../..
python Main.py
Optional dependencies:
Quick start:
Default configuration uses debug preset for rapid testing. System auto-detects hardware, compiles CUDA kernels if nvcc available, selects precision, validates data, initializes model, begins training with acceleration.
Resume from checkpoint:
python Main.py --resume path/to/checkpoint.pt
Restores model state, optimizer state, scheduler, training step counter, random seeds, CUDA kernel state.
CUDA kernel management:
# Check kernel status
python -c "from moe_cuda_wrapper import print_performance_summary; print_performance_summary()"
# Recompile kernels after update
cd Src/Main_Scripts/core
./compile_transformer_ops.sh
./compile_cuda_moe.sh
cd ../training
./compile_kernels.sh
# Disable CUDA acceleration (for debugging)
# Set in config:
# use_cuda: false
# use_fused_rope/use_fused_swiglu/use_fused_moe/use_fused_loss/use_fused_grad_clip: false
Four data handling strategies for different use cases, all compatible with CUDA acceleration.
Raw text without conversational structure. For domain-specific pre-training, continued pre-training, language modeling research.
Data format:
Processing: Tokenize and split into fixed-length sequences with optional overlap (stride parameter). CUDA-accelerated tokenization for large corpora.
Loss: Applied to all tokens (causal language modeling) with fused loss computation kernel.
Conversational data with role annotations. For instruction tuning, chat models, task-specific adaptation.
Data format: JSONL with "conversation" field containing list of messages. Each message has "role" (system/user/assistant) and "content".
Processing: Concatenate messages with special tokens marking roles: [BOS] system [SEP] user [SEP] assistant [EOS]. CUDA-accelerated tokenization and batching.
Loss: Can mask user tokens (loss only on assistant responses) or compute on all tokens. Fused loss kernel handles masking efficiently.
Two-phase training: base corpus then conversational data. Builds general understanding, then adapts to conversation.
Configuration: Separate epoch counts per phase. Optional learning rate warmup between phases to handle distribution shift. CUDA acceleration maintained across phase transitions.
Use cases: Domain adaptation (medical literature clinical QA), continual learning (new data maintained task performance).
Mix base and conversational data within batches/epochs. Maintains general capabilities while learning conversation. Prevents catastrophic forgetting.
Mixing ratio: base_ratio controls proportion (e.g., 0.7 = 70% base, 30% conversational).
Strategies:
Use cases: General-purpose chat models, multi-task learning with auxiliary objectives.
State machine monitoring training every N steps (default: 100). Triggers interventions across 18 methods when confidence threshold exceeded (default: 0.75). Monitors CUDA kernel performance and adjusts strategies accordingly.
Monitored metrics:
Intervention categories:
Decision process:
MoE Architecture Management (3 methods):
add_expert(layer_idx): Add expert to underutilized layer when average utilization > thresholdprune_expert(layer_idx, expert_idx): Remove expert with utilization < threshold_initialize_new_expert(new_expert, existing_experts): Initialize from existing with noiseMoE Routing Control (4 methods):
adjust_capacity_factor(factor): Modify token capacity per expertadjust_routing_temperature(temp): Control routing sharpness (lower = more concentrated)enable_expert_dropout(prob): Regularization via random expert droppingget_expert_statistics(): Retrieve utilization, entropy, load balance loss, tokens droppedMoD Control (2 methods):
adjust_mod_capacity(factor): Change fraction of tokens using full computationget_mod_statistics(): Retrieve capacity factor, tokens processed, average depthBatch Size Adaptation (2 methods):
adjust_batch_size(new_size): Change micro batch size (typically for OOM recovery)_recreate_dataloader(dataset): Rebuild dataloader after batch size changeEmergency Recovery (2 methods):
emergency_lr_reduction(factor): Reduce learning rate by factor (for gradient explosion)rollback_steps(num_steps): Revert to earlier checkpoint (for divergence)Optimizer Adjustments (2 methods):
adjust_weight_decay(value): Modify regularization strength_update_optimizer_param_groups(param, value): Internal parameter group updateReal-time Metrics (3 methods):
get_current_metrics(): Query loss, LR, gradient norm, throughput, CUDA stats_extract_moe_routing_stats(): Internal MoE statistics extraction_calculate_throughput(): Compute tokens/second with CUDA performance breakdownPerformance Optimization (2 methods):
optimize_cuda_performance(): Analyze and tune CUDA kernel usageget_cuda_performance_stats(): Detailed per-kernel timing and efficiency metricsAutomatic training duration calculation following compute-optimal scaling laws (Hoffmann et al., 2022) with CUDA-aware compute budgets.
Formula: N_optimal_tokens = multiplier model_parameters
Default multiplier: 20 (configurable: 10-50)
Process:
N_opt = 20 total_parameterseffective_N_opt = N_opt / speedup_factorepochs = N_opt / dataset_tokensEnhanced features:
Runtime integration:
System calculates optimal duration at training start with CUDA performance estimates. Displays token budget, coverage percentage (dataset_tokens / optimal_tokens), recommended epochs, expected CUDA speedup. During training, prints status every N steps: current progress, convergence score, training phase (warming/learning/convergence), efficiency trend, CUDA performance metrics, recommendations (continue/adjust/stop).
Platform-specific optimizations automatically applied based on detected hardware with CUDA acceleration where available.
Automatic optimizations:
mixed_bf16 for Ampere+, mixed_fp16 for Volta/TuringConfiguration parameters:
use_flash_attention: Enable Flash Attention 2.x (2-4 attention speedup)use_fused_rmsnorm: Enable fused RMSNorm kernel (default profile: false)use_fused_rope: Enable fused RoPE kernel (default profile: true)use_fused_swiglu: Enable fused SwiGLU kernel (default profile: true)use_fused_moe: Enable CUDA MoE routing/dispatch kernels (default profile: true)use_fused_loss: Enable fused loss kernel (default profile: true)use_fused_grad_clip: Enable fused gradient clipping kernel (default profile: true)validate_moe_cuda_indices: Extra safety checks for CUDA MoE indices (default: false, slower)force_dense_expert_grads: Force dense expert gradient paths (default: false, slower)routing_stats_update_interval: Routing stats sync cadence (default: 64 steps)gradient_checkpointing: Trade compute for memory (enables larger models)compile: PyTorch 2.0 compilation (5-30% additional speedup)use_deepspeed: Enable DeepSpeed for multi-GPUzero_stage: ZeRO optimization level (0-3)DeepSpeed ZeRO stages:
Memory optimization:
CUDA kernel performance:
Custom Metal Shaders (NEW):
Metal shader compilation:
cd Src/Main_Scripts/core
./compile_metal.sh
Automatic optimizations:
Limitations:
Recommendations:
debug or debug_200m presets for testingAutomatic settings:
Optimizations:
Expectations:
Memory-efficient data loading with zero-copy operations, automatic caching, and CUDA-accelerated preprocessing.
Features enabled:
Data intelligence:
Preprocessing pipeline:
Statistics tracked:
Validation:
System validates all data paths before training. Checks: file existence, readability, size, format correctness. Prints summary: file count, total size, samples per file, estimated CUDA preprocessing speedup. Reports errors: missing files, corrupt formats, empty files.
Comprehensive metrics tracked during training with real-time logging, experiment tracking integration, and CUDA performance monitoring.
Core metrics:
MoE-specific metrics:
MoD-specific metrics:
Chinchilla metrics:
CUDA performance metrics:
Logging configuration:
Output destinations:
Health checks:
Orchestrator performs comprehensive health assessment every N steps:
Health check output includes status (healthy/warning/critical), detected issues, recommended interventions, confidence scores, CUDA performance summary.
Throughput measurements on reference hardware configurations with and without CUDA acceleration. All benchmarks use sequence_length=2048, batch_size optimized per GPU, mixed precision training with gradient checkpointing.
Google Colab T4 (15.8GB, Turing, sm_75):
NVIDIA RTX 3090 (24GB, Ampere, sm_80):
NVIDIA A100 40GB (Ampere, sm_80):
NVIDIA A100 80GB (Ampere, sm_80):
NVIDIA H100 80GB (Hopper, sm_90):
Apple M1 Max (32GB unified, MPS):
Apple M2 Ultra (128GB unified, MPS):
4 A100 80GB (DeepSpeed ZeRO-2 + CUDA):
8 A100 80GB (DeepSpeed ZeRO-3 + CUDA):
16 H100 80GB (DeepSpeed ZeRO-3 + expert parallelism + CUDA):
Scaling efficiency factors:
CUDA Custom Kernels (3-5 overall):
Flash Attention (Ampere+):
PyTorch Compilation (torch.compile):
Gradient Checkpointing:
Mixed Precision:
Per-kernel breakdown (b7 model, A100):
Operation | PyTorch | CUDA | Speedup | % Time
-------------------|---------|-------|---------|--------
RMSNorm | 45ms | 12ms | 3.8 | 18%
RoPE | 38ms | 6ms | 6.3 | 9%
SwiGLU | 62ms | 24ms | 2.6 | 22%
MoE Routing | 28ms | 9ms | 3.1 | 11%
MoE Dispatch | 42ms | 14ms | 3.0 | 15%
MoE Combine | 35ms | 11ms | 3.2 | 13%
Loss Computation | 18ms | 5ms | 3.6 | 6%
Other Operations | 52ms | 48ms | 1.1 | 6%
-------------------|---------|-------|---------|--------
Total per batch | 320ms | 129ms | 2.5 | 100%
Effective tokens/s | 195 | 680 | 3.5 |
Note: Effective speedup higher than per-operation average due to reduced overhead and better GPU utilization.
MoE Architecture Management:
add_expert(layer_idx: int) -> None
prune_expert(layer_idx: int, expert_idx: int) -> None
MoE Routing Control:
adjust_capacity_factor(factor: float) -> None
adjust_routing_temperature(temperature: float) -> None
enable_expert_dropout(dropout_prob: float) -> None
get_expert_statistics() -> Dict
MoD Control:
adjust_mod_capacity(capacity_factor: float) -> None
get_mod_statistics() -> Dict
Batch Management:
adjust_batch_size(new_batch_size: int) -> None
Emergency Recovery:
emergency_lr_reduction(reduction_factor: float) -> None
rollback_steps(num_steps: int) -> None
Optimizer Control:
adjust_weight_decay(weight_decay: float) -> None
Metrics Query:
get_current_metrics() -> Dict
CUDA Performance:
get_cuda_performance_stats() -> Dict
optimize_cuda_performance() -> None
Lower layer capacity factors reduce FLOPs without significantly affecting performance.
Model architecture:
hidden_size: Embedding and hidden dimension (128-20480, prefer multiples of 256 for CUDA efficiency)num_layers: Transformer layer count (2-120)num_heads: Attention head count (2-160)num_kv_heads: KV cache heads for GQA (2-40, typically num_heads/4)intermediate_size: FFN intermediate dimension (typically 8/3 hidden_size, round to 256 for CUDA)max_position_embeddings: Maximum sequence length (128-32768)vocab_size: Tokenizer vocabulary size (typically 32000-100000)MoE parameters:
use_moe: Enable MoE (boolean)num_experts: Expert count per layer (4-64, typically 8)moe_top_k: Experts activated per token (1-4, typically 2)capacity_factor: Token capacity multiplier (1.0-2.0, typically 1.25)load_balancing_weight: Auxiliary loss coefficient (0.001-0.1, typically 0.01)routing_temperature: Softmax temperature (0.1-2.0, typically 1.0)MoD parameters:
use_mod: Enable MoD (boolean)mod_capacity_factor: Fraction using full computation (0.1-1.0, typically 0.5)mod_routing_type: Routing mechanism ('learned', 'static', 'random')mod_start_layer: First layer with MoD (0-num_layers)mod_end_layer: Last layer with MoD (None = all layers)Training parameters:
num_epochs: Training duration in epochs (1-100)batch_size: Micro batch size per GPU (1-128)gradient_accumulation_steps: Accumulation before optimizer step (1-128)learning_rate: Optimizer learning rate (1e-5 to 1e-3)weight_decay: L2 regularization (0.0-0.1, typically 0.01)gradient_clip_val: Gradient norm clipping (0.5-5.0, typically 1.0)warmup_steps: Learning rate warmup duration (steps or fraction)Precision parameters:
precision: Training precision ('auto', 'fp32', 'fp16', 'bf16', 'mixed_fp16', 'mixed_bf16', 'fp8_e4m3')inference_precision: Evaluation precision (same options as training)Optimization parameters:
use_flash_attention: Enable Flash Attention (boolean, auto-detected)use_fused_rmsnorm: Enable fused RMSNorm kernel (boolean, default false)use_fused_rope: Enable fused RoPE kernel (boolean, default true)use_fused_swiglu: Enable fused SwiGLU kernel (boolean, default true)use_fused_moe: Enable CUDA MoE routing/dispatch kernels (boolean, default true)use_fused_loss: Enable fused loss kernel (boolean, default true)use_fused_grad_clip: Enable fused gradient clipping kernel (boolean, default true)validate_moe_cuda_indices: Enable strict CUDA MoE index validation (boolean, default false)force_dense_expert_grads: Force dense expert gradient path for all experts (boolean, default false)routing_stats_update_interval: Steps between routing stats sync/updates (int, default 64)mod_routing_stats_update_interval: Steps between MoD stats updates (int, default 64)metric_history_size: Bounded in-memory training metric window (int, default 2048)routing_history_size: Bounded in-memory routing metric window (int, default 512)gradient_checkpointing: Activation checkpointing (boolean)compile: PyTorch 2.0 compilation (boolean)use_deepspeed: Enable DeepSpeed (boolean)zero_stage: ZeRO optimization level (0-3)cpu_offload: Offload optimizer to CPU (boolean)Data parameters:
training_mode: Data handling ('base_only', 'finetuning_only', 'hybrid_sequential', 'hybrid_interleaved')base_paths: List of base training filesfinetuning_paths: List of fine-tuning filesbase_eval_paths: Base validation filesfinetuning_eval_paths: Fine-tuning validation filesbase_ratio: Mixing ratio for interleaved mode (0.0-1.0)mask_user_tokens: Mask user messages in loss (boolean)pin_memory: Pinned host memory for faster CPUGPU transfer (boolean, default true on CUDA)prefetch_factor: DataLoader prefetch depth when num_workers > 0 (int, default 4)Orchestrator parameters:
use_adaptive_training: Enable orchestrator (boolean)intervention_threshold: Confidence required for intervention (0.0-1.0, typically 0.75)check_interval: Steps between health checks (10-1000, typically 100)enable_emergency_recovery: Allow emergency interventions (boolean)enable_architecture_adaptation: Allow architecture changes (boolean)Chinchilla parameters:
auto_epoch_scaling: Enable automatic epoch calculation (boolean)chinchilla_multiplier: Token multiplier (5-50, typically 20)min_auto_epochs: Minimum epochs (1-10)max_auto_epochs: Maximum epochs (10-100)enable_loss_landscape: Track loss patterns (boolean)enable_compute_efficiency: Track efficiency metrics (boolean)enable_early_stopping: Allow early termination (boolean)Checkpoint parameters:
save_every_n_batches: Checkpoint interval in steps (100-10000)save_total_limit: Maximum checkpoints to keep (1-100)early_stopping_patience: Epochs without improvement before stopping (3-20)CUDA parameters:
cuda_kernel_path: Path to compiled CUDA kernels (default: auto-detect)enable_cuda_profiling: Enable detailed kernel profiling (boolean)cuda_profile_interval: Steps between profiling snapshots (1000-10000)Automatic handling: Orchestrator detects OOM exceptions, reduces batch size by 50%, recreates dataloader, resumes training from last checkpoint. CUDA kernel buffers automatically adjusted.
Manual interventions:
batch_size: Start with 1-2 for very large modelsgradient_accumulation_steps: Maintains effective batch size with less memorygradient_checkpointing: Trades compute for memory (recompute activations)zero_stage: 123 for progressively more memory optimizationcpu_offload: Moves optimizer states to CPU (slower but massive memory savings)max_position_embeddings: Shorter sequences use less memoryuse_fused_* = false) or set use_cuda=falseMemory estimation: Model memory (FP16) 2 bytes total_parameters Optimizer memory (Adam) 8 bytes parameters Gradient memory 2 bytes parameters Activation memory 2 batch_size sequence_length num_layers hidden_size CUDA kernel buffers 100-500 MB (temporary buffers) Total 12-16 bytes per parameter + activation memory + kernel overhead
Gradient explosion: Symptoms: Loss becomes NaN, gradient norm > 100, rapid loss increase
Automatic recovery: Orchestrator detects high gradient norm, triggers emergency LR reduction (10), rolls back to previous checkpoint, resumes with lower LR. CUDA fused gradient clipping prevents most explosions.
Manual fixes:
learning_rate: Try 10 reductiongradient_clip_val: Clip at lower threshold (0.5 instead of 1.0)use_fused_* = false temporarilyLoss divergence: Symptoms: Loss increases consistently, validation loss >> training loss, sudden loss spikes
Automatic recovery: Orchestrator detects divergence pattern, rolls back N steps, adjusts learning rate, may modify architecture parameters.
Manual fixes:
learning_rate: Start 3-5 lowerweight_decay: Stronger regularization (0.1 instead of 0.01)Expert collapse (MoE): Symptoms: All tokens route to 1-2 experts, routing entropy < 1.0, most experts have near-zero utilization
Automatic recovery: Orchestrator detects imbalance, increases load_balancing_weight, adjusts routing_temperature, may prune/add experts. CUDA routing kernel continues to function correctly during recovery.
Manual fixes:
load_balancing_weight: Try 0.02 or 0.05 (from 0.01)capacity_factor: Allow more tokens per expert (1.5 or 2.0)routing_temperature: Higher values (1.5-2.0) encourage uniform routingexpert_dropout: Forces routing to all expertsAutomatic optimization: Orchestrator monitors throughput, detects degradation, suggests optimizations (enable compilation, adjust batch size, check data loading bottlenecks, verify CUDA kernel usage).
Manual optimizations:
compile: PyTorch 2.0 compilation (5-30% speedup)use_fused_rope, use_fused_swiglu, use_fused_moe, use_fused_loss, use_fused_grad_clipuse_fused_rmsnorm=false unless profiling shows a gain on your workload/GPUuse_flash_attention: 2-4 attention speedup on Ampere+mixed_bf16 or mixed_fp16: 2 speedup over FP32num_workers: Parallelize data loading (typically 4-8)pin_memory=true and tune prefetch_factor (typically 2-8)batch_size: Better GPU utilization (if memory allows)gradient_checkpointing: Faster but more memoryenable_cuda_profiling=True to identify bottlenecksBottleneck identification:
Common issues:
Solutions:
compile=False: Disable compilation if unstablenum_workers=0: MPS prefers single-threaded data loadinguse_fused_rmsnorm/use_fused_rope/use_fused_swiglu/use_fused_moe/use_fused_loss/use_fused_grad_clip)batch_size: Start conservative (2-4)Corruption: Symptoms: Checkpoint fails to load, missing keys, size mismatch
Recovery: System automatically tries previous checkpoints (latest latest-1 best validation). If all corrupt, restart from initialization.
Prevention: Enable save_total_limit > 3, save to reliable storage, validate checksums. CUDA kernel state saved separately for recovery.
Resume failures: Symptoms: Training resumes but loss resets, optimizer state lost, different results than before
Causes: Incomplete checkpoint save, random seed mismatch, configuration mismatch, CUDA kernel version change
Solutions: Verify checkpoint integrity before resume, ensure configuration matches checkpoint, check random seed restoration, recompile CUDA kernels if updated.
Format errors: Symptoms: Training fails during data loading, "invalid JSON" or "unexpected format" errors
Solutions: Validate data format with provided validation scripts, check for: missing fields, incorrect JSON structure, encoding issues (use UTF-8), empty files or lines.
Quality problems: Symptoms: Training succeeds but poor results, high validation loss, model outputs nonsense
Causes: Data contamination, label errors, poor quality samples, distribution mismatch
Solutions: Enable automatic_data_cleaning, increase quality_threshold, manually inspect samples, check train/validation split, verify preprocessing correctness.
Compilation failures: Symptoms: Kernels fail to compile, nvcc errors, missing libraries
Solutions:
nvcc --versionsudo apt-get install build-essentialcd Src/Main_Scripts/core && ./compile_transformer_ops.sh && ./compile_cuda_moe.sh && cd ../training && ./compile_kernels.shRuntime errors: Symptoms: CUDA kernel crashes, incorrect results, NaN outputs
Solutions:
CUDA_LAUNCH_BLOCKING=1use_fused_* = false (or use_cuda=false) to isolate issuePerformance issues: Symptoms: CUDA kernels slower than expected, low speedup, high overhead
Solutions:
enable_cuda_profiling=Trueget_cuda_performance_stats()Considerations for deploying trained models in production environments.
Checkpoint format: Standard PyTorch state dict compatible with transformers library. Can export to HuggingFace format, ONNX (for inference optimization), TorchScript (for deployment), or TensorRT (for NVIDIA inference).
Conversion process:
Size optimization:
Quantization strategies:
Batching:
KV cache management:
Serving frameworks:
Inference metrics:
Model drift detection:
Adaptive Training System is released under the Apache License 2.0.
This means you are free to:
Please see the LICENSE file for the full legal text.
Evaluation / Demo: The demo notebook and local installation are provided for testing purposes. All core features including custom CUDA kernels are available under the Apache 2.0 license.
Adaptive Training Manual: docs/adaptive_training.md
MoE/MoD Tutorial: docs/sparse_architectures.md
MoE/MoD Tutorial: docs/adapters.md
MoE/MoD Tutorial: docs/cuda_acceleration.md
@software{AdaptiveTrainingSystem2025,
title = {Adaptive Training System: Modular Transformer Training with MoE/MoD},
author = {MatN23},
year = {2025},
url = {https://github.com/matn23/AdaptiveTrainingSystem},
note = {Production-grade training framework with adaptive optimization and CUDA acceleration}
}
Issues: GitHub issue tracker for bug reports and feature requests
Discussions: GitHub discussions for questions and community support
Email: matiasnhmb@gmail.com for licensing and technical inquiries
602 commits
Python
92.9%
Cuda
2.0%
C++
1.8%
HTML
1.8%
Shell
1.2%