Code usage

Besides the tutorials there are a few ways to learn how to use keypoint-MoSeq:

  • Use the docstrings. All functions in keypoint-MoSeq have docstrings that explain their inputs, outputs and purpose. The docstrings can be accessed on this site using the search bar. They can also be accessed while coding using help(function_name) or by adding a question mark, as in function_name?.

  • Join our slack workspace. We are happy to answer questions and help troubleshoot issues.

  • Search the github issues to see if anyone else has had a similar question.

Input data

How much data do I need?

As a rule of thumb, a few hours (a few hundred thousand frames) of data are needed. More data is better. Since keypoint-MoSeq uses a hierarchical Dirichlet process (HDP) prior, the number of distinct syllables detected will gradually increase with more input data. Therefore a larger dataset may be necessary to detect rare behaviors.

How many/which keypoints?

A fine starting point is 5-10 keypoints. For rodents, we recommend omitting the tail. The most important aspect is that the keypoints are informative and provide a holistic description of the animal’s pose. If you are already tracking 4 keypoints along the spine, for example, adding 4 more may not add much new information. Note that it is always possible to exclude keypoints from modeling using the use_bodyparts setting in the config.

Multiple animals

  • For multi-animal experiments where the animals are comparable in size and shape (e.g. same sex and strain), it is best to fit a single model to all the data from both animals, which will result in two or more syllable sequences for each video. To load multi-animal data from SLEAP or DeepLabCut, the same functions can be used as for single-animal data, and each tracked animal will be added as a separate key/value pair in the coordinates and confidences dictionaries. In SLEAP, for example, a single file called two_mice.h5 will generate a pair of keys 'two_mice_track0', 'two_mice_track1'. In DeepLabCut, the name of each individual will be used as a suffix, e.g. 'two_mice_mouseA', 'two_mice_mouseB'. These keys can then be used at the end of modeling to access syllables for each animal. Since these recordings share one video, set shared_videos to True in the config (kpms.update_config(project_dir, shared_videos=True)). Otherwise checking videos, calibration and grid movies warn that a video is matched to more than one recording.

  • For multi-animal experiments where the animals differ in size (e.g. adults and pups), it is best to fit separate models. If the tracking data is contained in a single file, the use_bodyparts config option can be used to limit modeling to the subset of keypoints belonging to each animal respectively. If the tracking data for each type of animal is in separate files, then simply restrict to the appropriate files when loading the data.

Keypoints are noisy

In general, keypoint-MoSeq is tolerant to noise in keypoint tracking. During fitting, the model tries to detect and downweight tracking errors. It also takes advantage of neural network-based confidence estimates when they are available (which is typically the case for DeepLabCut and SLEAP). A good rule of thumb is to watch a video of the tracked keypoints. If you can tell what the animal is doing from the keypoints alone, then they likely provide a good starting point for keypoint-MoSeq.

High proportion of NaNs

If your keypoint tracking data contains a high proportion of NaNs, you may get the following warning when loading it with keypoint-MoSeq:

_images/nan_warning.png
  • Check if the NaNs are occurring in a specific subset of recordings. If they are, then it may be useful to exclude them from modeling, or to retrain the keypoint detection network with added training examples from the problematic recordings. For a recording-by-recording breakdown of NaNs, run

kpms.check_nan_proportions(coordinates, bodyparts, breakdown=True)
  • Rerun keypoint detection with a lower threshold for missing data. In general, keypoint tracking algorithms such as SLEAP and DeepLabCut will mark a keypoint as NaN in a given frame if its confidence is below a certain level. In SLEAP, this level can be adjusted using the argument --peak_threshold when running inference from the command line, e.g.

sleap-track VIDEO [other_args] --peak_threshold 0.05

Should I preprocess keypoints?

For 2D keypoint tracking we generally don’t recommend this. Keypoint-MoSeq is designed to work with raw keypoints. Preprocessing (e.g., smoothing, filtering, etc.) may remove important information.

Head-fixed animals

We have only tested keypoint-MoSeq on freely moving animals, using either 2D keypoint detections from a top-down/bottom-up camera, or 3D keypoint detections inferred from multiple camera angles. But head-fixed animals could work in principle. In that case, one may wish to prevent keypoint-MoSeq from inferring heading angle and performing egocentric alignment. This can be done by setting fix_heading=True in the config.

Non-rodents

