Skip to content
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

Fix adjoint gradient with conductivities #1830

Merged
merged 2 commits into from
Nov 22, 2021
Merged

Conversation

mochen4
Copy link
Collaborator

@mochen4 mochen4 commented Nov 18, 2021

Replaces #1823. Fixes #1811.

@stevengj
Copy link
Collaborator

Test failure?

@mochen4
Copy link
Collaborator Author

mochen4 commented Nov 18, 2021

Test failure?

The double precision tests past but single precision one failed. I am still looking at why.

@stevengj
Copy link
Collaborator

Maybe try changing FD_DEFAULT in python/adjoint/utils.py to see if it is the fault of the finite-difference dε/du.

@stevengj
Copy link
Collaborator

In discussion with @mochen4, it seems like simply increasing the runtime fixes the problem — there seems to be a problem with the stop_when_dft_decayed convergence criterion in single precision.

@mawc2019
Copy link
Contributor

When I compile the current master branch with --enable-single and Python 3.7.3, the check at test_damping still fails as described in #1821. The finite-difference gradients change a lot between double precision and single precision. I increased minimum_run_time to 2000 in forward_simulation_damping and adjoint_solver_damping, but the check still failed. A tweak following @smartalecH 's suggestion is as follows, with which the check passes locally. Maybe this issue is negligible because the online check does not fail.

    def test_damping(self):
        print("*** TESTING CONDUCTIVITIES ***")

        for frequencies in [[1/1.58, fcen, 1/1.53]]:
            ## filter the design field
            filter_radius = 0.12
            p_filtered = mpa.conic_filter(
                np.reshape(p,(Nx,Ny)),filter_radius,design_region_size.x,design_region_size.y,design_region_resolution).flatten()
            dp_filtered = mpa.conic_filter(
                np.reshape(dp,(Nx,Ny)),filter_radius,design_region_size.x,design_region_size.y,design_region_resolution).flatten()
            
            ## compute gradient using adjoint solver
            adjsol_obj, adjsol_grad = adjoint_solver_damping(p_filtered, frequencies)

            ## compute unperturbed S12
            S12_unperturbed = forward_simulation_damping(p_filtered, frequencies)

            ## compare objective results
            print("S12 -- adjoint solver: {}, traditional simulation: {}".format(adjsol_obj,S12_unperturbed))
            self.assertClose(adjsol_obj,S12_unperturbed,epsilon=1e-6)

            ## compute perturbed S12
            S12_perturbed = forward_simulation_damping(p_filtered+dp_filtered, frequencies)

            ## compare gradients
            if adjsol_grad.ndim < 2:
                adjsol_grad = np.expand_dims(adjsol_grad,axis=1)
            adj_scale = (dp_filtered[None,:]@adjsol_grad).flatten()
            fd_grad = S12_perturbed-S12_unperturbed
            print("Directional derivative -- adjoint solver: {}, FD: {}".format(adj_scale,fd_grad))
            tol = 0.06 if mp.is_single_precision() else 0.03
            self.assertClose(adj_scale,fd_grad,epsilon=tol)

@mochen4
Copy link
Collaborator Author

mochen4 commented Dec 10, 2021

test_damping is only added after this PR, so certainly you wouldn't see the failure for commits before this one. But that test is only about the added features in this PR, so I don't think it is the reason why #1821 fails locally on your machine.

Maybe this issue is negligible because the online check does not fail.

The CI test runs the single-precision case with python3.9. I tested the master branch locally under python3.9 in single-precision, and tests passed. So I think the issue is either something with the python version or something in your local machine.

@mawc2019

mochen4 added a commit to mochen4/meep that referenced this pull request Feb 16, 2022
* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
mochen4 added a commit to mochen4/meep that referenced this pull request Feb 16, 2022
* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
mochen4 added a commit to mochen4/meep that referenced this pull request Feb 16, 2022
* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
mochen4 added a commit to mochen4/meep that referenced this pull request Feb 22, 2022
* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
mochen4 added a commit to mochen4/meep that referenced this pull request Feb 22, 2022
* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
mochen4 added a commit to mochen4/meep that referenced this pull request Feb 22, 2022
* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
mochen4 added a commit to mochen4/meep that referenced this pull request Feb 22, 2022
* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
mochen4 added a commit to mochen4/meep that referenced this pull request Feb 22, 2022
* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
mochen4 added a commit to mochen4/meep that referenced this pull request Feb 22, 2022
* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
mochen4 added a commit to mochen4/meep that referenced this pull request Feb 22, 2022
* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
mochen4 added a commit to mochen4/meep that referenced this pull request Feb 22, 2022
* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
mochen4 added a commit to mochen4/meep that referenced this pull request Feb 22, 2022
* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
stevengj added a commit that referenced this pull request Mar 10, 2022
* first draft of loop_in_chunks using grid_vol calculations

