Coding Standards - krishanth7/EveryO GitHub Wiki

Coding Standards

EveryO โ€” Python Engineering, Numerical Correctness & Maintainable Architecture

Readable Code ยท Correct Mathematics ยท Reliable APIs ยท Reproducible Results

Python EveryO Ruff License

The engineering reference for writing consistent, testable, secure, mathematically correct, and maintainable EveryO source code.

Home ยท Development Setup ยท Contributing ยท Testing and Quality Assurance


Project Maintainer: @krishanth7

Important

Source of Authority

The repository's pyproject.toml, CONTRIBUTING.md, and REPOSITORY_RULES.md define the current coding requirements.

This Wiki page expands those requirements with recommended engineering practices. Recommendations do not become mandatory repository rules unless adopted by the maintainers.


Table of Contents

  1. Overview
  2. Engineering Principles
  3. Python Compatibility
  4. Formatting and Linting
  5. Naming Conventions
  6. Module Organization
  7. Type Annotations
  8. Docstring Standards
  9. Public API Design
  10. Error Handling
  11. Tensor Operations
  12. Automatic Differentiation
  13. Neural Network Modules
  14. Numerical Precision and Stability
  15. Memory and Performance
  16. Data Pipeline Standards
  17. Backend Independence
  18. CUDA Coding Standards
  19. Security and Input Validation
  20. Testing Standards
  21. Documentation Standards
  22. Logging and Diagnostics
  23. Dependency Management
  24. Git and Commit Practices
  25. Code Review Standards
  26. Quality Checklist
  27. Official References
  28. Next Steps

1. Overview

Coding standards provide a consistent engineering foundation for EveryO.

They help contributors implement new features while preserving the framework's architecture, mathematical behavior, and public interfaces.

1.1 Objectives

  • Improve source readability.
  • Reduce defects.
  • Preserve numerical correctness.
  • Maintain API consistency.
  • Support multiple contributors.
  • Improve testability.
  • Prevent unnecessary dependencies.
  • Simplify long-term maintenance.

1.2 Quality Dimensions

Dimension Expected Outcome
Readability Code is understandable
Correctness Mathematical results are verified
Consistency APIs follow established conventions
Reliability Edge cases are handled
Security Unsafe behavior is avoided
Testability Changes can be validated
Maintainability Code remains easy to modify

2. Engineering Principles

EveryO is a readable neural computing framework.

Its engineering philosophy prioritizes correctness and clarity over unnecessary complexity.

2.1 Core Principles

  1. Correctness before optimization.
  2. Readability before cleverness.
  3. Explicit behavior before hidden assumptions.
  4. Tests before unsupported claims.
  5. Stable APIs before unnecessary changes.
  6. Minimal dependencies.
  7. CPU functionality as the baseline.
  8. Documentation aligned with implementation.

2.2 Architectural Requirements

The core framework must not require:

  • GPU hardware.
  • CUDA.
  • TensorFlow.
  • API credentials.
  • Network access.
  • External AI services.

2.3 Performance Trade-Offs

Optimization is encouraged when it provides measurable value.

However, a performance improvement that substantially reduces maintainability should be evaluated carefully.

Contributors must not fabricate benchmarks or claim unverified acceleration.


3. Python Compatibility

3.1 Declared Requirement

EveryO declares:

requires-python = ">=3.9"

The inspected project CI explicitly tests Python 3.9 through 3.12.

3.2 Compatibility Rule

New core code should remain compatible with Python 3.9 unless an approved change modifies the supported baseline.

3.3 Type Hint Compatibility

Prefer syntax supported by the minimum Python version.

For example:

from typing import Optional

def normalize(
    values: list[float],
    epsilon: Optional[float] = None,
) -> list[float]:
    ...

Avoid introducing syntax requiring a newer interpreter without an approved compatibility change.

3.4 Verification

Run the relevant tests on the supported Python versions, using CI to identify version-specific failures.


4. Formatting and Linting

EveryO uses Ruff.

4.1 Configuration

The inspected pyproject.toml specifies:

[tool.ruff]
line-length = 100
target-version = "py39"
exclude = [".venv", "build", "dist"]

4.2 Enabled Lint Families

