-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Add tanh Chebyshev approx #3004
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
7d1e688
Add tanh Chebyshev approx
gmuraru b5d90c2
Add tests
gmuraru 34555d1
Merge branch 'master' into gm-improve-tanh
gmuraru 3587d03
Merge branch 'master' into gm-improve-tanh
LaRiffle ef44dcb
Merge branch 'master' into gm-improve-tanh
iamtrask File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| # This source code is licensed under the MIT license found in the | ||
| # LICENSE file in the root directory of this source tree. | ||
|
|
||
| import torch | ||
| import numpy as np | ||
|
|
||
|
|
||
| def chebyshev_series(func, width, terms): | ||
| """ | ||
| Computes Chebyshev coefficients | ||
| For n = terms, the ith Chebyshev series coefficient is | ||
| .. math:: | ||
| c_i = 2/n \sum_{k=1}^n \cos(j(2k-1)\pi / 4n) f(w\cos((2k-1)\pi / 4n)) | ||
| Args: | ||
| func (function): function to be approximated | ||
| width (int): approximation will support inputs in range [-width, width] | ||
| terms (int): number of Chebyshev terms used in approximation | ||
| Returns: | ||
| Chebyshev coefficients with shape equal to num of terms. | ||
| """ | ||
| n_range = torch.arange(start=0, end=terms).float() | ||
| x = width * torch.cos((n_range + 0.5) * np.pi / terms) | ||
| y = func(x) | ||
| cos_term = torch.cos(torch.ger(n_range, n_range + 0.5) * np.pi / terms) | ||
| coeffs = (2 / terms) * torch.sum(y * cos_term, axis=1) | ||
| return coeffs | ||
|
|
||
|
|
||
| def chebyshev_polynomials(tensor, terms=32): | ||
| """ | ||
| Evaluates odd degree Chebyshev polynomials at x | ||
| Chebyshev Polynomials of the first kind are defined as | ||
| .. math:: | ||
| P_0(x) = 1, P_1(x) = x, P_n(x) = 2 P_{n - 1}(x) - P_{n-2}(x) | ||
| Args: | ||
| tensor (torch.tensor): input at which polynomials are evaluated | ||
| terms (int): highest degree of Chebyshev polynomials. | ||
| Must be even and at least 6. | ||
| """ | ||
| if terms % 2 != 0 or terms < 6: | ||
| raise ValueError("Chebyshev terms must be even and >= 6") | ||
|
|
||
| polynomials = [tensor.clone()] | ||
| y = 4 * tensor ** 2 - 2 | ||
| z = y - 1 | ||
| polynomials.append(z.mul(tensor)) | ||
|
|
||
| for k in range(2, terms // 2): | ||
| next_polynomial = y * polynomials[k - 1] - polynomials[k - 2] | ||
| polynomials.append(next_polynomial) | ||
|
|
||
| return torch.stack(polynomials) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import torch | ||
| import itertools | ||
|
|
||
| from syft.common.util import chebyshev_series, chebyshev_polynomials | ||
|
|
||
|
|
||
| def test_chebyshev_polynomials(): | ||
| """Tests evaluation of chebyshev polynomials""" | ||
| sizes = [(1, 10), (3, 5), (3, 5, 10)] | ||
| possible_terms = [6, 40] | ||
| tolerance = 0.05 | ||
|
|
||
| for size, terms in itertools.product(sizes, possible_terms): | ||
| tensor = torch.rand(torch.Size(size)) * 42 - 42 | ||
| result = chebyshev_polynomials(tensor, terms) | ||
|
|
||
| # check number of polynomials | ||
| assert result.shape[0] == terms // 2 | ||
|
|
||
| assert torch.all(result[0] == tensor), "first term is incorrect" | ||
|
|
||
| second_term = 4 * tensor ** 3 - 3 * tensor | ||
| diff = (result[1] - second_term).abs() | ||
| norm_diff = diff.div(result[1].abs() + second_term.abs()) | ||
| assert torch.all(norm_diff <= tolerance), "second term is incorrect" | ||
|
|
||
|
|
||
| def test_chebyshev_series(): | ||
| """Checks coefficients returned by chebyshev_series are correct""" | ||
| for width, terms in [(6, 10), (6, 20)]: | ||
| result = chebyshev_series(torch.tanh, width, terms) | ||
|
|
||
| # check shape | ||
| assert result.shape == torch.Size([terms]) | ||
|
|
||
| # check terms | ||
| assert result[0] < 1e-4 | ||
| assert torch.isclose(result[-1], torch.tensor(3.5e-2), atol=1e-1) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm curious,
2 * sigmoid(2 * tensor) - 1wasn't precise enough or too slow?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In the PR, they say this:
Before this, they also had the implementation using the
sigmoidThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok cool!