Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[run]
omit =
src/psd/optimizer_tf.py
src/psd/framework_optimizers.py
src/psd/functions.py
src/psd/algorithms.py
src/psd_optimizer/optimizer.py
src/psd_optimizer/perturbed_adam.py
55 changes: 55 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
name: CI

on:
push:
pull_request:

jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
cache: pip
- name: Install dependencies
run: pip install .[dev]
- name: Run pre-commit
run: pre-commit run --show-diff-on-failure --color=always --all-files

type-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
cache: pip
- name: Install dependencies
run: pip install .[dev]
- name: Run mypy
run: mypy src

tests:
needs: [lint, type-check]
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
python-version: ['3.9', '3.10', '3.11', '3.12']
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: pip
- name: Install dependencies
run: pip install .[dev]
- name: Run tests
run: pytest --cov=src --cov-report=xml --cov-report=term-missing --cov-fail-under=90
- name: Upload coverage report
uses: actions/upload-artifact@v4
with:
name: coverage-${{ matrix.os }}-${{ matrix.python-version }}
path: coverage.xml
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Perturbed Saddle-escape Descent (PSD)

[![CI](https://github.com/farukalpay/PSD/actions/workflows/ci.yml/badge.svg)](https://github.com/farukalpay/PSD/actions/workflows/ci.yml) [![Coverage](https://img.shields.io/badge/coverage-90%25-brightgreen)](https://github.com/farukalpay/PSD/actions/workflows/ci.yml)

## Project Summary

This repository implements the **Perturbed Saddle-escape Descent (PSD)**
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ dev = [
"mypy==1.10.0",
"ruff==0.1.7",
"pytest==7.4.4",
"pytest-cov==4.1.0",
"hypothesis==6.99.13",
]
docs = [
"sphinx==7.2.6",
Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ torchvision
optuna
matplotlib
pytest
pytest-cov
hypothesis
transformers
29 changes: 29 additions & 0 deletions tests/test_algorithms_property.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import sys
from pathlib import Path

import numpy as np
from hypothesis import given, settings
from hypothesis import strategies as st

sys.path.append(str(Path(__file__).resolve().parents[1] / "src"))

from psd.algorithms import gradient_descent # noqa: E402


@given(
st.lists(
st.floats(min_value=-10, max_value=10, allow_nan=False, allow_infinity=False),
min_size=1,
max_size=5,
)
)
@settings(max_examples=100)
def test_gradient_descent_converges_to_zero(x0: list[float]) -> None:
arr = np.array(x0, dtype=float)

def grad(x: np.ndarray) -> np.ndarray:
return x

x, iters = gradient_descent(arr, grad, step_size=0.5, tol=1e-8, max_iter=1000)
assert np.linalg.norm(x) <= 1e-6
assert iters <= 1000
57 changes: 57 additions & 0 deletions tests/test_graph_properties.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import sys
from pathlib import Path

import pytest
from hypothesis import given, settings
from hypothesis import strategies as st

sys.path.append(str(Path(__file__).resolve().parents[1] / "src"))

from psd.graph import _reconstruct_path, find_optimal_path # noqa: E402


def _bruteforce_weight(graph: dict[str, dict[str, float]], start: str, end: str) -> float:
"""Compute the minimal path weight via exhaustive search."""
if start == end:
return 0.0
weights: list[float] = []
for neighbour, w in graph.get(start, {}).items():
weights.append(w + _bruteforce_weight(graph, neighbour, end))
return min(weights)


@st.composite
def dag_strategy(draw: st.DrawFn) -> tuple[dict[str, dict[str, float]], str, str]:
n = draw(st.integers(min_value=2, max_value=6))
nodes = [str(i) for i in range(n)]
graph = {node: {} for node in nodes}
# Ensure a base path 0->1->...->n-1
for i in range(n - 1):
graph[nodes[i]][nodes[i + 1]] = draw(
st.floats(min_value=0.1, max_value=10, allow_infinity=False, allow_nan=False)
)
for i in range(n - 1):
for j in range(i + 2, n):
if draw(st.booleans()):
graph[nodes[i]][nodes[j]] = draw(
st.floats(min_value=0.1, max_value=10, allow_infinity=False, allow_nan=False)
)
return graph, nodes[0], nodes[-1]


@given(dag_strategy())
@settings(max_examples=50)
def test_find_optimal_path_matches_bruteforce(args: tuple[dict[str, dict[str, float]], str, str]) -> None:
graph, start, end = args
path = find_optimal_path(graph, start, end)
# Weight along returned path
weight = 0.0
for a, b in zip(path, path[1:]): # noqa: B905
weight += graph[a][b]
assert weight == pytest.approx(_bruteforce_weight(graph, start, end))


def test_reconstruct_path_cycle_raises() -> None:
prev = {"A": "B", "B": "C", "C": "B"}
with pytest.raises(ValueError):
_reconstruct_path(prev, "A", "C")
Loading