[tool.ruff.lint]
select = [
    "E",
    "F",
    "W",
    "I",
    "UP",
    "B",
    "C4",
    "SIM",
    "RET",
]

These cover areas including style, potential errors, import ordering, Python modernization, common bugs, and simplification.

4.3 Linting

ruff check .

4.4 Formatting Validation

ruff format --check .

4.5 Apply Formatting

ruff format .

4.6 Repository Script

./scripts/lint.sh

Automatic fixes:

./scripts/lint.sh --fix

4.7 Ruff Version

The development dependencies pin:

ruff==0.17.0

Use the repository-defined version to minimize differences between local development and CI.


5. Naming Conventions

Consistent naming improves readability and discoverability.

5.1 Recommended Conventions

Element Convention Example
Modules snake_case tensor_utils.py
Functions snake_case compute_gradient()
Variables snake_case batch_size
Classes PascalCase Linear, Tensor
Constants UPPER_SNAKE_CASE DEFAULT_EPSILON
Private helpers Leading underscore _validate_shape()
Test functions test_ prefix test_matmul_shape()

5.2 Prefer Descriptive Names

Preferred:

learning_rate = 0.001
batch_size = 32

Avoid:

lr2 = 0.001
bsx = 32

Short mathematical variables such as x, y, and w are acceptable when their meaning is clear.

5.3 Boolean Names

Prefer names that communicate a condition:

is_training = True
requires_grad = False
has_bias = True

6. Module Organization

Modules should have focused responsibilities.

6.1 Example Architecture

everyo/
โ”‚
โ”œโ”€โ”€ core/
โ”‚   โ”œโ”€โ”€ tensor.py
โ”‚   โ”œโ”€โ”€ operations.py
โ”‚   โ””โ”€โ”€ device.py
โ”‚
โ”œโ”€โ”€ nn/
โ”‚   โ”œโ”€โ”€ module.py
โ”‚   โ”œโ”€โ”€ layers.py
โ”‚   โ””โ”€โ”€ losses.py
โ”‚
โ”œโ”€โ”€ optim/
โ”œโ”€โ”€ data/
โ”œโ”€โ”€ training/
โ”œโ”€โ”€ serialization/
โ””โ”€โ”€ cuda/

This is an illustrative selection of repository modules.

6.2 Single Responsibility

A module should have one clear responsibility.

Avoid mixing unrelated functions such as:

  • Dataset parsing.
  • Neural network initialization.
  • Model serialization.
  • CLI output.

6.3 Module Size

The contribution guide recommends splitting files that grow beyond a few hundred lines when doing so improves clarity.

This is a design guideline rather than a strict line-count limit.

6.4 Internal Dependencies

Avoid circular imports.

Keep dependencies flowing toward foundational modules rather than making the core depend on higher-level training or visualization features.


7. Type Annotations

EveryO requires type hints on public functions and methods.

7.1 Example

def calculate_batch_count(
    sample_count: int,
    batch_size: int,
) -> int:
    if batch_size <= 0:
        raise ValueError("batch_size must be positive")

    return (sample_count + batch_size - 1) // batch_size

7.2 Recommended Practices

  • Annotate parameters.
  • Annotate return values.
  • Use meaningful types.
  • Avoid unnecessary Any.
  • Preserve Python 3.9 compatibility.
  • Keep public interfaces understandable.

7.3 Optional Values

from typing import Optional

def create_label(
    name: Optional[str] = None,
) -> str:
    return name or "unnamed"

7.4 Type Safety Limitations

Type annotations do not replace runtime validation.

Tensor shapes, numerical dtypes, and device availability may still require explicit checks.


8. Docstring Standards

Public modules, classes, and functions require docstrings.

8.1 Recommended Structure

A public function docstring should explain:

  • Purpose.
  • Parameters.
  • Return value.
  • Exceptions.
  • Important numerical behavior.
  • Usage examples where useful.

8.2 Example

