Skip to content

get_noise_levels returns a cached value even when the call asks for a different seed or chunks #4928

Open

Description

@grahamfindlay

get_noise_levels caches its result on the recording, as a property named noise_level_{method}_{scaled|raw}. The key doesn't include random_slices_kwargs (seed, number of chunks, nor length of chunks). So future calls that ask for a different seed or chunks don't get what they ask for, and there is no warning. And as a downstream consequence, code that records its own parameters (what it asked for) ends up recording ones that weren't used (because what was actually used is whatever was in the cache).

Two possible fixes:

  1. Store all the relevant parameters with the cached value, and recompute when a call asks for different ones.
  2. Drop the cache, and pass noise levels explicitly or take them from the noise_levels extension, which records its params.

I only mention option 2 because gets rid of hidden state. But it would be way too complicated, I think. I think option 1 is the only reasonable option. Assuming option 1, there are a couple decisions to make:

  • seed=None means "accept anything with the same chunk layout"?
  • A request with different parameters replaces the cached value? Keeping several entries is possible... but probably not worth the complexity?

Activity

  1. added
    bug
    discussion
    on Nov 8, 2026
  2. chrishalcrow commented on Nov 10, 2026

    @chrishalcrow
    Member

    Would be great to fix.

    I think main use of this cache is in sorting components and internal sorters, which need the noise levels repeatedly. So I think 1. is the right solution in that context. I would vote that seed=None is equiv to "I don't care" => accept anything with the same chunk layout. I think keeping one cached value is good.

    I'm not 100% sure where to keep the kwargs. The recording properties don't have a generic associated place to store kwargs. Using the property name as a place to store them is a bit awkward. Anyone have any better ideas? Are there other properties where it would be good to keep kwargs?

  3. grahamfindlay commented on Nov 12, 2026

    @grahamfindlay
    CollaboratorAuthor

    I think I'd put the kwargs in an annotation, one annotation for each set of stored noise levels. Each annotation holds a dict (e.g., for the noise_level_mad_scaled property: noise_level_mad_scaled_params = {"seed": 42, "num_chunks_per_segment": 20, "chunk_size":15000, ...}).

    The challenge is that the kwargs/annotation need to get copied and dropped at the same moments as the noise levels. For example, right now, copy_metadata drops the noise levels (in _skip_properties) so that a filtered recording, say, can get its own noise levels. But copy_metadata keeps every annotation. So basically, I think we would need to add a _skip_annotations to copy_metadata.

    It seems like right now just about everywhere else (e.g. saving to zarr, pickling to workers) properties and annotations are either kept or dropped together (good).

  4. h-mayorquin commented on Nov 12, 2026

    @h-mayorquin
    Contributor

    We discussed a possible solution in today's maintainers meeting. I wrote a general framework for thinking about this in #4939 so here I just want to draft the idea of the state dict that we discussed today.

    The idea is that for properties we could keep another dict that indicates what type of state they are (see the table of types in #4939) and therefore how consumers should use it. Something like this:

    recording._properties_metadata = {
        "gain_to_uV": {"origin": "format"},  # set by the reader in __init__, rebuilding the recording sets it again
        "location": {"origin": "format"},  # same
        "brain_area": {"origin": "user"},  # set by the user after construction, only the user knows it
        "noise_level_mad_scaled": {  # set by get_noise_levels
            "origin": "computed",  # derived from the traces, can be rebuilt but it costs time
            "params": {"seed": 42, "num_chunks_per_segment": 20, "chunk_size": 10000},  # what produced the values
        },
    }

    The important thing is that the dictionary gives us cues of how each consumer should handle each property, as in the consumer table of #4939. For example, a "user" property like brain_area has to travel to a spawn worker, while a "format" property like gain_to_uV doesn't, as the worker rebuilds it from the construction.

    For this specific case (calculating the noise levels) it would tell us the following:

    • get_noise_levels returns the cached values only if the "params" match the random_slices_kwargs of the call, and computes them again otherwise. seed=None accepts any seed, as Chris suggested.
    • copy_metadata drops the noise levels after a preprocessing step because their origin is "computed" and the traces changed, not because they are in the hardcoded _skip_properties list. Any computed property we add later gets the same treatment.
    • I think pickling and saving should carry the noise levels together with their "params", so a worker or a loaded folder can reuse them instead of computing them again.

    @samuelgarcia @alejoe91 @JoeZiminski

  5. h-mayorquin commented on Nov 12, 2026

    @h-mayorquin
    Contributor

    That said, I do not think that we should wait till Christmas (which in France occasionally falls on Easter, owing to the précession des équi-Noëls, or the Garcia instability as it is known in celestial mechanics) to solve this problem here.

    There is a simpler way forward that should not block or get in the way of the more general solution later. I think that we can keep the noise levels in the property and store the parameters that produced them in a private dict, recording._noise_levels_params[key]. When the dict lands this becomes the "params" entry of the property, and nothing user-facing changes in between.

    With that:

    • get_noise_levels returns the cached values only if the stored parameters match the call. It compares them after filling the defaults of get_random_sample_slices, so {} and {"seed": None} are the same call, and seed=None accepts any stored seed.
    • A noise level property without stored parameters counts as a miss and is computed again once. This is the case of a loaded folder, as saving doesn't write the private dict.
    • copy_metadata needs no change, as it already drops the property and the derived recording starts without the private dict.
    • highpass_spatial_filter reads noise_level_rms_raw directly and skips the check, so it should call get_noise_levels with its random_slice_kwargs instead.

    I prefer this over the annotation because an annotation is saved to disk which would introduce version dependent annoyances.

  6. grahamfindlay commented on Nov 12, 2026

    @grahamfindlay
    CollaboratorAuthor

    @h-mayorquin I have to think more about #4939 , but the interim solution sounds good to me! With one caveat (that probably bears on the more general framework you proposed, too):

    What happens if the noise levels were set by hand? Because that's what I'm actually doing. I am using recording.set_property("noise_level_std_scaled", values) to make SpikeInterface use noise levels computed elsewhere. I'm doing it so that sd_ratio divides by noise measured outside artifact periods (eventually I want to have a way to do this in SpikeInterface).

    If a property without stored parameters counts as a miss, get_noise_levels would quietly recompute over those values.

    Possible solution: Could a property without stored parameters count as a miss only when the call asks for something specific (a seed, or a chunk layout other than the defaults), and be returned otherwise? So set-by-hand values would keep working for calls that leave the parameters at their defaults, like sd_ratio without a seed, and those calls would also reuse a loaded folder's noise levels instead of computing them again. Calls that ask for specific parameters would still get exactly what they asked for.

    It is a bit weird, but this is the only decent way I could come up with that preserves a user's ability to set properties by hand (which I do an awful lot).

  7. h-mayorquin commented on Nov 13, 2026

    @h-mayorquin
    Contributor

    Good point, I did not think about noise levels set by hand.
    I think your rule is right. A call that leaves the parameters at their defaults gets what it gets today, the stored values, and a call that asks for a seed or a chunk layout gets exactly what it asked for. So nothing that works today breaks, including your sd_ratio case and the noise levels of a loaded folder.

    This is also a good example for #4939. Noise levels set with set_property are user state, and a value the user set should win over computing one unless the call explicitly asks for a different computation. With the metadata dict your values would be {"origin": "user"}, and your rule is how get_noise_levels would read them.

  8. chrishalcrow commented on Nov 13, 2026

    @chrishalcrow
    Member

    I'm in favor of the interim solution, and agree that a call that asks for nothing specific should get whatever is cached.

    Talking of sd_ratio and tangentially related to this, it would be great to loosen the requirement for the analyzer to have a recording attached here:

    if not sorting_analyzer.has_recording():

    So that the metric can still be computed if noise_level_std_scaled is a recording property (in the analyzer's rec_attributes). It's one of the only metrics that requires the recording, and it would be great to have a way to recompute in recordingless mode, especially for merges/splits in curation. Only realised this would be possible thanks to this issue!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugdiscussion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions