Model Training - krishanth7/EveryO GitHub Wiki

Model Training

EveryO — Training Pipelines, Evaluation & Experiment Management

Prepare · Train · Validate · Monitor · Improve

Python EveryO Training License

A comprehensive guide to training neural networks with EveryO, including data loading, optimization, validation, callbacks, checkpointing, metrics, and reproducible experimentation.

Home · Neural Networks · Optimization · API Reference


Maintained By & Owner: EveryO Contributors & @krishanth7

Important

Version Compatibility

This documentation targets EveryO v0.2.0 and uses interfaces inspected from the repository's default branch.

Examples should be tested in your installed environment. Training behavior and numerical results depend on model initialization, data, and configuration.


Table of Contents

  1. Overview
  2. Training Architecture
  3. Development Environment
  4. Trainer API
  5. Dataset Preparation
  6. DataLoader Integration
  7. Model Construction
  8. Loss Functions
  9. Optimizer Configuration
  10. Complete Training Example
  11. Validation and Evaluation
  12. Training History
  13. Callbacks
  14. Early Stopping
  15. Model Checkpointing
  16. Learning-Rate Scheduling
  17. Gradient Clipping
  18. Experiment Tracking
  19. Reproducibility
  20. Performance Optimization
  21. Testing and Validation
  22. Troubleshooting
  23. Developer References
  24. Next Steps

1. Overview

Model training is the process of updating neural network parameters using examples, objective functions, and optimization algorithms.

EveryO provides a Trainer abstraction to coordinate training and evaluation.

1.1 Core Components

Component Responsibility
Dataset Stores training examples
DataLoader Produces batches
Model Computes predictions
Loss Function Measures prediction error
Optimizer Updates parameters
Trainer Coordinates the training loop
Callbacks Observe or influence training
History Records training metrics

1.2 Training Objectives

A reliable training workflow should support:

  • Correct gradient computation.
  • Stable parameter updates.
  • Data separation.
  • Metric monitoring.
  • Reproducibility.
  • Checkpoint management.
  • Error detection.
  • Performance measurement.

2. Training Architecture

2.1 Conceptual Pipeline

                  TRAINING DATA
                       |
                       v
                    DataLoader
                       |
                       v
                  Neural Network
                       |
                       v
                    Predictions
                       |
                       v
                   Loss Function
                       |
                       v
                 Backpropagation
                       |
                       v
                     Optimizer
                       |
                       v
                Updated Parameters
                       |
                       v
                  Next Mini-Batch

           Validation / Evaluation
                       |
                       v
                Metrics & History
                       |
                       v
                    Callbacks

2.2 Training Lifecycle

  1. Initialize the model.
  2. Prepare datasets.
  3. Configure loss.
  4. Configure optimizer.
  5. Initialize trainer.
  6. Execute training epochs.
  7. Evaluate validation data.
  8. Record metrics.
  9. Execute callbacks.
  10. Save results.

3. Development Environment

3.1 Install EveryO

git clone https://github.com/krishanth7/EveryO.git
cd EveryO

python -m pip install -e .

3.2 Development Installation

python -m pip install -e ".[dev]"

3.3 Verify Installation

import everyo as eo

print("EveryO version:", eo.__version__)

3.4 Dependencies

EveryO declares:

  • Python 3.9 or newer.
  • NumPy 1.22 or newer.
  • Matplotlib 3.5 or newer.

Optional integrations have additional requirements.


4. Trainer API

The Trainer class coordinates model training, evaluation, and inference.

4.1 Constructor

Trainer(
    model,
    optimizer,
    loss_fn,
    *,
    metrics=(),
    device="cpu",
    gradient_clip=None
)

4.2 Parameters

Parameter Description
model EveryO Module
optimizer EveryO optimizer bound to model parameters
loss_fn Callable producing loss
metrics Metric names or callables
device Execution device
gradient_clip Optional maximum global gradient norm

4.3 Initialization Example

import everyo as eo

model = eo.Sequential(
    eo.Linear(4, 8, seed=0),
    eo.ReLU(),
    eo.Linear(8, 2, seed=1)
)

optimizer = eo.Adam(
    model.parameters(),
    lr=0.001
)

trainer = eo.Trainer(
    model,
    optimizer,
    eo.CrossEntropyLoss(),
    metrics=["accuracy"],
    device="cpu"
)