def calculate_batch_count(
    sample_count: int,
    batch_size: int,
) -> int:
    """Calculate the number of batches including the final partial batch.

    Args:
        sample_count: Total number of samples.
        batch_size: Number of samples per batch.

    Returns:
        Number of batches.

    Raises:
        ValueError: If sample_count is negative or batch_size is not positive.
    """
    if sample_count < 0:
        raise ValueError("sample_count must be non-negative")

    if batch_size <= 0:
        raise ValueError("batch_size must be positive")

    return (sample_count + batch_size - 1) // batch_size

8.3 Mathematical Documentation

When implementing numerical operations, document the relevant formula and shape behavior.

For example:

[ Y=XW+b ]

Explain input, parameter, and output dimensions.


9. Public API Design

Public APIs should be predictable and consistent.

9.1 Design Principles

  • Use descriptive names.
  • Keep signatures focused.
  • Provide sensible defaults.
  • Validate invalid arguments.
  • Document side effects.
  • Avoid unexpected global state.
  • Preserve backward compatibility where practical.

9.2 Example

import everyo as eo

layer = eo.Linear(
    4,
    8,
    bias=True,
    seed=42,
)

9.3 Public Exports

When introducing a public operation, update the relevant package exports.

For core operations:

everyo/__init__.py

For neural network layers:

everyo/nn/__init__.py
everyo/__init__.py

9.4 Breaking Changes

Proposals that alter existing signatures or behavior should document:

  • Motivation.
  • Compatibility impact.
  • Migration approach.
  • Required tests.
  • Release implications.

10. Error Handling

EveryO defines framework-specific exception classes.

10.1 Examples

  • EveryOError
  • EveryOShapeError
  • EveryODTypeError
  • EveryODeviceError
  • EveryOGradientError
  • EveryOSerializationError

10.2 Error Quality

Error messages should identify the relevant values and explain the problem.

Preferred:

Cannot multiply matrices with shapes
(32, 64) and (128, 10).

Avoid ambiguous messages such as:

Invalid input.

10.3 Recommended Pattern

def validate_matrix_dimensions(
    left_shape: tuple[int, int],
    right_shape: tuple[int, int],
) -> None:
    if left_shape[1] != right_shape[0]:
        raise ValueError(
            "Incompatible matrix shapes: "
            f"{left_shape} and {right_shape}"
        )

This example demonstrates error-message quality; production EveryO code should use the appropriate framework exception where applicable.

10.4 Exception Handling

Avoid broad exception handling that hides programming errors.

When wrapping an exception, preserve useful diagnostic information.


11. Tensor Operations

Tensor operations must preserve mathematical and shape correctness.

11.1 Implementation Requirements

  • Validate input shapes.
  • Handle broadcasting correctly.
  • Preserve expected dtype behavior.
  • Implement correct forward computation.
  • Implement backward computation when differentiable.
  • Test edge cases.

11.2 Broadcasting

For compatible dimensions, broadcasting expands operands conceptually without changing the mathematical meaning of the operation.

Gradient implementations must reduce contributions along broadcast dimensions appropriately.

11.3 Matrix Multiplication

For:

[ A\in\mathbb{R}^{m\times k} ]

and:

[ B\in\mathbb{R}^{k\times n} ]

the output has shape:

[ AB\in\mathbb{R}^{m\times n} ]

11.4 Verification Example

import numpy as np
import everyo as eo

def test_matmul_shape():
    a = eo.ones(3, 4)
    b = eo.ones(4, 5)

    result = eo.matmul(a, b)

    assert result.shape == (3, 5)

    np.testing.assert_allclose(
        result.numpy(),
        np.full((3, 5), 4.0),
    )

12. Automatic Differentiation

Automatic differentiation is a correctness-critical subsystem.

12.1 Required Validation

Every new differentiable operation must have appropriate gradient tests.

The contribution guide specifically requires finite-difference verification.

12.2 Central Difference

[ \frac{\partial f}{\partial x_i} \approx \frac{f(x_i+\epsilon)-f(x_i-\epsilon)} {2\epsilon} ]

12.3 Example

For:

[ f(x)=x^2 ]

the derivative is:

