diffgames 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
diffgames/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Sun Nov 29 21:04:09 2026
5
+
6
+ @author: danish
7
+ """
8
+
9
+ from .optim import ConsensusOptimization, Extragradient, OGDA, SimGDA
10
+
11
+ __all__ = ["SimGDA", "Extragradient", "OGDA", "ConsensusOptimization"]
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Sun Nov 29 21:04:08 2026
5
+
6
+ @author: danish
7
+ """
8
+
9
+ from .base import ZeroSumGame
10
+ from .bilinear import BilinearGame
11
+ from .quadratic import QuadraticGame
12
+
13
+ __all__ = ["ZeroSumGame", "BilinearGame", "QuadraticGame"]
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Mon Nov 30 23:17:17 2026
5
+
6
+ @author: danish
7
+ """
8
+
9
+ from abc import ABC, abstractmethod
10
+ import torch
11
+
12
+
13
+ class ZeroSumGame(ABC):
14
+ """Base class for continuous two-player zero-sum games min_x max_y f(x, y)."""
15
+
16
+ @abstractmethod
17
+ def __call__(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
18
+ pass
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Mon Nov 30 23:20:30 2026
5
+
6
+ @author: danish
7
+ """
8
+
9
+ import torch
10
+ from .base import ZeroSumGame
11
+
12
+
13
+ class BilinearGame(ZeroSumGame):
14
+ """Bilinear zero-sum game f(x, y) = x^T A y."""
15
+
16
+ def __init__(self, matrix: torch.Tensor | None = None):
17
+ if matrix is None:
18
+ self.A = torch.tensor([[1.0]])
19
+ else:
20
+ self.A = matrix.float()
21
+
22
+ def __call__(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
23
+ return x @ self.A @ y
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Mon Nov 30 23:19:03 2026
5
+
6
+ @author: danish
7
+ """
8
+
9
+ import torch
10
+ from .base import ZeroSumGame
11
+
12
+
13
+ class QuadraticGame(ZeroSumGame):
14
+ """Strongly convex-concave game f(x, y) = (mu/2)||x||^2 + x^T A y - (mu/2)||y||^2."""
15
+
16
+ def __init__(self, matrix: torch.Tensor | None = None, mu: float = 0.5):
17
+ if matrix is None:
18
+ self.A = torch.tensor([[1.0]])
19
+ else:
20
+ self.A = matrix.float()
21
+ self.mu = mu
22
+
23
+ def __call__(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
24
+ reg_x = 0.5 * self.mu * torch.sum(x**2)
25
+ reg_y = 0.5 * self.mu * torch.sum(y**2)
26
+ return reg_x + (x @ self.A @ y) - reg_y
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Sun Nov 29 21:04:09 2026
5
+
6
+ @author: danish
7
+ """
8
+ from .consensus import ConsensusOptimization
9
+ from .extragradient import Extragradient
10
+ from .gda import SimGDA
11
+ from .ogda import OGDA
12
+
13
+ __all__ = ["SimGDA", "Extragradient", "OGDA", "ConsensusOptimization"]
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Tue Dec 1 09:53:14 2026
5
+
6
+ @author: danish
7
+ """
8
+
9
+ import torch
10
+
11
+
12
+ class ConsensusOptimization:
13
+ """Consensus Optimization (Mescheder et al., 2017) for min_x max_y f(x, y)."""
14
+
15
+ def __init__(self, params_x, params_y, lr: float = 1e-2, gamma: float = 0.1):
16
+ self.params_x = list(params_x)
17
+ self.params_y = list(params_y)
18
+ self.lr = lr
19
+ self.gamma = gamma
20
+
21
+ def step(self, loss: torch.Tensor):
22
+ params = self.params_x + self.params_y
23
+ grads = torch.autograd.grad(loss, params, create_graph=True)
24
+
25
+ reg = 0.5 * sum(torch.sum(g**2) for g in grads)
26
+ reg_grads = torch.autograd.grad(reg, params)
27
+
28
+ n_x = len(self.params_x)
29
+ grads_x, grads_y = grads[:n_x], grads[n_x:]
30
+ reg_x, reg_y = reg_grads[:n_x], reg_grads[n_x:]
31
+
32
+ with torch.no_grad():
33
+ for p, g, rg in zip(self.params_x, grads_x, reg_x):
34
+ p.add_(g + self.gamma * rg, alpha=-self.lr)
35
+
36
+ for p, g, rg in zip(self.params_y, grads_y, reg_y):
37
+ p.add_(g - self.gamma * rg, alpha=self.lr)
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Sun Nov 29 21:45:31 2026
5
+
6
+ @author: danish
7
+ """
8
+
9
+ import torch
10
+
11
+
12
+ class Extragradient:
13
+ """Extragradient (EG) optimizer for min_x max_y f(x, y)."""
14
+
15
+ def __init__(self, params_x, params_y, lr: float = 1e-2):
16
+ self.params_x = list(params_x)
17
+ self.params_y = list(params_y)
18
+ self.lr = lr
19
+ self._saved_x = []
20
+ self._saved_y = []
21
+
22
+ def zero_grad(self):
23
+ for p in self.params_x + self.params_y:
24
+ if p.grad is not None:
25
+ p.grad.zero_()
26
+
27
+ @torch.no_grad()
28
+ def extrapolation(self):
29
+ # Сохраняем копию текущих координат
30
+ self._saved_x = [p.clone() for p in self.params_x]
31
+ self._saved_y = [p.clone() for p in self.params_y]
32
+
33
+ # Делаем пробный шаг вперед
34
+ for p in self.params_x:
35
+ if p.grad is not None:
36
+ p.add_(p.grad, alpha=-self.lr)
37
+
38
+ for p in self.params_y:
39
+ if p.grad is not None:
40
+ p.add_(p.grad, alpha=self.lr)
41
+
42
+ @torch.no_grad()
43
+ def step(self):
44
+ # Возвращаемся в исходную точку и шагаем по новым градиентам
45
+ for p, p_old in zip(self.params_x, self._saved_x):
46
+ p.copy_(p_old)
47
+ if p.grad is not None:
48
+ p.add_(p.grad, alpha=-self.lr)
49
+
50
+ for p, p_old in zip(self.params_y, self._saved_y):
51
+ p.copy_(p_old)
52
+ if p.grad is not None:
53
+ p.add_(p.grad, alpha=self.lr)
diffgames/optim/gda.py ADDED
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Sun Nov 29 21:25:56 2026
5
+
6
+ @author: danish
7
+ """
8
+
9
+ import torch
10
+
11
+
12
+ class SimGDA:
13
+ """Simultaneous Gradient Descent-Ascent for min_x max_y f(x, y)."""
14
+
15
+ def __init__(self, params_x, params_y, lr: float = 1e-2):
16
+ self.params_x = list(params_x)
17
+ self.params_y = list(params_y)
18
+ self.lr = lr
19
+
20
+ def zero_grad(self):
21
+ for p in self.params_x + self.params_y:
22
+ if p.grad is not None:
23
+ p.grad.zero_()
24
+
25
+ @torch.no_grad()
26
+ def step(self):
27
+ for p in self.params_x:
28
+ if p.grad is not None:
29
+ p.add_(p.grad, alpha=-self.lr)
30
+
31
+ for p in self.params_y:
32
+ if p.grad is not None:
33
+ p.add_(p.grad, alpha=self.lr)
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Mon Nov 30 22:48:55 2026
5
+
6
+ @author: danish
7
+ """
8
+
9
+ import torch
10
+
11
+
12
+ class OGDA:
13
+ """Optimistic Gradient Descent-Ascent for min_x max_y f(x, y)."""
14
+
15
+ def __init__(self, params_x, params_y, lr: float = 1e-2):
16
+ self.params_x = list(params_x)
17
+ self.params_y = list(params_y)
18
+ self.lr = lr
19
+ self._prev_grad_x = [None] * len(self.params_x)
20
+ self._prev_grad_y = [None] * len(self.params_y)
21
+
22
+ def zero_grad(self):
23
+ for p in self.params_x + self.params_y:
24
+ if p.grad is not None:
25
+ p.grad.zero_()
26
+
27
+ @torch.no_grad()
28
+ def step(self):
29
+ for i, p in enumerate(self.params_x):
30
+ if p.grad is None:
31
+ continue
32
+ if self._prev_grad_x[i] is None:
33
+ p.add_(p.grad, alpha=-self.lr)
34
+ else:
35
+ p.add_(p.grad, alpha=-2.0 * self.lr)
36
+ p.add_(self._prev_grad_x[i], alpha=self.lr)
37
+ self._prev_grad_x[i] = p.grad.clone()
38
+
39
+ for i, p in enumerate(self.params_y):
40
+ if p.grad is None:
41
+ continue
42
+ if self._prev_grad_y[i] is None:
43
+ p.add_(p.grad, alpha=self.lr)
44
+ else:
45
+ p.add_(p.grad, alpha=2.0 * self.lr)
46
+ p.add_(self._prev_grad_y[i], alpha=-self.lr)
47
+ self._prev_grad_y[i] = p.grad.clone()
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.4
2
+ Name: diffgames
3
+ Version: 0.1.0
4
+ Summary: Gradient-based optimization algorithms for continuous two-player zero-sum differentiable games in PyTorch.
5
+ Author: Danish Khan
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Danish Khan
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/DanishKhan2002/diffgames
29
+ Project-URL: Repository, https://github.com/DanishKhan2002/diffgames
30
+ Requires-Python: >=3.9
31
+ Description-Content-Type: text/markdown
32
+ License-File: LICENSE
33
+ Requires-Dist: torch>=2.0
34
+ Dynamic: license-file
35
+
36
+ # diffgames
37
+
38
+ Gradient-based optimization algorithms for continuous two-player zero-sum differentiable games ($\min_x \max_y f(x, y)$) in PyTorch.
39
+
40
+ ![Phase Portrait](phase_portrait.png)
41
+
42
+ ## Implemented Algorithms
43
+
44
+ | Algorithm | Class | Order | Gradient Evals / Step | Bilinear Convergence | Reference |
45
+ | :--- | :--- | :---: | :---: | :---: | :--- |
46
+ | Simultaneous GDA | `SimGDA` | 1st | 1 | Diverges | — |
47
+ | Extragradient | `Extragradient` | 1st | 2 | Converges | Korpelevich (1976) |
48
+ | Optimistic GDA | `OGDA` | 1st | 1 | Converges | Daskalakis et al. (2018) |
49
+ | Consensus Optimization | `ConsensusOptimization` | 2nd | 1 (+ JVP) | Converges | Mescheder et al. (2017) |
50
+
51
+ ## Benchmark Games
52
+
53
+ Available in `diffgames.games`:
54
+ - `BilinearGame`: $f(x, y) = x^\top A y$
55
+ - `QuadraticGame`: $f(x, y) = \frac{\mu}{2}\Vert{}x\Vert{}^2 + x^\top A y - \frac{\mu}{2}\Vert{}y\Vert{}^2$
56
+
57
+ ## Installation
58
+
59
+ ```bash
60
+ git clone https://github.com/DanishKhan2002/diffgames.git
61
+ cd diffgames
62
+ pip install -e .
63
+ ```
64
+
65
+ ## Quick Start
66
+
67
+ ```python
68
+ import torch
69
+ from diffgames import OGDA
70
+ from diffgames.games import BilinearGame
71
+
72
+ game = BilinearGame()
73
+ x = torch.tensor([1.0], requires_grad=True)
74
+ y = torch.tensor([1.0], requires_grad=True)
75
+
76
+ opt = OGDA([x], [y], lr=0.2)
77
+
78
+ for _ in range(100):
79
+ opt.zero_grad()
80
+ loss = game(x, y)
81
+ loss.backward()
82
+ opt.step()
83
+
84
+ print(f"x={x.item():.4f}, y={y.item():.4f}")
85
+ ```
86
+
87
+ For second-order methods (`ConsensusOptimization`), pass the scalar loss directly to `step()`:
88
+
89
+ ```python
90
+ from diffgames import ConsensusOptimization
91
+
92
+ opt = ConsensusOptimization([x], [y], lr=0.2, gamma=0.5)
93
+ for _ in range(100):
94
+ loss = game(x, y)
95
+ opt.step(loss)
96
+ ```
97
+
98
+ ## Tests and Examples
99
+
100
+ Run the test suite:
101
+
102
+ ```bash
103
+ pytest
104
+ ```
105
+
106
+ Regenerate the phase portrait:
107
+
108
+ ```bash
109
+ python examples/phase_portrait.py
110
+ ```
111
+
112
+ ## References
113
+
114
+ - G. M. Korpelevich, *The extragradient method for finding saddle points and other problems*, Ekonomika i Matematicheskie Metody, 1976.
115
+ - L. Mescheder, S. Nowozin, A. Geiger, *The Numerics of GANs*, NeurIPS 2017.
116
+ - C. Daskalakis, A. Ilyas, V. Syrgkanis, H. Zeng, *Training GANs with Optimism*, ICLR 2018.
@@ -0,0 +1,15 @@
1
+ diffgames/__init__.py,sha256=CULsNpOvDuamSww_x_2WbmiKCBtgmqbpjnfv_uP_hpM,250
2
+ diffgames/games/__init__.py,sha256=WTYAT8oFsnSqWGPkYVYn5SwY1Ybu8ybStha8lwTnDIk,270
3
+ diffgames/games/base.py,sha256=2hunKScW2pLbKjUZRVH4eTpES8Q0usIbY-Y3nmRYApk,374
4
+ diffgames/games/bilinear.py,sha256=iIEO1ehoVudTFZQns3j8h-do_UYfWiK3DbnvUqKRSfE,524
5
+ diffgames/games/quadratic.py,sha256=6X7Ida5bbolOD8Ttnko_siW07i9qIHVhoflgRqz1i5A,715
6
+ diffgames/optim/__init__.py,sha256=D2ks_B6ayw1DwuuuaAT3M_WpRajd--11EXK0J_bcnbk,313
7
+ diffgames/optim/consensus.py,sha256=YO5YgDy3VTbE8i_Heb-dtGZnGWaTDSfUxEkptgqjFhw,1132
8
+ diffgames/optim/extragradient.py,sha256=a-BXz031X8RDKfTP4vmYMNwxUMUeJXjFqLfjvFVzkA0,1591
9
+ diffgames/optim/gda.py,sha256=Ji9rjefL9F1__W_tZkBKMXPHC_rsWDtH9HkVwhjPrnk,781
10
+ diffgames/optim/ogda.py,sha256=q6H5kgvgNvk-w_HwlKlxtOyT9-Z9tGRWtHHbncaKJC0,1411
11
+ diffgames-0.1.0.dist-info/licenses/LICENSE,sha256=NIrCwlTfBq0M5KUgo3Z2ux64_IbsnATt0mUxfI9R_a4,1068
12
+ diffgames-0.1.0.dist-info/METADATA,sha256=C1vQ5e9DBpOBeVB44gPruXXelHQE0aNi6TnQmGh8CiM,3835
13
+ diffgames-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
14
+ diffgames-0.1.0.dist-info/top_level.txt,sha256=5vsrFqn-LjX_nR-XcF49WJ37FJ98DROFeBaPBidQMz0,10
15
+ diffgames-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Danish Khan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ diffgames