Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkTuddenham committed Sep 15, 2021
0 parents commit fbc8058
Show file tree
Hide file tree
Showing 5 changed files with 313 additions and 0 deletions.
146 changes: 146 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
!.gitkeep

# Created by https://www.toptal.com/developers/gitignore/api/python
# Edit at https://www.toptal.com/developers/gitignore?templates=python

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# End of https://www.toptal.com/developers/gitignore/api/python
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Mark Tuddenham

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Orthogonalised Optimisers

## Install package
```bash
pip install .
```
or

```bash
pip install git+https://github.com/MarkTuddenham/Orthogonal-Optimiser.git#egg=orth_optim
```

## Usage
And then at the top of your main python script:

```python
from orth_optim import hook
hook()
```
Now SGD has an orthogonal option
```python
torch.optim.SGD(model.parameters(),
lr=1e-3,
momentum=0.9,
orth=True)
```

## Custom Optimisers
If you have a custom optimiser you can apply the `orthogonalise` decorator.

```python
from orth_optim import orthogonalise

@orthogonalise
class LARS(torch.optim.Optimizer):
...
```


33 changes: 33 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#!/usr/bin/env python

import os
from setuptools import setup
from setuptools import find_packages

# User-friendly description from README.md
current_directory = os.path.dirname(os.path.abspath(__file__))
try:
with open(os.path.join(current_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
except Exception:
long_description = ''

setup(name='orth_optim',
author='Mark Tuddenham',
author_email='[email protected]',
version='1.0.0',
description='Add option to orthogonalise gradients to pytorch optimisers',
long_description=long_description,
long_description_context_type='text/markdown',
license='MIT',
url='https://github.com/MarkTuddenham/Orthogonal-Optimisers',
keywords=['optimisation', 'optimzation', 'pytorch'],
packages=find_packages(where='src'),
package_dir={"": "src"},
install_requires=['torch'],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
)
74 changes: 74 additions & 0 deletions src/orth_optim/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
from typing import TypeVar
from typing import Type
from typing import Any

import logging

import torch

OptimType = TypeVar('U', bound=torch.optim.Optimizer)

logger: logging.Logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.NullHandler())


@torch.no_grad()
def _orth_grads(optimiser: OptimType) -> None:
# Orthogonalise the gradients using SVD
for group in optimiser.param_groups:
orth = group['orth']
for i, p in enumerate(group['params']):
if orth and p.grad is not None and p.ndim > 1:
G: torch.Tensor = p.grad.flatten(start_dim=1)
try:
u, s, vt = torch.linalg.svd(G, full_matrices=False)
orth_G: torch.Tensor = u @ vt
except RuntimeError:
logger.error('Failed to perform SVD, adding some noise.')
try:
u, s, v = torch.svd_lowrank(
G,
q=1, # assume rank is at least 1
M=1e-4 * G.mean() * torch.randn_like(G))
orth_G: torch.Tensor = u @ v.T
except RuntimeError:
logger.error(('Failed to perform SVD with noise,'
' skipping gradient orthogonalisation'))
return
p.grad = orth_G.reshape_as(p)


def orthogonalise(cls: Type[OptimType]) -> Type[OptimType]:
og_init = cls.__init__
og_step = cls.step

def new_init(self, *args, orth=False, **kwargs):
# Add orth hyperparam to defaults
og_init(self, *args, **kwargs)
self.defaults['orth'] = orth
for grp in self.param_groups:
grp.setdefault('orth', orth)

def new_step(self, *args, **kwargs):
# Orthogonalise the grads before the original optim's step method
_orth_grads(self)
og_step(self, *args, **kwargs)

cls.__init__ = new_init
cls.step = new_step
return cls


def hook() -> None:
from inspect import isclass
for mod in dir(torch.optim):
if mod.startswith('_'):
continue
_optim: Any = getattr(torch.optim, mod)
if (
isclass(_optim)
and issubclass(_optim, torch.optim.Optimizer)
and _optim is not torch.optim.Optimizer
):
setattr(torch.optim, mod, orthogonalise(_optim))

0 comments on commit fbc8058

Please sign in to comment.