[ f'(x)=2x ]

import numpy as np
import everyo as eo

def test_square_gradient():
    x = eo.tensor(
        [2.0],
        requires_grad=True,
    )

    y = x * x
    y.backward()

    np.testing.assert_allclose(
        x.grad,
        [4.0],
    )

12.4 Gradient Test Cases

  • Scalar inputs.
  • Vector inputs.
  • Matrix inputs.
  • Broadcasting.
  • Reused tensors.
  • Gradient accumulation.
  • Chain-rule composition.
  • Invalid gradient shapes.

12.5 Numerical Tolerances

Use tolerances appropriate to the dtype, operation, and numerical conditions.

Do not impose one universal tolerance on all computations.


13. Neural Network Modules

New layers should follow EveryO's Module architecture.

13.1 Requirements

  • Subclass Module.
  • Register the layer appropriately.
  • Implement forward().
  • Register trainable parameters.
  • Support applicable backward computation.
  • Provide configuration for serialization.
  • Add tests.

13.2 Layer Example

import everyo as eo

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

output = model(eo.zeros(8, 4))

assert output.shape == (8, 2)

13.3 Serialization

Layers with constructor arguments should implement get_config() when necessary for reconstruction.

Include save/load round-trip tests.

13.4 Training and Evaluation

Modules with training-dependent behavior should correctly support the framework's training and evaluation modes.


14. Numerical Precision and Stability

Machine learning computations are affected by floating-point limitations.

14.1 Common Risks

  • Overflow.
  • Underflow.
  • Cancellation.
  • Division by zero.
  • Loss of precision.
  • Unstable exponentiation.

14.2 Stable Softmax

For logits (z_i), a numerically stable softmax subtracts the maximum logit:

[ softmax(z_i)= \frac{e^{z_i-m}} {\sum_j e^{z_j-m}} ]

where:

[ m=\max_j z_j ]

14.3 Recommended Practices

  • Use stable formulations.
  • Avoid unnecessary precision conversions.
  • Test extreme input values.
  • Compare against trusted numerical references.
  • Document known limitations.

14.4 Numerical Testing

import numpy as np

np.testing.assert_allclose(
    actual,
    expected,
    rtol=1e-5,
    atol=1e-7,
)

The example tolerances are illustrative and must be chosen for the specific computation.


15. Memory and Performance

Performance improvements must preserve correctness and readability.

15.1 Recommended Practices

  • Prefer vectorized operations.
  • Avoid unnecessary copies.
  • Reduce redundant computation.
  • Profile before optimizing.
  • Benchmark representative workloads.
  • Record numerical differences.

15.2 Memory Formula

For a dense array:

[ Memory=Elements\times BytesPerElement ]

15.3 Benchmark Requirements

Performance claims should include:

  • Hardware.
  • Python version.
  • EveryO version or commit.
  • Input dimensions.
  • Dtype.
  • Number of repetitions.
  • Timing methodology.
  • Baseline results.

15.4 Optimization Review

A performance change should explain why the improvement justifies any added complexity.


16. Data Pipeline Standards

Data processing must preserve sample integrity and reproducibility.

16.1 Requirements

  • Validate feature-target alignment.
  • Handle empty datasets.
  • Validate batch sizes.
  • Avoid unintended dtype conversions.
  • Document shuffling behavior.
  • Preserve deterministic behavior when seeded.

16.2 Example

import numpy as np
import everyo as eo

features = np.zeros(
    (100, 4),
    dtype=np.float32,
)

targets = np.zeros(
    100,
    dtype=np.int64,
)

dataset = eo.ArrayDataset(
    features,
    targets,
)

loader = eo.DataLoader(
    dataset,
    batch_size=16,
    shuffle=True,
    seed=42,
)

16.3 Data Leakage

Fit preprocessing parameters on training data only.

Apply the fitted transformation to validation and test data.

16.4 Reproducibility

Seeded workflows should be tested for repeatability where the API promises deterministic behavior.


17. Backend Independence

EveryO's core must remain usable without optional acceleration or interoperability packages.

17.1 Core Baseline

The core numerical implementation uses NumPy.

17.2 Optional Components

Component Status
NumPy Core dependency
TensorFlow Optional
CUDA Optional
ONNX Optional
PyYAML Optional

17.3 Requirements

  • Optional imports must not break core imports.
  • CPU-only testing must remain possible.
  • Unsupported devices should produce meaningful behavior or errors.
  • Backend-specific tests should skip appropriately.

17.4 Dependency Boundaries

Do not make everyo.core depend on higher-level modules or heavyweight optional frameworks.


18. CUDA Coding Standards

CUDA development requires additional safety and correctness controls.

18.1 Source Locations

cuda/src/
cuda/include/everyo_cuda.h
cuda/bindings/bindings.cpp
everyo/cuda/interface.py

18.2 Required Practices

  • Bounds-check memory access.
  • Validate CUDA calls.
  • Check kernel launches.
  • Use safe device-memory ownership.
  • Provide NumPy fallback behavior.
  • Compare results with CPU references.

18.3 Error Checking

Use the repository's CUDA error-checking facilities:

EVERYO_CUDA_CHECK(...)
EVERYO_CUDA_CHECK_KERNEL()

18.4 Memory Ownership

Use the project's detail::DeviceBuffer abstraction where required to ensure device memory is released safely.

18.5 Testing

./scripts/build_cuda.sh

python -m pytest tests/test_devices.py -v

CUDA pull requests should document the actual hardware tested.


19. Security and Input Validation

Security is part of code quality.

19.1 Prohibited Practices

Do not introduce:

  • Credential harvesting.
  • Undisclosed telemetry.
  • Unauthorized network activity.
  • Malicious code.
  • Unsafe execution of model-file contents.
  • Secrets committed to the repository.

19.2 Input Validation

Validate relevant:

  • Tensor shapes.
  • Dtypes.
  • Array dimensions.
  • Configuration values.
  • File formats.
  • Serialization metadata.

19.3 Model Serialization

EveryO's security policy describes pickle-free model loading.

Changes must preserve the intended safe-loading architecture.

19.4 Vulnerability Reporting

Report vulnerabilities privately:

GitHub Private Vulnerability Reporting

Do not publish exploit details in a public issue.


20. Testing Standards

Behavioral changes require appropriate tests.

20.1 Test Categories

Change Required or Recommended Testing
Tensor operation Forward and gradient correctness
Bug fix Regression test
Neural layer Forward, backward, serialization
Optimizer Parameter update behavior
Data pipeline Edge cases and alignment
CUDA kernel CPU reference comparison
Serialization Save/load round trip
Public API Compatibility tests

20.2 Run Tests

python -m pytest -q

20.3 Targeted Tests

python -m pytest tests/test_autograd.py -v

20.4 Optional Dependencies

Tests requiring CUDA or TensorFlow should skip appropriately when the required environment is unavailable.

20.5 Test Quality

Tests should be:

  • Deterministic where practical.
  • Focused.
  • Readable.
  • Independent.
  • Meaningful.
  • Sensitive to actual defects.

Avoid assertions that merely confirm execution without checking relevant behavior.


21. Documentation Standards

Documentation must describe implemented functionality accurately.

21.1 Required Updates

When public behavior changes, update relevant:

  • API documentation.
  • Tutorials.
  • Examples.
  • Changelog entries.
  • README content where appropriate.

21.2 Status Terminology

Distinguish:

Status Meaning
Available Implemented and usable
Experimental Implemented but subject to limitations
Planned Not yet implemented

21.3 Accuracy Requirements

Do not fabricate:

  • Benchmarks.
  • Test results.
  • Compatibility claims.
  • Citations.
  • Contributors.
  • Adoption metrics.

21.4 Example Quality

Documentation examples should:

  • Use valid imports.
  • Match current signatures.
  • Explain prerequisites.
  • Avoid nonexistent APIs.
  • Include correct expected behavior.

22. Logging and Diagnostics

Diagnostic information should help developers understand failures.

22.1 Principles

  • Use meaningful messages.
  • Avoid unnecessary output.
  • Do not log credentials.
  • Do not expose private datasets.
  • Preserve useful exception context.

22.2 Recommended Logging

Use the framework's existing logging utilities where appropriate instead of introducing a competing logging system.

22.3 Error Reporting

Bug reports should include:

python -m everyo info

Along with a minimal reproduction and relevant traceback.


23. Dependency Management

Dependencies affect installation size, compatibility, security, and maintenance.

23.1 Existing Dependencies

The inspected package metadata declares:

numpy>=1.22
matplotlib>=3.5

23.2 Optional Extras

tensorflow
cuda
onnx
yaml
dev

23.3 New Dependency Review

Before adding a dependency, consider:

  1. Is it necessary?
  2. Can the feature be implemented using existing dependencies?
  3. Is it compatible with supported Python versions?
  4. Does it introduce security concerns?
  5. Should it be optional?
  6. Does it increase installation complexity?

23.4 Core Independence

The everyo.core layer must remain dependency-free beyond NumPy under the current contribution rules.


24. Git and Commit Practices

Contributions should be submitted through focused branches and reviewed pull requests.

24.1 Recommended Branch Names

fix/gradient-broadcasting
feature/new-layer
docs/api-reference
test/optimizer-regression
refactor/tensor-validation

24.2 Recommended Commit Format

type(scope): description

Examples:

feat(nn): add activation layer
fix(core): correct tensor broadcasting
test(autograd): add finite-difference coverage
docs(wiki): improve coding standards

These commit conventions are recommended rather than currently enforced.

24.3 Commit Quality

  • Keep commits focused.
  • Explain changes clearly.
  • Avoid unrelated files.
  • Never commit credentials.
  • Preserve reviewable history.

25. Code Review Standards

EveryO's repository rules require technically sound, maintainable contributions.

25.1 Review Criteria

Criterion Review Focus
Correctness Does the implementation work?
Mathematics Are formulas and gradients correct?
Architecture Does the change respect boundaries?
Readability Is the code understandable?
Testing Are relevant cases covered?
Security Are new risks introduced?
Compatibility Are existing users affected?
Documentation Are changes accurately described?

25.2 Pull Request Expectations

A pull request should explain:

  • Problem.
  • Solution.
  • Alternatives.
  • Testing performed.
  • Compatibility implications.
  • Relevant documentation.

25.3 Approval

Passing CI does not guarantee merge approval.

Maintainers may request changes, defer work, or reject contributions that do not align with the project's direction.


26. Quality Checklist

Before Coding

  • Understand the relevant architecture.
  • Review existing implementation patterns.
  • Confirm Python compatibility.
  • Identify tests that should be updated.

During Coding

  • Follow naming conventions.
  • Add type hints to public APIs.
  • Add public docstrings.
  • Validate inputs.
  • Use appropriate exceptions.
  • Preserve dependency boundaries.
  • Keep modules focused.

Numerical Verification

  • Forward results are correct.
  • Gradients are correct.
  • Broadcasting is tested.
  • Edge cases are covered.
  • Numerical tolerances are justified.

Before Pull Request

  • Tests pass.
  • Ruff lint passes.
  • Ruff formatting passes.
  • Documentation is updated.
  • Changelog is updated where relevant.
  • No credentials are included.
  • Performance claims are measured.
  • Compatibility impacts are documented.

Recommended Commands

python -m pytest -q

ruff check .

ruff format --check .

python -m compileall -q everyo

27. Official References

Resource Link
EveryO Repository GitHub
Project Configuration pyproject.toml
Contributing Guide CONTRIBUTING.md
Repository Rules REPOSITORY_RULES.md
Security Policy SECURITY.md
Governance GOVERNANCE.md
Tensor Operations operations.py
Neural Network Modules module.py
Test Suite tests/
CI GitHub Actions
Pull Requests GitHub Pull Requests

28. Next Steps

Continue with EveryO's contribution and release documentation.

Page Focus
Pull Request Guidelines PR submission, review, and approval
Release Process Versioning, packaging, and publication
Contributing Community contribution workflow
Development Setup Local development environment
Testing and Quality Assurance Testing and CI

Wiki links become active after the corresponding pages are created.


Coding Standards โ€” Documentation Prepared

Next Recommended Page: Pull Request Guidelines โ†’

Home ยท Contributing ยท Development Setup


EveryO โ€” Open Machine Learning. Built for Developers.

Project Maintainer: @krishanth7

Open Source ยท MIT Licensed ยท Community Driven

ยฉ 2026 EveryO Contributors

โš ๏ธ **GitHub.com Fallback** โš ๏ธ