Keypoint-MoSeq has only been validated on rodents (mice, rats, and anecdotal success with naked mole rats), but there is no reason in principle that it wouldn’t work on other species such as insects. If you try it on another species, please let us know how it goes! A key consideration for non-rodents is setting the target syllable duration, which may differ from the 400 ms we recommend for rodents. For additional information, see Choosing the target syllable duration.

Loading keypoint tracking data

Keypoint-MoSeq can be used with any method that produces 2D or 3D keypoint detections. Currently we support SLEAP, DeepLabCut, anipose, SLEAP-anipose, Neurodata Without Borders (NWB), Facemap, FreiPose and DANNCE. For methods not on this list, you can write a custom loading function or get in touch and request it as a new feature.

  • If using one of the supported formats, data can be loaded as follows, optionally replacing 'deeplabcut' with one of the following: 'sleap', 'anipose', 'sleap-anipose', 'nwb', 'facemap', 'freipose', 'dannce'. The file formats expected in each case are described in the docstring for keypoint_moseq.io.load_keypoints().

coordinates, confidences, bodyparts = kpms.load_keypoints(keypoint_data_path, 'deeplabcut')
  • For multi-animal data, each DeepLabCut individual or SLEAP track becomes its own recording and is treated as one animal followed through the whole file, so load tracked output, such as DeepLabCut’s _el.h5. Per-frame detections that were never tracked, such as DeepLabCut’s SuperAnimal output, don’t follow one animal.

  • If writing your own data loader, the output should be a coordinates dictionary that maps recording names to arrays of shape (num_frames, num_keypoints, num_dimensions), where num_dimensions is 2 or 3. The keypoint axis should correspond to the bodyparts list in the config. You can also include a confidences dictionary that maps recording names to arrays of shape (num_frames, num_keypoints). If your loader applies to a commonly used keypoint inference method, please let us know! We’d love to add it for others to use.

  • We are also happy to help write a loader for your data. Just open a github issue and describe the method you used for keypoint tracking and the format of the data, including the file format, how it is organized into directories, and how the output files are typically named (especially in relation to the corresponding videos). If possible, also attach one or more example files to the issue, or link to them if they are too large.

Size variation between animals

Substantial size variation between animals may cause syllables to become over-fractionated, i.e. the same behaviors may be split into multiple syllables based on size alone. We plan to address this in a future release. Please get in touch if this is a pressing issue for you, either by opening a github issue, or reaching out through our Slack workspace.

3D keypoint data

Keypoint-MoSeq can be used with 3D keypoint data.

Modeling

Validating model outputs

To confirm that model fitting was successful, you can check the following:

  • Syllables have the target duration. You can check the median duration by inspecting the plots generated during fitting (as shown below). You can also plot the distribution of syllable durations using kpms.plot_duration_distribution(project_dir, model_name). If the median duration is below/above the target value, adjust the kappa hyperparameter and re-fit the model. Initially it may be necessary to change kappa by a factor of 10 or more.

  • The syllable labels stabilized during the last few iterations of model fitting. This can be checked by inspection of the heatmaps generated during model fitting (e.g. the right-most subplot below).

  • The trajectory plots for each syllable are distinct and depict recognizable behaviors.

  • The grid movies for each syllable are distinct and internally consistent.

_images/fitting_progress.png

Choosing the target syllable duration

For rodents we recommend a target duration of ~400ms (i.e. 12 frames at 30fps), since this timescale has been validated through analyses of behavior and neural activity in previous studies. For other animals or head-fixed setups, the target duration may be different, and depends mainly on the timescale of behavior that you are interested in.

Number of model fitting iterations

It may be necessary to re-run the fitting process a few times to choose a good value for the kappa hyperparameter. During these initial runs, fitting need only be run until the syllable durations stabilize. This typically takes fewer than 10 iterations for the initial (AR only) stage of fitting, and 10-50 iterations for the second (full model) stage. After setting kappa, continue fitting until the syllable sequence stabilizes, e.g. 200-500 iterations. In our experience, the model fit improves somewhat from 200 to 500 iterations, but not after that.

Why is the first iteration slow, and where is compiled code stored?