4.4 Training Method

The inspected fit() signature is:

trainer.fit(
    train_loader,
    *,
    epochs=10,
    validation_loader=None,
    callbacks=(),
    verbose=True,
    log_every=1
)

4.5 Training Return Value

fit() returns an EveryO History object containing recorded epoch metrics.


5. Dataset Preparation

Good training results depend on reliable input data.

5.1 Data Requirements

  • Correct feature dimensions.
  • Valid target values.
  • Consistent data types.
  • Appropriate preprocessing.
  • Training and validation separation.
  • Protection against data leakage.

5.2 Example Dataset

import numpy as np

rng = np.random.default_rng(42)

features = rng.normal(
    size=(200, 4)
).astype("float32")

targets = (
    features.sum(axis=1) > 0
).astype("int64")

This synthetic dataset defines a binary classification task.

5.3 Dataset Shapes

Variable Shape
Features (200, 4)
Targets (200,)

5.4 Training and Validation Split

train_x = features[:160]
train_y = targets[:160]

val_x = features[160:]
val_y = targets[160:]

For this independently generated synthetic dataset, the example uses a straightforward split.

Real-world datasets should use an appropriate splitting strategy, including temporal or group-aware separation when needed.


6. DataLoader Integration

EveryO exports ArrayDataset and DataLoader.

6.1 Create Datasets

import everyo as eo

train_dataset = eo.ArrayDataset(
    train_x,
    train_y
)

val_dataset = eo.ArrayDataset(
    val_x,
    val_y
)

6.2 Create DataLoaders

train_loader = eo.DataLoader(
    train_dataset,
    batch_size=16
)

val_loader = eo.DataLoader(
    val_dataset,
    batch_size=16
)

6.3 Batch Size

Batch size determines how many examples are processed together.

For:

[ N=160 ]

and:

[ B=16 ]

the number of full batches is:

[ 160/16=10 ]

6.4 DataLoader Responsibilities

  • Batch construction.
  • Dataset iteration.
  • Input and target pairing.
  • Optional ordering controls.
  • Consistent batch shapes.

7. Model Construction

7.1 Classification Model

model = eo.Sequential(
    eo.Linear(4, 8, seed=0),
    eo.ReLU(),
    eo.Linear(8, 2, seed=1)
)

7.2 Architecture

Input Features: 4
       |
       v
Linear Layer: 8
       |
       v
ReLU Activation
       |
       v
Linear Layer: 2
       |
       v
Class Logits

7.3 Parameter Count

First layer:

[ 4\times8+8=40 ]

Second layer:

[ 8\times2+2=18 ]

Total:

[ P=58 ]

7.4 Model Design Considerations

  • Input feature count.
  • Output class count.
  • Hidden-layer size.
  • Activation selection.
  • Parameter initialization.
  • Computational cost.

8. Loss Functions

Loss functions quantify model prediction error.

8.1 Classification Loss

loss_fn = eo.CrossEntropyLoss()

8.2 Regression Loss

loss_fn = eo.MSELoss()

8.3 Available Loss Classes

Loss Typical Use
MSELoss Regression
MAELoss Regression
BCELoss Binary probability predictions
BCEWithLogitsLoss Binary logits
CrossEntropyLoss Multiclass classification

8.4 Important Distinction

Use a loss function that matches the output representation and target format.

For example, multiclass cross-entropy commonly expects logits and class-index targets.

Do not apply softmax unnecessarily before a loss implementation that already handles logits.


9. Optimizer Configuration

EveryO exports SGD and Adam.

9.1 SGD

optimizer = eo.SGD(
    model.parameters(),
    lr=0.01
)

9.2 Adam

optimizer = eo.Adam(
    model.parameters(),
    lr=0.001
)

9.3 Optimization Process

[ \theta_{t+1}

\theta_t-\eta\nabla_\theta L ]

The actual update depends on the selected optimizer.

9.4 Optimization Considerations

  • Learning rate.
  • Momentum.
  • Weight decay.
  • Gradient magnitude.
  • Numerical precision.
  • Optimizer state.

Related: Optimization


10. Complete Training Example

Objective: Train a binary classifier using EveryO's built-in training engine.

10.1 Full Python Example

import numpy as np
import everyo as eo

# ---------------------------------
# 1. Generate synthetic data
# ---------------------------------

