This document provides a comprehensive reference for all public APIs in the LM-Trainer library.
lm_trainer/
├── cli/ # Command-line interface tools
├── core/ # Core utilities, exceptions, and constants
├── data/ # Data loading and preprocessing
├── extensions/ # Third-party integrations (PEFT, Accelerate, etc.)
├── inference/ # Text generation and model serving
├── models/ # Model architectures and components
├── tokenizers/ # Tokenization utilities
├── training/ # Training loop, optimizers, and evaluation
└── utilities/ # Logging, monitoring, and system utilities
Base exception for all LM-Trainer errors.
Raised when there is an error in configuration.
Raised when there is an error during training.
Raised when there is a validation error.
Raised when there is an error in model serialization.
Default device setting ("auto").
Default data type (torch.float32).
Enhanced configuration for the training process with TRL-style parameters.
Attributes:
batch_size: Training batch size (int, default: 32)learning_rate: Learning rate (float, default: 1e-4)weight_decay: Weight decay coefficient (float, default: 0.01)num_epochs: Number of training epochs (int, default: 10)max_steps: Maximum number of training steps (Optional[int], default: None)lr_scheduler: Learning rate scheduler type (str, default: "cosine")warmup_steps: Number of warmup steps (int, default: 1000)warmup_ratio: Ratio of warmup steps (float, default: 0.1)min_lr_ratio: Minimum learning rate ratio (float, default: 0.1)optimizer: Optimizer type (str, default: "adamw")beta1: Beta1 parameter for Adam optimizers (float, default: 0.9)beta2: Beta2 parameter for Adam optimizers (float, default: 0.999)eps: Epsilon parameter for optimizers (float, default: 1e-8)max_grad_norm: Maximum gradient norm for clipping (float, default: 1.0)gradient_accumulation_steps: Gradient accumulation steps (int, default: 1)use_amp: Use automatic mixed precision (bool, default: True)amp_dtype: AMP data type (str, default: "float16")save_steps: Save checkpoint every N steps (int, default: 1000)save_total_limit: Maximum number of checkpoints to keep (int, default: 3)checkpoint_dir: Checkpoint directory (str, default: "./checkpoints")resume_from_checkpoint: Path to resume from (Optional[str], default: None)eval_steps: Evaluation steps (int, default: 500)eval_strategy: Evaluation strategy (str, default: "steps")eval_accumulation_steps: Evaluation accumulation steps (Optional[int], default: None)logging_steps: Logging steps (int, default: 100)log_level: Log level (str, default: "info")report_to: Reporting backends (List[str], default: ["tensorboard"])dataloader_num_workers: Number of data loader workers (int, default: 4)dataloader_pin_memory: Pin memory in data loader (bool, default: True)dataloader_drop_last: Drop last batch in data loader (bool, default: True)local_rank: Local rank for distributed training (int, default: -1)world_size: World size for distributed training (int, default: 1)distributed_backend: Distributed backend (str, default: "nccl")use_deepspeed: Use DeepSpeed (bool, default: False)deepspeed_config: DeepSpeed configuration path (Optional[str], default: None)use_accelerate: Use Accelerate (bool, default: False)accelerate_mixed_precision: Accelerate mixed precision (str, default: "no")use_peft: Use Parameter-Efficient Fine-Tuning (bool, default: False)peft_type: PEFT type (str, default: "lora")peft_r: LoRA rank (int, default: 8)peft_alpha: LoRA alpha (int, default: 16)peft_dropout: LoRA dropout (float, default: 0.05)peft_target_modules: Target modules for PEFT (Optional[List[str]], default: None)peft_bias: LoRA bias setting (str, default: "none")peft_task_type: PEFT task type (str, default: "CAUSAL_LM")device: Device to use (str, default: "auto")force_cpu: Force CPU usage (bool, default: False)seed: Random seed (int, default: 42)early_stopping_patience: Early stopping patience (Optional[int], default: None)early_stopping_threshold: Early stopping threshold (float, default: 0.0)compile_model: Compile model (bool, default: False)compile_mode: Compilation mode (str, default: "default")auto_tune_batch_size: Auto-tune batch size (bool, default: False)use_gradient_compression: Use gradient compression (bool, default: False)gradient_as_bucket_view: Gradient as bucket view (bool, default: True)static_graph: Static graph optimization (bool, default: False)
Methods:
get_effective_device(): Get the effective deviceshould_use_amp(): Determine if AMP should be usedget_effective_distributed_backend(): Get effective distributed backendsave(path): Save configuration to fileload(path): Load configuration from fileto_dict(): Convert to dictionaryfrom_dict(config_dict): Create from dictionary
Configuration for Transformer model architecture.
Attributes:
vocab_size: Vocabulary size (int, default: 50000)d_model: Model dimension (int, default: 512)n_heads: Number of attention heads (int, default: 8)n_layers: Number of layers (int, default: 6)d_ff: Feed-forward dimension (int, default: 2048)max_seq_len: Maximum sequence length (int, default: 1024)dropout: Dropout rate (float, default: 0.1)attention_dropout: Attention dropout rate (float, default: 0.1)init_std: Initialization standard deviation (float, default: 0.02)use_learned_pos_emb: Use learned positional embeddings (bool, default: False)layer_norm_eps: Layer normalization epsilon (float, default: 1e-5)pre_norm: Use pre-normalization (bool, default: True)activation: Activation function (str, default: "gelu")use_bias: Use bias terms (bool, default: True)gradient_checkpointing: Use gradient checkpointing (bool, default: False)
Properties:
d_head: Dimension of each attention head
Methods:
save(path): Save configuration to fileload(path): Load configuration from fileto_dict(): Convert to dictionaryfrom_dict(config_dict): Create from dictionary
Base trainer class for training language models.
Methods:
__init__(model, train_dataloader, eval_dataloader, optimizer, scheduler, config, model_config, callbacks): Initialize trainertrain(): Run the training loopevaluate(): Evaluate the modelsave_checkpoint(metrics): Save a checkpointload_checkpoint(checkpoint_path): Load a checkpoint
Abstract base class for training callbacks.
Methods:
on_train_start(trainer): Called at the beginning of trainingon_train_end(trainer, results): Called at the end of trainingon_train_error(trainer, error): Called when training encounters an erroron_epoch_start(trainer, epoch): Called at the beginning of each epochon_epoch_end(trainer, epoch, metrics): Called at the end of each epochon_epoch_begin(trainer, epoch): Called at the beginning of epoch training phaseon_epoch_finish(trainer, epoch): Called at the end of epoch training phaseon_batch_start(trainer, batch_idx, batch): Called at the beginning of each training batchon_batch_end(trainer, batch_idx, batch, outputs): Called at the end of each training batchon_step_end(trainer, step): Called at the end of each training stepon_eval_start(trainer): Called at the beginning of evaluationon_eval_end(trainer, metrics): Called at the end of evaluationon_eval_batch_start(trainer, batch_idx, batch): Called at the beginning of each evaluation batchon_eval_batch_end(trainer, batch_idx, batch, outputs): Called at the end of each evaluation batch
Simple progress bar callback for training visualization.
TensorBoard logging callback for training metrics.
Early stopping callback to prevent overfitting.
Learning rate scheduler callback.
Model checkpoint callback for saving best models.
Manages model checkpoints during training.
Methods:
__init__(checkpoint_dir, max_checkpoints): Initialize checkpoint managersave_checkpoint(data, step, is_best, prefix): Save a checkpointload_checkpoint(checkpoint_path): Load a checkpointget_latest_checkpoint(): Get the latest checkpointget_best_checkpoint(): Get the best checkpointsave_training_state(...): Save complete training stateload_training_state(checkpoint_path): Load complete training state
Create an optimizer for the given model.
Parameters:
model: The model to optimizeoptimizer_type: Type of optimizerlearning_rate: Learning rateweight_decay: Weight decay coefficient**kwargs: Additional optimizer-specific parameters
Returns:
- Configured optimizer instance
Lion optimizer implementation.
Sophia optimizer implementation.
Create a learning rate scheduler.
Parameters:
optimizer: Optimizer to schedulescheduler_type: Type of schedulernum_warmup_steps: Number of warmup stepsnum_training_steps: Total number of training steps**kwargs: Additional scheduler-specific parameters
Returns:
- Configured learning rate scheduler
Linear warmup followed by cosine decay scheduler.
Linear warmup followed by linear decay scheduler.
Gradient clipping utility for preventing gradient explosion.
Gradient scaling utility for mixed precision training.
Compress gradients for efficient communication in distributed training.
Decompress gradients after communication in distributed training.
Calculate perplexity metric.
Calculate accuracy metric.
Calculate F1 score for text generation.
Calculate ROUGE scores (simplified version).
Calculate BLEU score (simplified version).
Unified metric calculator for multiple metrics.
Transformer model implementation.
Multi-head attention mechanism.
Feed-forward network.
Positional encoding layer.
Layer normalization.
Base tokenizer interface.
BPE tokenizer implementation.
WordPiece tokenizer implementation.
HuggingFace tokenizer wrapper.
Create a data loader.
Text dataset implementation.
Collate function for data loading.
Text preprocessing utility.
Base text generator class.
Greedy text generation.
Beam search text generation.
Sampling-based text generation.
Generate text using the specified method.
LoRA adapter for model fine-tuning.
Configuration for adapter layers.
Configuration for LoRA adaptation.
Apply LoRA adaptation to a model.
Get all LoRA parameters from a model.
Wrapper for HuggingFace Accelerator.
Distributed trainer using Accelerator.
Prepare model for distributed training.
Configuration for distributed training.
Initialize distributed training environment.
Synchronize model parameters across all processes.
Gather tensors from all processes.
Setup logging for the application.
Get a logger with the specified name.
Log training progress.
Log evaluation results.
System resource monitor.
Resource usage monitor for training processes.
Training process monitor.
Get comprehensive system information.
Check CUDA availability and get GPU information.
Get list of available GPU indices.
Estimate memory requirements for training.
Select the optimal device for computation.
Get available memory for a device.
Configure optimal batch size based on available memory.
Check if system meets minimum resource requirements.
Main training command.
Main generation command.
Main evaluation command.