In each session, JAX compiles every fitting step for your data’s shapes the first time it runs, which takes up to a minute on a GPU. keypoint-moseq keeps the compiled programs in a cache, so later sessions with the same data shapes and the same versions of keypoint-moseq, jax-moseq and JAX load them in seconds. The cache is in ~/.cache/keypoint_moseq/jax on Linux, ~/Library/Caches/keypoint_moseq/jax on macOS and %LOCALAPPDATA%\keypoint_moseq\keypoint_moseq\Cache\jax on Windows. It grows by a few megabytes for each new data size and each new version of keypoint-moseq, jax-moseq or JAX, and keypoint-moseq never removes old entries, so you may want to delete it now and then. Deleting it is always safe; the next session just compiles again. To keep it elsewhere, set the environment variable JAX_COMPILATION_CACHE_DIR before starting Python; keypoint-moseq then leaves JAX’s cache settings as you set them.

Detecting existing syllables in new data

If you already have a trained MoSeq model and would like to apply it to new data, you can do so using the apply_model function.

# load the most recent model checkpoint
model = kpms.load_checkpoint(project_dir, model_name)[0]

# load new data (e.g. from deeplabcut)
new_data = 'path/to/new/data/' # can be a file, a directory, or a list of files
coordinates, confidences, bodyparts = kpms.load_keypoints(new_data, 'deeplabcut')
coordinates, confidences = kpms.outlier_removal(
    coordinates, confidences, project_dir, overwrite=False, **config())
data, metadata = kpms.format_data(coordinates, confidences, **config())

# apply saved model to new data
results = kpms.apply_model(model, data, metadata, project_dir, model_name, **config())

Note

Some users have reported systematic differences in the way syllables are assigned when applying a model to new data. To control for this, we recommend running apply_model on both the new and original data and using these new results instead of the original model output. Since the original data is already in results.h5, you will need to set overwrite=True or save the results to a separate file using results_path:

# Option 1: overwrite existing results
results = kpms.apply_model(
    model, data, metadata, project_dir, model_name,
    overwrite=True, **config()
)

# Option 2: save to a separate file
results = kpms.apply_model(
    model, data, metadata, project_dir, model_name,
    results_path="path/to/new_results.h5", **config()
)

Continue model fitting but with new data

If you already trained a keypoint-MoSeq model, but would like to improve it using newly collected data (without starting from scratch), then follow the recipe below. Briefly, the code shows how to load model parameters from a saved checkpoint and then use them as the starting point for a new round of model fitting.

import keypoint_moseq as kpms

project_dir = 'project/directory'
config = lambda: kpms.load_config(project_dir)
model_name = 'name_of_model'  # e.g. '2023_03_16-15_50_11'

# load and format new data (e.g. from DeepLabCut)
new_data = 'path/to/new/data/' # can be a file, a directory, or a list of files
coordinates, confidences, bodyparts = kpms.load_keypoints(new_data, 'deeplabcut')
coordinates, confidences = kpms.outlier_removal(
    coordinates, confidences, project_dir, overwrite=False, **config())
data, metadata = kpms.format_data(coordinates, confidences, **config())

# load the model checkpoint
model = kpms.load_checkpoint(project_dir, model_name)[0]

# initialize a new model using saved parameters
model = kpms.init_model(
   data, metadata=metadata, params=model['params'],
   hypparams=model['hypparams'], **config())

# continue fitting, now with the new data
model, model_name = kpms.fit_model(
   model, data, metadata, project_dir, ar_only=False, num_iters=200,
   **config())

Interpreting model outputs

The final output of keypoint MoSeq is a results .h5 file (and optionally a directory of .csv files) that contain the following information:

  • Syllables

    The syllable label assigned to each frame (i.e. the state indexes assigned by the model).

  • Centroid and heading

    The centroid and heading of the animal in each frame, as estimated by the model.

  • Latent state

    Low-dimensional representation of the animal’s pose in each frame. These are similar to PCA scores, but are modified to reflect the pose dynamics and noise estimates inferred by the model.

Validating results when applying a model to new data

When applying a model to new data, it may be useful to generate new grid movies and trajectory plots so you can confirm that the meaning of the syllables has been preserved. Let’s say you’ve already applied the model to new data as follows:

# load new data (e.g. from deeplabcut)
coordinates, confidences, bodyparts = kpms.load_keypoints(new_data_path, 'deeplabcut')
coordinates, confidences = kpms.outlier_removal(
    coordinates, confidences, project_dir, overwrite=False, **config())
data, metadata = kpms.format_data(coordinates, confidences, **config())

# apply saved model to new data
results = kpms.apply_model(model, data, metadata, project_dir, model_name, **config())