rng = np.random.default_rng(42)

x = rng.normal(
    size=(200, 4)
).astype("float32")

y = (
    x.sum(axis=1) > 0
).astype("int64")

# ---------------------------------
# 2. Split the dataset
# ---------------------------------

train_x = x[:160]
train_y = y[:160]

val_x = x[160:]
val_y = y[160:]

# ---------------------------------
# 3. Create datasets
# ---------------------------------

train_dataset = eo.ArrayDataset(
    train_x,
    train_y
)

val_dataset = eo.ArrayDataset(
    val_x,
    val_y
)

# ---------------------------------
# 4. Create data loaders
# ---------------------------------

train_loader = eo.DataLoader(
    train_dataset,
    batch_size=16
)

val_loader = eo.DataLoader(
    val_dataset,
    batch_size=16
)

# ---------------------------------
# 5. Create model
# ---------------------------------

model = eo.Sequential(
    eo.Linear(4, 8, seed=0),
    eo.ReLU(),
    eo.Linear(8, 2, seed=1)
)

# ---------------------------------
# 6. Configure optimizer
# ---------------------------------

optimizer = eo.Adam(
    model.parameters(),
    lr=0.01
)

# ---------------------------------
# 7. Initialize trainer
# ---------------------------------

trainer = eo.Trainer(
    model,
    optimizer,
    eo.CrossEntropyLoss(),
    metrics=["accuracy"]
)

# ---------------------------------
# 8. Train model
# ---------------------------------

history = trainer.fit(
    train_loader,
    epochs=20,
    validation_loader=val_loader,
    verbose=False
)

# ---------------------------------
# 9. Evaluate model
# ---------------------------------

results = trainer.evaluate(val_loader)

print("Evaluation:", results)

# ---------------------------------
# 10. Inspect training history
# ---------------------------------

print("Completed epochs:", history.epochs)
print("Available metrics:", history.keys)

10.2 Expected Behavior

The script should:

  1. Generate synthetic training data.
  2. Construct a classifier.
  3. Execute training epochs.
  4. Evaluate validation data.
  5. Return training history.

Numerical results are not fixed and should be measured in the actual environment.


11. Validation and Evaluation

Validation measures model behavior on data outside the training subset.

11.1 Evaluation API

results = trainer.evaluate(val_loader)

11.2 Metrics

The trainer supports metric names and callable metrics.

Example:

metrics=["accuracy"]

11.3 Evaluation Results

Evaluation returns a dictionary of loss and metric values.

11.4 Recommended Evaluation Practices

  • Keep validation data separate.
  • Avoid preprocessing leakage.
  • Monitor both loss and task-specific metrics.
  • Compare against simple baselines.
  • Reserve an independent test set for final assessment.

12. Training History

EveryO's History object records per-epoch training information.

12.1 History Properties

API Description
history.records Recorded epoch dictionaries
history.epochs Number of recorded epochs
history.keys Available metric names
history.last() Latest epoch record
history.best() Best matching record
history.to_dict() Dictionary of metric series
history.to_json() Export JSON
history.to_csv() Export CSV

12.2 Inspect History

print(history.epochs)
print(history.keys)
print(history.last())

12.3 Access Loss History

loss_values = history["loss"]

print(loss_values)

12.4 Best Validation Epoch

best_epoch = history.best(
    key="val_loss",
    mode="min"
)

print(best_epoch)

12.5 Export History

history.to_json("runs/history.json")

history.to_csv("runs/history.csv")

13. Callbacks

Callbacks observe or influence the training process.

13.1 Available Callbacks

Callback Purpose
Callback Base callback class
EarlyStopping Stop on metric stagnation
ModelCheckpoint Save model checkpoints
LearningRateScheduler Adjust learning rate
CSVLogger Write training logs
ProgressLogger Report training progress

13.2 Callback Lifecycle

The inspected base class provides:

on_train_begin
      |
      v
on_epoch_begin
      |
      v
on_batch_begin
      |
      v
on_batch_end
      |
      v
on_epoch_end
      |
      v
on_train_end

Batch hooks repeat for each batch, while epoch hooks repeat for each epoch.

13.3 Custom Callback

import everyo as eo

class EpochReporter(eo.Callback):

    def on_epoch_end(self, trainer, epoch, logs):
        print(
            f"Epoch {epoch}:",
            logs
        )

