Repository navigation
Description
Describe the issue:
Right now, we cache Jmatrix in a lot of places (which is good for saving computation!) but we are not careful about checking if the m that is provided to getJ is indeed consistent with self.model and therefore with the Jmatrix that is returned. This can lead to some confusing behaviour
For example, if you are performing a sensitivity analysis, you could get yourself into a confusing spot
Reproducible code example:
model1 = halfspace
model2 = model_with_structure
sim = dc.Simulation2DNodal(mesh, survey, storeJ=True) # because I later want to run an inversion
J1 = sim.getJ(model1)
J2 = sim.getJ(model2) # this will return J1 -- wrong!Error message:
No response
Runtime information:
latest SimPEG version
Context for the issue:
This is a conceptual bug. Although it could be resolved if we set storeJ=False, the behaviour is non-intuitive and is something that we should address.
The issue lies here
simpeg/SimPEG/electromagnetics/static/resistivity/simulation_2d.py
Lines 267 to 278 in 716e221
| def getJ(self, m, f=None): | |
| """ | |
| Generate Full sensitivity matrix | |
| """ | |
| if getattr(self, "_Jmatrix", None) is None: | |
| if self.verbose: | |
| print("Calculating J and storing") | |
| self.model = m | |
| if f is None: | |
| f = self.fields(m) | |
| self._Jmatrix = (self._Jtvec(m, v=None, f=f)).T | |
| return self._Jmatrix |
My suggestion, include a check that the model provided is basically the same as self.model. If this is computationally expensive enough that we don't want to be calling it every time, then we could also allow m=None and we return the cached J. Something like the following:
def getJ(self, m=None, f=None):
"""
Generate Full sensitivity matrix
"""
if m is None:
if self._Jmatrix is not None:
return self._Jmatrix # early return if no model provided and J has been created
elif not np.all_close(m, self.model):
self.model = m # this will clear self._Jmatrix if it exists
if getattr(self, "_Jmatrix", None) is None:
if self.verbose:
print("Calculating J and storing")
if f is None:
f = self.fields(m)
self._Jmatrix = (self._Jtvec(self.model, v=None, f=f)).T
return self._Jmatrix
Thanks @anna1963 for catching this!
Note that I only highlighted this for DC, but it will be common to wherever we have getJ
Activity
ghwilliams commentedon Feb 13, 2024
I had already experienced this too. My solution was to do
sim1._Jmatrix = None
sim1.getJ(myModel)
in order to force getJ to return J for myModel.
jcapriot commentedon Feb 13, 2024
We need to be vigilant about assigning to the model on calls to any function where the model is an argument.
I.e. it should be:
Which should erase the cached
_Jmatrixif the model has changed.We are only doing this on certain calls, in certain cases. It should be everywhere.
ghwilliams commentedon Feb 13, 2024
We could use checksum to check if the model has changed. Very vague idea here.
santisoler commentedon Feb 22, 2024
I've just reviewed @lheagy's PR (#1361) and I think we should go forward with that, but nonetheless I wanted to leave my two cents in this discussion.
The proposed fix in #1361 (and how some other simulations handle the assignment of the model) can be error prone. By assigning the model with:
we are assigning the
modelattribute as a reference to the passed model. Therefore we could be changing that model from outside, what might introduce unwanted behaviour without any hint.For example, lets say we have the following simulation:
Then let's define a conductivity model and run
getJ:Now, if we modify the
sigmaarray:we are also changing the stored
modelin the simulation:This means that now the cached
_Jmatrixdoesn't correspond to the one of the assignedmodel.One possible solution is to assign a deep copy of the
marray:But this impacts performance: requires more RAM and allocates an array on every call. Another way to make sure that the current J corresponds to the right model is through a checksum, as @ghwilliams proposed.
I'm just mentioning this to keep it in mind. We probably don't need to tackle this for this bugfix, but at some point it would be nice to revisit this.
jcapriot commentedon Feb 23, 2024
That’s a very good point as well. I think what we could do is only copy it when it changes… The relevant bits are in the
HasModelclass. There it checks if the passed model is close to whatever came before. If it changes “enough” it stores the passed array on the model. Instead we could store it as a copy. We could even set theWriteableflag on this copied model toFalseto prevent people from modifying the stored copy.jcapriot commentedon Feb 23, 2024
simpeg/SimPEG/props.py
Line 461 in b22e6a2
jcapriot commentedon Feb 23, 2024
As a note about checksums, since we’re talking about it. I don’t think it will be a realistic solution for this, because the checksum operation is not unique.
Two arrays could have different values but the same checksum. This is referred to as a collision. So when two arrays would have the same check sum, you would still need to actually compare all of the values of the arrays… which means we would still need to store an immutable copy of the model to check against. So the operation would go:
So, I don’t see anyway to get around storing an immutable copy of the array and just checking all of the values.
I don’t have anything other than a feeling for this next bit: It’s also likely slower when the arrays are equal (which is the timing we actually care about). When the arrays are equal you would have to loop over the elements of the array to compute a checksum, then loop over all of the elements again to compare equality.
santisoler commentedon Feb 23, 2024
You're right that checksums might lead to collisions, but the sha256 hashes of two different arrays have a collision probability of$\simeq 1 / 2^{256}$ , which is extremely low. In practical applications we could consider that two arrays with equal hashes have the same values.
This is good enough for security applications, so I think we should be fine with using checksums to assess if the passed model is the same one as before or not.
jcapriot commentedon Feb 26, 2024
That's true, then we would need to consider a few things:
Our current logic, which happens after the input has been tested for consistent shape, type, etc.
Clearly this cannot catch in-place changes to the model.
That being said, a few things it does well:
all_closeall_closeafter many changes.)Assuming we still want to be able to access the model vector last assigned to a simulation from
sim.modelThe problem is that it can't check for inplace operations done to the model.
A few potential solutions then:
1) Store a copy of the new array (will never be able to short-circuit by checking two models are the same object)
2) Hash the new input and compare to previous hash value
3) Make the passed model immutable on storage
model.flags['WRITEABLE'] = False.In general the timing we are most concerned with, is when we repeatedly pass the same model to the functions Jvec and Jtvec, as those are usually called repeatedly inside iterative CG solvers.
Option 1 would require the most memory and more time than 3.
Option 2 would require more time than 3 but similar amounts of memory as 3
Option 3 would result in the quickest timing of the three (due to being able to check if they are the same object), but it could cause a few headaches to users.
Something to consider about checking if the model is changed:
Do we want to continue using an
all_closecall to check for changes in the model?If 2 does take more time, is the amount of time even impactful?
Some rough timing on machines, on an array of float64:
np.allclosetake about the same amount of time. This is about 2-3 ms for a 1 million length array.np.array_equalis about 10x as fast as the previous.arr is arris essentially free (<10ns).My first guess is that hashing probably won't take up that much time relative to doing the bigger operation of
Jvec/Jtvec(we should also be conscious of if calling one of those with a storedJmatrix will make multiple passes at assigning the model).santisoler commentedon Feb 27, 2024
Thanks for sharing those thoughts @jcapriot.
Just some personal opinions and preferences after reading them:
Have clear scopes for the model attribute
I think we should be super explicit at separating the scope and ownership of the class attributes. In this particular case, I think the
modelin thesimulationshouldn't be a vector owned by the user, which could lead to unwanted behaviour in case that model gets change from outside the simulation class.I don't quite like the
model.flags['WRITEABLE'] = Falseoption. It's hard to document that, it's non-intuitive among scientific Python users, and if something goes wrong error messages will come from anywhere down the line (e.g.: try to edit the model after running the inversion), which would be a nightmare to debug.Keep
simulation.model?Considering these opinions: if we really want to be able to access the last
modelpassed to the simulation, I think the straight forward solution is to store a copy of the passedmodel:Then the checks for updates could be done as you mentioned (
np.allclose,np.array_equal).If we are not going to store the
modelin the simulation...If we choose that we can live without having the previous
modelin the simulation, then I think the hash solution is great. We would need to keep record of the hash of the last model passed to the simulation, and check against it everytime we need to return the J matrix. Something like:Set the model when calling `getJ` in DC and SIP simulations (simpeg#1361