The results dictionary returned by apply_model contains only the recordings in data, while results.h5 also holds the original recordings. If you load results from results.h5 with kpms.load_results, subset them to the new data as shown below. In either case, specify alternative paths for saving the new movies and plots so the original ones aren’t overwritten.

import os

# only include results for the new data
new_results = {k:v for k,v in results.items() if k in coordinates}

# save trajectory plots for the new data
output_dir = os.path.join(project_dir, model_name, "new_trajectory_plots")
kpms.generate_trajectory_plots(
   coordinates, new_results, project_dir,model_name, output_dir=output_dir, **config()
)

# save grid movies for the new data
output_dir = os.path.join(project_dir, model_name, "new_grid_movies")
kpms.generate_grid_movies(
   new_results, project_dir, model_name, coordinates=coordinates, output_dir=output_dir, **config()
);

Visualization

Making grid movies for 3D data

Grid movies show examples of each syllable. For 2D keypoints, these clips are cropped from the original video recordings and rotated so that the animal faces in a consistent direction. Doing the same thing for 3D data is complicated because:

  • there are usually multiple videos (from different angles) associated with each recording

  • 3D keypoints alone don’t provide enough information to crop videos around the animal

  • rotating videos to change the heading only makes sense for top-down or bottom-up views

Below we provide two code recipes to get around these issues. The first recipe is simpler and recommended for people without much programming experience.

  1. Make grid movies that just show the keypoints (i.e., without showing clips from original videos). This can be done by setting keypoints_only=True when calling keypoint_moseq.viz.generate_grid_movies(), as shown below. It may be necessary to adjust keypoints_scale, which determines the number of pixels per 3D unit (the default value keypoints_scale=1.0 means that 1 unit in 3D space corresponds to 1 pixel in the grid movie).

    kpms.generate_grid_movies(
       results,
       project_dir,
       model_name,
       coordinates=coordinates,
       keypoints_only=True,
       keypoints_scale=1,
       use_dims=[0,1], # controls projection plane
       **config());
    
  2. Pick a camera angle and load the 2D keypoint detections from that camera. The exact code for this will depend on the format of the 2D keypoints and the way that the 3D keypoint files, 2D keypoint files, and video files are organized. To take a simple example, let’s say you filmed a mouse from the top and the side, performed 2D keypoint detection using SLEAP, and now have the following files for each recording:

    <video_dir>/
    ├──<recording_name>.h5        # 3D keypoints
    ├──top-<recording_name>.h5    # 2D keypoints from top camera
    ├──top-<recording_name>.mp4   # video from top camera
    ├──side-<recording_name>.h5   # 2D keypoints from side camera
    ├──side-<recording_name>.mp4  # video from side camera
    

    To make grid movies using the top-camera, you’d need to load the top-camera 2D keypoints and match them up with the modeling results (which were most likely named using the 3D keypoints files), then compute 2D centroids and headings, and finally pass everything to keypoint_moseq.viz.generate_grid_movies().

    video_dir = ... # insert path to video directory
    
    coordinates_2D,_,_ = kpms.load_keypoints(f'{video_dir}/top-*', 'sleap')
    video_paths = kpms.find_matching_videos(coordinates_2D.keys(), video_dir, as_dict=True)
    
    # rename keys to match the results dictionary
    coordinates_2D = {k.replace('top-', ''): v for k, v in coordinates_2D.items()}
    video_paths    = {k.replace('top-', ''): v for k, v in video_paths.items()}
    
    # compute the 2D centroid and heading
    centroids, headings = kpms.get_centroids_headings(coordinates_2D, **config())
    
    # make the grid movies
    kpms.generate_grid_movies(
       results,
       project_dir,
       model_name,
       video_paths=video_paths,
       coordinates=coordinates_2D,
       centroids=centroids,
       headings=headings,
       **config());
    

    You could follow a similar procedure for the side camera, but adding an extra line to zero-out the heading so the video clips aren’t rotated.

    headings = {k: np.zeros_like(v) for k, v in headings.items()}
    

Why are there only trajectory plots for a subset of syllables?