Use it with:

history = trainer.fit(
    train_loader,
    epochs=10,
    callbacks=[EpochReporter()]
)

14. Early Stopping

Early stopping can end training when a monitored metric stops improving.

14.1 Constructor

EarlyStopping(
    monitor="val_loss",
    *,
    patience=5,
    min_delta=0.0,
    mode="min",
    restore_best_weights=True,
    verbose=True
)

14.2 Example

early_stopping = eo.EarlyStopping(
    monitor="val_loss",
    patience=5,
    mode="min",
    restore_best_weights=True
)

14.3 Training Integration

history = trainer.fit(
    train_loader,
    epochs=100,
    validation_loader=val_loader,
    callbacks=[early_stopping]
)

14.4 Parameters

Parameter Description
monitor Metric to monitor
patience Tolerated non-improving epochs
min_delta Minimum meaningful improvement
mode min or max
restore_best_weights Restore best model parameters
verbose Enable messages

14.5 Important Behavior

The inspected implementation stops when the non-improvement counter exceeds patience.

Restoring the best weights means the final model may correspond to an earlier epoch, not the last recorded epoch.


15. Model Checkpointing

Checkpoints preserve model state for later use.

15.1 Purpose

Checkpointing can support:

  • Model recovery.
  • Experiment comparison.
  • Best-model selection.
  • Reproducible evaluation.
  • Training continuation.

15.2 Public API

eo.ModelCheckpoint

15.3 Inspect Constructor

import inspect
import everyo as eo

print(
    inspect.signature(eo.ModelCheckpoint)
)

Use the inspected signature when configuring checkpoint paths, monitored metrics, or save conditions.

15.4 Recommended Checkpoint Metadata

  • Model architecture.
  • Parameter state.
  • Optimizer configuration.
  • Training epoch.
  • Validation metrics.
  • Framework version.
  • Dataset identifier.
  • Experiment configuration.

Warning

Saving model parameters alone may not preserve all optimizer or scheduler state needed for an exact training continuation.


16. Learning-Rate Scheduling

A learning-rate scheduler changes the optimizer's learning rate during training.

16.1 Public API

eo.LearningRateScheduler

16.2 Scheduling Strategies

Common strategies include:

  • Step decay.
  • Exponential decay.
  • Cosine scheduling.
  • Warmup.
  • Metric-dependent adjustment.

Availability of individual strategies depends on the callback implementation and supplied schedule function.

16.3 Inspect Constructor

import inspect
import everyo as eo

print(
    inspect.signature(
        eo.LearningRateScheduler
    )
)

16.4 Monitoring

Track the learning rate alongside:

  • Training loss.
  • Validation loss.
  • Gradient norms.
  • Training duration.

17. Gradient Clipping

Gradient clipping limits the magnitude of gradients before optimizer updates.

17.1 Trainer Configuration

The inspected Trainer constructor supports:

gradient_clip=1.0

17.2 Example

trainer = eo.Trainer(
    model,
    optimizer,
    eo.CrossEntropyLoss(),
    metrics=["accuracy"],
    gradient_clip=1.0
)

17.3 Global Norm Clipping

For gradient vector (g) and threshold (c):

[ g_{clipped}

g\cdot \min\left( 1,\frac{c}{|g|_2} \right) ]

for nonzero gradient norm.

17.4 Considerations

Clipping can help with excessively large gradients but does not replace proper numerical validation or learning-rate selection.


18. Experiment Tracking

Experiment tracking provides a record of model development.

18.1 Recommended Metadata

Field Description
Experiment ID Unique run identifier
Framework Version EveryO version
Dataset Dataset name or version
Model Architecture
Optimizer Algorithm and configuration
Learning Rate Initial learning rate
Batch Size Samples per batch
Epochs Training duration
Validation Metrics Evaluation results
Seed Reproducibility configuration

18.2 Example Directory

experiments/
 |
 +-- run-001/
 |    +-- config.json
 |    +-- history.json
 |    +-- history.csv
 |    +-- model-checkpoint
 |
 +-- run-002/
      +-- config.json
      +-- history.json
      +-- history.csv
      +-- model-checkpoint

18.3 History Export

history.to_json(
    "experiments/run-001/history.json"
)

history.to_csv(
    "experiments/run-001/history.csv"
)