* try to only use owned points in loop_in_chunks

* don't unpad if !use_symmetry

* stop vscode from complaining about comments

* rm hack to loop over centered grid

* fix and example

* almost fix

* before fix

* one more loop over num_chunk

* include set

* different approach

* minor

* include climits

* include climits

* fix retval

* clean up

* using flipped

* add missing changes

* fix bug

* fix pml

* Fix memory leaks in SWIG wrappers. (#1826)

* Fix memory leaks in SWIG wrappers.

* move delete into material_free

Co-authored-by: Steven G. Johnson <stevenj@alum.mit.edu>

* Fix adjoint gradient with conductivities (#1830)

* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>

* plot geometry for dispersive materials without initializing structure object (#1827)

* plot geometry without initializing structure class

* update docstrings

* rotate epsilon grid by 90 degrees to properly orient axes

* add support for dispersive ε

* update markdown pages from docstrings

* make frequency and resolution parameters of plot2D dictionary keys of eps_parameters

* reinstate frequency parameter of plot2D and add warning that it is deprecated

* fix order of frequency check

* unit test for `get_epsilon_grid` (#1835)

* unit test for get_epsilon_grid

* fix

* limit test points to homogeneous regions (i.e. no material interfaces) and away from potential chunk boundaries

* support for single-precision floating point for fields array functions (#1833)

* switch dft-related functions to using realnum from double

* more fixes

* more type conversions from double to realnum

* adjust check tolerance of tests/integrate.cpp based on floating-point precision

* more fixes

* rebase from master from fix merge conflicts

* slight adjustment to tolerances in unit tests and update docs

* remove type check in test_adjoint_solver.py

* revert return types of integration functions to double

* revert return type of process_dft_component to double

* cleanup

* Fix memory leaks (#1839)

* Fix memory leaks

* Add kkg to authors list

* Fix for Issue #1834  (#1840)

* Fix memory leaks

* Add kkg to authors list

* Expose set_default_material and use it in libpympb/pympb.cpp

* use unique_ptr (C++11) instead of make_unique (C++14) (#1844)

* Use None instead of empty list in constructors (#1846)

* use None

* minor fix

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>

* Define what happens when `β=∞` and `u=η` (#1842)

* define what happens when beta=inf and u=0.5

* use eta not 0.5

* Update src/meepgeom.cpp

Co-authored-by: Steven G. Johnson <stevenj@mit.edu>

* fix for arrays (#1845)

* minor improvements to docs (#1848)

* update homebrew instructions for hdf5 and openblas

(fixes #1850)

* recommend python3 on macos

* silence compiler warnings

* whoops, missing commit

* tests need scipy and autograd

* missing sudo

* parameterized package is also used for tests

* h5py and jax on mac

* note on autogen.sh for git clone

* xcode installation shortcut

* bug fix for get_epsilon_point and cell boundary in parallel simulation (#1849)

* bug fix for get_epsilon_point and cell boundary in parallel simulation

* check for six digits in test_material_grid.py because of single precision

* unit test for conductivity (#1857)

* unit test for conductivity

* describe in the docs how to model the attenutation coefficient using conductivity

* Update python/tests/test_conductivity.py

Co-authored-by: Steven G. Johnson <stevenj@mit.edu>

* Fix the failure message for absorber 1D test (#1859)

* add missing fixed field phase to MPB unit test (#1860)

* fix memory leak in array-slice-ll.cpp (#1865)

* fix memory leak in array-slice-ll.cpp

* reinstate line break

* fix memory leak in cyl-ellipsoid-ll.cpp (#1866)

* level parameter for contour plot calls epsilon data (#1869)

* fix heap buffer overflow error for update E from D in cylindrical coordinates (#1871)

* Add cylindrical coordinates support for `plot2d` (#1873)

* add visualization support for plot2d

* bug fix with cartesian plotting

* fix near-field monitor position in cylindrical coordinate tutorial (#1874)

* fix memory leaks in structure and fields load during checkpointing (#1872)

* fix memory leaks in structure and fields load during checkpointing

* delete the chi1inv and fields array if it exists and reallocate

* in unit test, set gaussian source cutoff to 0 due to off-by-1 timestep counter bug

* remove cutoff=0 from unit tests

* lazily allocate H only if B is not NULL

* allocate fields array for H in PML region

* fix two memory leaks in geom_epsilon class (#1877)

* fix two memory leaks in geom_epsilon class

* delete global variable default_material at the end of unit tests

* add unset_default_material function to class meep_geom

* include ring-ll.cpp in C++ unit tests (#1878)

* include ring-ll.cpp in C++ unit tests

* only validate Harminv modes with error below some threshold

* fix and example

* first draft of loop_in_chunks using grid_vol calculations

* try to only use owned points in loop_in_chunks

* don't unpad if !use_symmetry

* stop vscode from complaining about comments

* rm hack to loop over centered grid

* almost fix

* before fix

* one more loop over num_chunk

* include set

* different approach

* minor

* include climits

* include climits

* fix retval

* clean up

* using flipped

* add missing changes

* fix bug

* fix pml

* Fix memory leaks in SWIG wrappers. (#1826)

* Fix memory leaks in SWIG wrappers.

* move delete into material_free

Co-authored-by: Steven G. Johnson <stevenj@alum.mit.edu>

* Fix adjoint gradient with conductivities (#1830)

* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>

* plot geometry for dispersive materials without initializing structure object (#1827)

* plot geometry without initializing structure class

* update docstrings

* rotate epsilon grid by 90 degrees to properly orient axes

* add support for dispersive ε

* update markdown pages from docstrings

* make frequency and resolution parameters of plot2D dictionary keys of eps_parameters

* reinstate frequency parameter of plot2D and add warning that it is deprecated

* fix order of frequency check

* unit test for `get_epsilon_grid` (#1835)

* unit test for get_epsilon_grid

* fix

* limit test points to homogeneous regions (i.e. no material interfaces) and away from potential chunk boundaries

* support for single-precision floating point for fields array functions (#1833)

* switch dft-related functions to using realnum from double

* more fixes

* more type conversions from double to realnum

* adjust check tolerance of tests/integrate.cpp based on floating-point precision

* more fixes

* rebase from master from fix merge conflicts

* slight adjustment to tolerances in unit tests and update docs

* remove type check in test_adjoint_solver.py

* revert return types of integration functions to double

* revert return type of process_dft_component to double

* cleanup

* Fix memory leaks (#1839)

* Fix memory leaks

* Add kkg to authors list

* Fix for Issue #1834  (#1840)

* Fix memory leaks

* Add kkg to authors list

* Expose set_default_material and use it in libpympb/pympb.cpp

* use unique_ptr (C++11) instead of make_unique (C++14) (#1844)

* Use None instead of empty list in constructors (#1846)

* use None

* minor fix

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>

* Define what happens when `β=∞` and `u=η` (#1842)

* define what happens when beta=inf and u=0.5

* use eta not 0.5

* Update src/meepgeom.cpp

Co-authored-by: Steven G. Johnson <stevenj@mit.edu>

* fix for arrays (#1845)

* minor improvements to docs (#1848)

* update homebrew instructions for hdf5 and openblas

(fixes #1850)

* recommend python3 on macos

* silence compiler warnings

* whoops, missing commit

* tests need scipy and autograd

* missing sudo

* parameterized package is also used for tests

* h5py and jax on mac

* note on autogen.sh for git clone

* xcode installation shortcut

* bug fix for get_epsilon_point and cell boundary in parallel simulation (#1849)

* bug fix for get_epsilon_point and cell boundary in parallel simulation

* check for six digits in test_material_grid.py because of single precision

* unit test for conductivity (#1857)

* unit test for conductivity

* describe in the docs how to model the attenutation coefficient using conductivity

* Update python/tests/test_conductivity.py

Co-authored-by: Steven G. Johnson <stevenj@mit.edu>

* Fix the failure message for absorber 1D test (#1859)

* add missing fixed field phase to MPB unit test (#1860)

* fix memory leak in array-slice-ll.cpp (#1865)

* fix memory leak in array-slice-ll.cpp

* reinstate line break

* fix memory leak in cyl-ellipsoid-ll.cpp (#1866)

* level parameter for contour plot calls epsilon data (#1869)

* fix heap buffer overflow error for update E from D in cylindrical coordinates (#1871)

* Add cylindrical coordinates support for `plot2d` (#1873)

* add visualization support for plot2d

* bug fix with cartesian plotting

* fix near-field monitor position in cylindrical coordinate tutorial (#1874)

* fix memory leaks in structure and fields load during checkpointing (#1872)

* fix memory leaks in structure and fields load during checkpointing

* delete the chi1inv and fields array if it exists and reallocate

* in unit test, set gaussian source cutoff to 0 due to off-by-1 timestep counter bug

* remove cutoff=0 from unit tests

* lazily allocate H only if B is not NULL

* allocate fields array for H in PML region

* fix two memory leaks in geom_epsilon class (#1877)

* fix two memory leaks in geom_epsilon class

* delete global variable default_material at the end of unit tests

* add unset_default_material function to class meep_geom

* include ring-ll.cpp in C++ unit tests (#1878)

* include ring-ll.cpp in C++ unit tests

* only validate Harminv modes with error below some threshold

* fix and example

* first draft of loop_in_chunks using grid_vol calculations

* try to only use owned points in loop_in_chunks

* don't unpad if !use_symmetry

* stop vscode from complaining about comments

* rm hack to loop over centered grid

* almost fix

* before fix

* one more loop over num_chunk

* include set

* different approach

* minor

* include climits

* include climits

* fix retval

* clean up

* using flipped

* add missing changes

* fix bug

* fix pml

* Fix adjoint gradient with conductivities (#1830)

* damp_fix

* increase run time

Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>

* plot geometry for dispersive materials without initializing structure object (#1827)

* plot geometry without initializing structure class

* update docstrings

* rotate epsilon grid by 90 degrees to properly orient axes

* add support for dispersive ε

* update markdown pages from docstrings

* make frequency and resolution parameters of plot2D dictionary keys of eps_parameters

* reinstate frequency parameter of plot2D and add warning that it is deprecated

* fix order of frequency check

* support for single-precision floating point for fields array functions (#1833)

* switch dft-related functions to using realnum from double

* more fixes

* more type conversions from double to realnum

* adjust check tolerance of tests/integrate.cpp based on floating-point precision

* more fixes

* rebase from master from fix merge conflicts

* slight adjustment to tolerances in unit tests and update docs

* remove type check in test_adjoint_solver.py

* revert return types of integration functions to double

* revert return type of process_dft_component to double

* cleanup

* Fix memory leaks (#1839)

* Fix memory leaks

* Add kkg to authors list

* Fix for Issue #1834  (#1840)

* Fix memory leaks

* Add kkg to authors list

* Expose set_default_material and use it in libpympb/pympb.cpp

* use unique_ptr (C++11) instead of make_unique (C++14) (#1844)

* update homebrew instructions for hdf5 and openblas

(fixes #1850)

* rm hack to loop over centered grid

* almost fix

* one more loop over num_chunk

* different approach

* include climits

* include climits

* clean up

* using flipped

* Revert "fix pml"

This reverts commit 9ed741e.

* fix rebase

* fix rebase

* fix rebase

* fix rebase

* fix rebase

* fix error

* increase tol

* cleanup

* cleanup

Co-authored-by: Steven G. Johnson <stevenj@alum.mit.edu>
Co-authored-by: Mo Chen <mochen@Mos-MacBook-Pro.local>
Co-authored-by: Mo Chen <mochen@dhcp-10-29-91-247.dyn.MIT.EDU>
Co-authored-by: Krishna Gadepalli <34969407+kkg4theweb@users.noreply.github.com>
Co-authored-by: Ardavan Oskooi <ardavano@google.com>
Co-authored-by: Steven G. Johnson <stevenj@mit.edu>
Co-authored-by: Alec Hammond <alec.m.hammond@gmail.com>
Co-authored-by: Andreas Hoenselaar <ahoens@google.com>
Co-authored-by: simbilod <46427609+simbilod@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Incorrect gradients when materials contain conductivities
3 participants