There are two reasons why a syllable might be excluded from the trajectory plots:

  1. Its frequency is below min_frequency. By default min_frequency=0.005, meaning that the syllable must make up at least 0.5% of all syllable instances. Lowering min_frequency may result in more syllables being included in the trajectory plots.

  2. There aren’t enough usable instances of the syllable. The number of required instances (50 by default) is set by the n_neighbors key of the sampling_options parameter. If you want to lower this number, (e.g. to 20) then you could call generate_trajectory_plots as follows.

    kpms.generate_trajectory_plots(..., sampling_options={"mode": "density", "n_neighbors": 20})
    

    Note that the number of usable syllable instances may be less than the total number of instances. Three criteria determine whether an instance is usable:

    • before_onset_sec: the time, in seconds, before syllable onset that is included in the trajectory. By default, before_onset_sec=0.167 (5 frames at 30 fps). If a particular syllable instance starts within the first before_onset_sec seconds of the video, then it is excluded.

    • after_onset_sec: the time, in seconds, after syllable onset that is included in the trajectory. By default, after_onset_sec=0.5 (15 frames at 30 fps). If a particular syllable instance starts within the last after_onset_sec seconds of the video, then it is excluded.

    • min_instance_duration_sec: the minimum duration of a syllable instance, in seconds. By default, min_instance_duration_sec=0.1 (3 frames at 30 fps), meaning that shorter syllable instances are excluded.

In summary, the following parameter changes will tend to increase the number of syllables included in the trajectory plots:

  • Lowering min_frequency (e.g. to 0.001)

  • Lowering n_neighbors (e.g. to 20)

  • Lowering before_onset_sec (at this point you’re scraping the bottom of the barrel)

  • Lowering after_onset_sec (again, scraping the bottom of the barrel here)

  • Lowering min_instance_duration_sec (this should be avoided; why are your syllables so short?)

Why are there only grid movies for a subset of syllables?

There are two reasons why a syllable might not have a grid movie:

  1. Its frequency is below min_frequency. By default min_frequency=0.005, meaning that the syllable must make up at least 0.5% of all syllable instances. Lowering min_frequency may result in more syllables being included among the grid movies.

  2. There aren’t enough usable instances of the syllable. There have to be at least enough instances to fill up every cell of the grid. The number of grid cells is determined by the rows and cols parameters. Note that the number of usable syllable instances may be less than the total number of instances. Three criteria determine whether an instance is usable:

    • before_onset_sec: the time, in seconds, before syllable onset that is included in the grid movie. By default, before_onset_sec=1.0, meaning that the movie in each grid cell starts 1 second before syllable onset. So if a particular syllable instance starts within the first second of the experiment, then it is excluded.

    • after_onset_sec: the time, in seconds, after syllable onset that is included in the grid movie. By default, after_onset_sec=2.0, meaning that the movie in each grid cell ends 2 seconds after syllable onset. If a particular syllable instance starts within the last 2 seconds of the experiment, then it is excluded.

    • min_instance_duration_sec: the minimum duration of a syllable instance, in seconds. By default, min_instance_duration_sec=0.1 (3 frames at 30 fps), meaning that shorter syllable instances are excluded.

In summary, the following parameter changes will tend to increase the number of syllables included in the grid movies:

  • Lowering min_frequency (e.g. to 0.001)

  • Lowering before_onset_sec (at this point you’re scraping the bottom of the barrel)

  • Lowering after_onset_sec (again, scraping the bottom of the barrel here)

  • Lowering min_instance_duration_sec (this should be avoided; why are your syllables so short?)

Why do my trajectory plots and grid movies disagree?

Users occasionally find that the trajectory plot and grid movie for a given syllable don’t match up. For example the animal might turn left in the trajectory plot but not consistently do so in the grid movie. Similarly, trajectory plots can occasionally change dramatically when a trained keypoint-MoSeq model is applied to new data. In most cases, these inconsistencies are caused by density sampling of syllable instances. Turning this feature off may result in more stable trajectory plots.

kpms.generate_trajectory_plots(..., density_sample=False)

Density sampling is a way of selecting syllable instances that are most representative relative to the full dataset. Specifically, for each syllable, a syllable-specific density function is computed in trajectory space and compared to the overall density across all syllables. An exemplar instance that maximizes the ratio between these densities is chosen for each syllable, and its nearest neighbors are randomly sampled. When the distribution of trajectories for a syllable is multimodal (i.e., it represents a mixture of distinct behaviors), the exemplar syllable may not capture the full range of behaviors, or it may jump from one mode to another when an existing model is applied to new data. In these cases, it may be better to sample syllable instances uniformly by turning off density sampling as shown above.

Two different syllables look very similar. Is there a way to consider them as one syllable?

Yes, see the Merging similar syllables section in the Advanced Usage guide for instructions on how to combine syllables that represent the same behavior.