19. Reproducibility

Reproducible training requires controlling relevant sources of variation.

19.1 Factors

  • Model initialization.
  • Dataset generation.
  • Data ordering.
  • Dependency versions.
  • Backend behavior.
  • Numerical precision.
  • Optimizer configuration.
  • Hardware.

19.2 Seeded Initialization

model = eo.Sequential(
    eo.Linear(4, 8, seed=42),
    eo.ReLU(),
    eo.Linear(8, 2, seed=43)
)

19.3 Recommended Practices

  • Record all relevant seeds.
  • Save configuration.
  • Pin dependencies.
  • Track the source commit.
  • Preserve evaluation datasets.
  • Document hardware.

A seed alone does not guarantee identical results across all platforms and environments.


20. Performance Optimization

Training performance depends on computation, memory, and data processing.

20.1 Optimization Areas

  • Batch size.
  • Model complexity.
  • Tensor dimensions.
  • Backend choice.
  • Numerical precision.
  • Data loading.
  • Intermediate allocations.

20.2 CPU and GPU

The CPU backend is the foundational execution path.

Optional acceleration requires supported hardware and a compatible implementation.

20.3 Benchmarking

Measure:

  1. Epoch duration.
  2. Batch throughput.
  3. Peak memory.
  4. Training loss.
  5. Validation metrics.
  6. Backend configuration.

20.4 Important Principle

Performance improvements must preserve acceptable numerical correctness.


21. Testing and Validation

Training code should be tested before being used for significant experiments.

21.1 Run Test Suite

python -m pytest

21.2 Recommended Tests

  • Dataset shapes.
  • DataLoader output.
  • Model forward pass.
  • Loss calculation.
  • Gradient generation.
  • Optimizer updates.
  • Training history.
  • Callback execution.
  • Validation metrics.
  • Checkpoint behavior.
  • Early stopping.
  • Error handling.

21.3 Minimal Smoke Test

import numpy as np
import everyo as eo

x = np.random.default_rng(0).normal(
    size=(32, 4)
).astype("float32")

y = (
    x.sum(axis=1) > 0
).astype("int64")

loader = eo.DataLoader(
    eo.ArrayDataset(x, y),
    batch_size=8
)

model = eo.Sequential(
    eo.Linear(4, 8, seed=0),
    eo.ReLU(),
    eo.Linear(8, 2, seed=1)
)

trainer = eo.Trainer(
    model,
    eo.Adam(model.parameters(), lr=0.01),
    eo.CrossEntropyLoss(),
    metrics=["accuracy"]
)

history = trainer.fit(
    loader,
    epochs=2,
    verbose=False
)

assert history.epochs == 2

22. Troubleshooting

Training loss does not decrease

Check learning rate, target encoding, model architecture, gradients, and preprocessing.

Validation accuracy is low

Inspect data distribution, class balance, preprocessing, model capacity, and overfitting.

Early stopping does not activate

Confirm the monitored metric exists in epoch logs and that the callback is supplied to fit().

For val_loss, provide a validation loader.

Training produces NaN loss

Inspect invalid numerical operations, gradient magnitude, input values, and learning rate.

Training is slow

Profile data loading, batch size, model complexity, and backend performance.

Checkpoint is not created

Verify callback configuration, monitored metrics, output paths, and file permissions.


23. Developer References

Resource Link
EveryO Repository GitHub
Trainer Implementation trainer.py
Callbacks callbacks.py
Training History history.py
Training Package training/
Data Package data/
Optimizers optim/
Tests tests/
Issues GitHub Issues

24. Next Steps

Continue with the following EveryO Wiki pages.

Page Focus
Data Pipeline Dataset processing and DataLoaders
Model Serialization Saving, loading, and checkpoints
Performance Optimization Profiling and benchmarking
Examples and Tutorials Practical workflows
API Reference Public framework interfaces

Wiki links become active after their corresponding pages are created.


Model Training — Documentation Prepared

Next Recommended Page: Data Pipeline →

Home · Neural Networks · Optimization · API Reference


EveryO — Open Machine Learning. Built for Developers.

Maintained By & Owner:
EveryO Contributors & @krishanth7

Open Source · MIT Licensed · Community Driven

© 2026 EveryO Contributors

⚠️ **GitHub.com Fallback** ⚠️