What statistical test is used to flag significant syllables in the syllable statistics plot?

The red stars in the plot produced by keypoint_moseq.analysis.plot_syll_stats_with_sem() come from a permutation-based Kruskal–Wallis test followed by a Dunn’s z-test post-hoc, with Benjamini–Hochberg (FDR) correction applied at two levels. The same procedure is used regardless of which statistic is plotted (frequency, duration, velocity_px_s_mean, etc.).

Omnibus test. For each syllable, a Kruskal–Wallis H statistic compares the groups. Significance is established empirically by shuffling group labels 10,000 times and recomputing H. The resulting per-syllable p-values are BH-adjusted across the syllables that were tested, as one correction family.

Post-hoc. For each syllable, a Dunn’s z-test is run on every pair of groups, again with empirical p-values from the same permutations. These are BH-adjusted within each syllable, across pairs — one correction family of size N_pairs, applied independently for each syllable. There is no joint correction across the full (syllable × pair) grid. For two-group experiments this post-hoc correction is a no-op (only one pair).

What the red stars mean. A syllable is starred for a given pair of groups only if its omnibus FDR-adjusted p-value (corrected across syllables) is at or below the significance threshold (default 0.05) and its FDR-adjusted Dunn’s pairwise p-value (corrected across pairs within that syllable) is below it.

Error bars are not from this test. The error bars are 68% bootstrap confidence intervals on each group’s mean across recordings. They reflect uncertainty in the group mean, not the significance test.

Notes.

  • The tests are nonparametric and rank-based, so they do not assume normality.

  • For duration and the kinematic statistics, a recording that never used a syllable has no value for it and is left out of that syllable’s test. A syllable is not tested, and never starred, when a group has no recordings with a value.

  • The p-values come from shuffling recordings between groups, so small groups limit how low they can go. With two groups of 3 recordings there are only 20 ways to split them, so no p-value is below 0.1 and nothing is starred. run_kruskal warns when a group has fewer than 3 recordings with a value.

  • To change the threshold, number of permutations, or multiple-comparisons method, call keypoint_moseq.analysis.run_kruskal() directly:

    df_kw, df_dunn, sig_sylls = kpms.analysis.run_kruskal(
        stats_df, statistic="frequency",
        n_perm=10000, thresh=0.05, mc_method="fdr_bh",
    )
    

Troubleshooting

Many problems are fixed in newer versions of keypoint-MoSeq, so first make sure you are using the latest one. Running kpms.check_installation() in a notebook prints the installed versions of keypoint-MoSeq and JAX and the devices JAX can use, and explains any installation problem it finds. To update to the latest version, run the following in a terminal, in the environment where keypoint-moseq is installed (not inside a Jupyter notebook):

pip install -U keypoint-moseq            # CPU
pip install -U "keypoint-moseq[cuda]"    # GPU with CUDA 12

Restart the kernel of any open notebook to use the updated version. If your problem remains after troubleshooting, please open a github issue.

Dead kernel

On Windows, GPU out of memory (OOM) errors may cause silent kernel failure. To determine whether this is the likely cause, try re-fitting the model using a small subset of the data. If the kernel still dies, then it is likely a different issue. If the kernel does not die, then it is likely an OOM error. Some workarounds for OOM errors are described below.

Out of memory

There are two main causes of GPU out of memory (OOM) errors:

  1. Multiple instances of keypoint MoSeq are running on the same GPU.

This can happen if you’re running multiple notebooks or scripts at the same time. Since JAX preallocates 75% of the GPU when it is first initialized (i.e. after running import keypoint_moseq), there is very little memory left for the second notebook/script. To fix this, you can either shut down the kernels of the other notebooks/scripts or use a different GPU.

  1. Large datasets.

Required GPU memory scales roughly linearly with the size of the dataset. With 4 latent dimensions and 100 states, model fitting needs about 0.5 GB plus roughly 0.05 MB of GPU memory per 100 frames of data, and more with more states. Before fitting on a GPU, keypoint-MoSeq measures the memory its largest steps need and, if they would not fit, runs the pose step over fewer segments at a time, which is slower. If your GPU still isn’t big enough, try one of the following:

  • Use Google colab.

    • Colab provides free access to GPUs with 16GB of VRAM.

    • Larger GPUs can be accessed using colab pro.

  • Use multiple GPUs if they are available (Linux only, including WSL2). To split the computation across GPUs, run the following code before fitting the model (if you have already initiated model fitting the kernel must be restarted).

from jax_moseq.utils import set_mixed_map_gpus
set_mixed_map_gpus(2)

This will split the computation across two GPUs. The number should be adjusted according to your hardware setup.

  • Fit to a subset of the data, then apply the model to the rest of the data.

    • To fit a subset of the data, specify the subset as a list of paths during data loading

      initial_data = ['path/to/file1.h5', 'path/to/file2.h5']
      coordinates, confidences, bodyparts = kpms.load_keypoints(initial_data, 'deeplabcut')
      
    • After model fitting, apply the model serially to the old and new data as follows

      model = kpms.load_checkpoint(project_dir, model_name)[0]
      
      new_data_batch1 = ['path/to/file3.h5', 'path/to/second/file4.h5']
      new_data_batch2 = ['path/to/file5.h5', 'path/to/second/file6.h5']
      
      for batch in [initial_data, new_data_batch1, new_data_batch2]:
      
          coordinates, confidences, bodyparts = kpms.load_keypoints(batch, 'deeplabcut')
          coordinates, confidences = kpms.outlier_removal(
              coordinates, confidences, project_dir, overwrite=False, **config())
          data, metadata = kpms.format_data(coordinates, confidences, **config())
          # overwrite=True replaces the results saved for the initial recordings
          results = kpms.apply_model(
              model, data, metadata, project_dir, model_name, overwrite=True, **config())
      

NaNs during fitting

In our experience, NaNs during fitting most often come from the data, usually stretches of a recording where the keypoints aren’t following a freely moving animal. Work through the steps below in order.

The data checks come before the sampler settings for a reason. Raising jitter can stop the NaNs without removing their cause, and the model still has to fit those frames. That can leave you with syllables that describe tracking problems rather than behavior.

Check your data

Three kinds of recording problems account for most of the NaNs we see. Each one gives the model frames that don’t look like a freely moving animal.

  1. Long periods without movement, such as sleep or long bouts of freezing.

  2. The animal entering or leaving the frame. Some recordings start before the animal is placed in the arena or keep going after it is taken out. While the arena is empty, the tracker labels whatever it can find, and the keypoints jump when the animal appears.

  3. Something else in the frame. An experimenter’s hand, a cable, or anything else that pulls the keypoints off the animal.

To look for these, watch the first and last minute of a few videos, and check the plots the outlier removal step saves to {project_dir}/QA/plots/keypoint_distance_outliers/. Long flat stretches in those plots mean the keypoints barely moved for that time.

Once you’ve found a problem stretch:

  • At the start or end of a recording, trim those frames from coordinates and confidences before formatting the data. Trimming inputs shows how to keep grid movies and other video steps lined up afterward using video_frame_indexes.

  • A long stretch in the middle of a recording: the easiest thing to do is exclude that recording from modeling.

Adjust the sampler

If your data looks clean but the NaNs persist, try these. Each is a keyword argument to the function that produced the NaNs (fit_model, apply_model or estimate_syllable_marginals).

  • Increase jitter. Jitter is a small variance added to each pose draw so the matrix math doesn’t fail. It’s measured in the model’s latent pose space, where each dimension has variance 1 (with the default whiten: true). The default 1e-3 is 0.1% of that; try raising it to at most 1e-2. Much larger values add noise on the scale of the animal’s own frame-to-frame movement. Jitter only affects the serial Kalman sampler, which is the default on CPU or when parallel_message_passing=False.

  • Enable parallel Kalman sampling with parallel_message_passing=True. By default it is only enabled when fitting on a GPU.

If the NaNs persist

Open an issue at https://github.com/dattalab/keypoint-moseq/issues. Include your config file, the code you ran, your keypoint-moseq version and the iteration where the NaNs appeared. We may ask for your data and most recent model checkpoint.

Installation errors

  • UNKNOWN: no kernel image is available for execution on the device

    If you’re running into issues when trying to use the GPU-accelerated version, you might see this error message:

    jaxlib.xla_extension.XlaRuntimeError: UNKNOWN: no kernel image is available for execution on the device
    

    Run kpms.check_installation() in a notebook. It runs a small computation on the GPU and, if it fails with this error, explains the likely cause: the installed jaxlib has no code for this GPU, because the GPU or its NVIDIA driver is too old. nvidia-smi shows the driver version; if the driver is old, update it.