Commit 0063a668 authored by chenzk's avatar chenzk
Browse files

v1.0

parents
import glob
import json
import os
import pickle
from datetime import datetime
import numpy as np
import tensorflow_datasets as tfds
from absl import logging
from dataset_builder import MultiThreadedDatasetBuilder
from PIL import Image
# we ignore the small amount of data that contains >4 views
N_VIEWS = 4
IMAGE_SIZE = (480, 640)
DEPTH = 5
TRAIN_PROPORTION = 0.9
ORIG_NAMES = [f"images{i}" for i in range(N_VIEWS)]
NEW_NAMES = [f"image_{i}" for i in range(N_VIEWS)]
def read_image(path: str) -> np.ndarray:
with Image.open(path) as im:
# depth should be uint16 (I;16), but PIL has a bug where it reads as int32 (I)
# there are also few trajectories where it's uint8 (L) for some reason
# we just cast to uint16 in both cases
assert im.mode == "RGB" or im.mode == "I" or im.mode == "L", (path, im.mode)
assert im.size == (640, 480), (path, im.size)
arr = np.array(im)
if arr.ndim == 2:
return arr[..., None].astype(np.uint16)
else:
assert arr.ndim == 3 and arr.shape[-1] == 3, (path, arr.shape)
assert arr.dtype == np.uint8, (path, arr.dtype)
return arr
# you can speed things up significantly by skipping image decoding/re-encoding by using the line below,
# but then you also need to skip the checks
# return open(path, "rb").read()
def process_images(path): # processes images at a trajectory level
image_dirs = set(os.listdir(str(path))).intersection(set(ORIG_NAMES))
image_paths = [
sorted(
glob.glob(os.path.join(path, image_dir, "im_*.jpg")),
key=lambda x: int(x.split("_")[-1].split(".")[0]),
)
for image_dir in image_dirs
]
filenames = [[path.split("/")[-1] for path in x] for x in image_paths]
assert all(x == filenames[0] for x in filenames), (path, filenames)
d = {
image_dir: [read_image(path) for path in p]
for image_dir, p in zip(image_dirs, image_paths)
}
return d
def process_depth(path):
depth_path = os.path.join(path, "depth_images0")
if os.path.exists(depth_path):
image_paths = sorted(
glob.glob(os.path.join(depth_path, "im_*.png")),
key=lambda x: int(x.split("_")[-1].split(".")[0]),
)
return [read_image(path) for path in image_paths]
else:
return None
def process_state(path):
fp = os.path.join(path, "obs_dict.pkl")
with open(fp, "rb") as f:
x = pickle.load(f)
return x["full_state"]
def process_actions(path):
fp = os.path.join(path, "policy_out.pkl")
with open(fp, "rb") as f:
act_list = pickle.load(f)
if isinstance(act_list[0], dict):
act_list = [x["actions"] for x in act_list]
return act_list
def process_lang(path):
fp = os.path.join(path, "lang.txt")
text = "" # empty string is a placeholder for missing text
if os.path.exists(fp):
with open(fp, "r") as f:
text = f.readline().strip()
return text
class BridgeDataset(MultiThreadedDatasetBuilder):
"""DatasetBuilder for bridge dataset."""
VERSION = tfds.core.Version("1.0.0")
RELEASE_NOTES = {
"1.0.0": "Initial release.",
}
MANUAL_DOWNLOAD_INSTRUCTIONS = "You can download the raw BridgeData from https://rail.eecs.berkeley.edu/datasets/bridge_release/data/."
NUM_WORKERS = 16
CHUNKSIZE = 1000
def _info(self) -> tfds.core.DatasetInfo:
"""Dataset metadata (homepage, citation,...)."""
return self.dataset_info_from_configs(
features=tfds.features.FeaturesDict(
{
"steps": tfds.features.Dataset(
{
"observation": tfds.features.FeaturesDict(
{
"image_0": tfds.features.Image(
shape=IMAGE_SIZE + (3,),
dtype=np.uint8,
encoding_format="jpeg",
doc="Main camera RGB observation (fixed position).",
),
"image_1": tfds.features.Image(
shape=IMAGE_SIZE + (3,),
dtype=np.uint8,
encoding_format="jpeg",
doc="Side camera RGB observation (varied position).",
),
"image_2": tfds.features.Image(
shape=IMAGE_SIZE + (3,),
dtype=np.uint8,
encoding_format="jpeg",
doc="Side camera RGB observation (varied position)",
),
"image_3": tfds.features.Image(
shape=IMAGE_SIZE + (3,),
dtype=np.uint8,
encoding_format="jpeg",
doc="Wrist camera RGB observation.",
),
"depth_0": tfds.features.Image(
shape=IMAGE_SIZE + (1,),
dtype=np.uint16,
encoding_format="png",
doc="Main camera depth observation (fixed position).",
),
"state": tfds.features.Tensor(
shape=(7,),
dtype=np.float32,
doc="Robot end effector state, consists of [3x XYZ, 3x roll-pitch-yaw, 1x gripper]",
),
}
),
"action": tfds.features.Tensor(
shape=(7,),
dtype=np.float32,
doc="Robot action, consists of [3x XYZ delta, 3x roll-pitch-yaw delta, 1x gripper absolute].",
),
"is_first": tfds.features.Scalar(
dtype=np.bool_, doc="True on first step of the episode."
),
"is_last": tfds.features.Scalar(
dtype=np.bool_, doc="True on last step of the episode."
),
"language_instruction": tfds.features.Text(
doc="Language Instruction."
),
}
),
"episode_metadata": tfds.features.FeaturesDict(
{
"file_path": tfds.features.Text(
doc="Path to the original data file."
),
"has_image_0": tfds.features.Scalar(
dtype=np.bool_,
doc="True if image0 exists in observation, otherwise dummy value.",
),
"has_image_1": tfds.features.Scalar(
dtype=np.bool_,
doc="True if image1 exists in observation, otherwise dummy value.",
),
"has_image_2": tfds.features.Scalar(
dtype=np.bool_,
doc="True if image2 exists in observation, otherwise dummy value.",
),
"has_image_3": tfds.features.Scalar(
dtype=np.bool_,
doc="True if image3 exists in observation, otherwise dummy value.",
),
"has_depth_0": tfds.features.Scalar(
dtype=np.bool_,
doc="True if depth0 exists in observation, otherwise dummy value.",
),
"has_language": tfds.features.Scalar(
dtype=np.bool_,
doc="True if language exists in observation, otherwise empty string.",
),
}
),
}
)
)
@classmethod
def _process_example(cls, example_input):
"""Process a single example."""
path, camera_topics = example_input
out = dict()
out["images"] = process_images(path)
out["depth"] = process_depth(path)
out["state"] = process_state(path)
out["actions"] = process_actions(path)
out["lang"] = process_lang(path)
# data collected prior to 7-23 has a delay of 1, otherwise a delay of 0
date_time = datetime.strptime(path.split("/")[-4], "%Y-%m-%d_%H-%M-%S")
latency_shift = date_time < datetime(2021, 7, 23)
# shift the actions according to camera latency
if latency_shift:
out["images"] = {k: v[1:] for k, v in out["images"].items()}
out["state"] = out["state"][1:]
out["actions"] = out["actions"][:-1]
if out["depth"] is not None:
out["depth"] = out["depth"][1:]
# append a null action to the end
out["actions"].append(np.zeros_like(out["actions"][0]))
assert len(out["actions"]) == len(out["state"]) == len(out["images"]["images0"])
# assemble episode
episode = []
episode_metadata = dict()
# map original image name to correct image name according to logged camera topics
orig_to_new = dict()
for image_idx in range(len(out["images"])):
orig_key = ORIG_NAMES[image_idx]
if camera_topics[image_idx] in [
"/cam0/image_raw",
"/camera0/color/image_raw",
"/D435/color/image_raw",
]:
# fixed cam should always be image_0
new_key = "image_0"
# assert new_key[-1] == orig_key[-1], episode_path
elif camera_topics[image_idx] == "/wrist/image_raw":
# wrist cam should always be image_3
new_key = "image_3"
elif camera_topics[image_idx] in [
"/cam1/image_raw",
"/cam2/image_raw",
"/cam3/image_raw",
"/cam4/image_raw",
"/camera1/color/image_raw",
"/camera3/color/image_raw",
"/camera2/color/image_raw",
"/camera4/color/image_raw",
"/blue/image_raw",
"/yellow/image_raw",
]:
# other cams can be either image_1 or image_2
if "image_1" in list(orig_to_new.values()):
new_key = "image_2"
else:
new_key = "image_1"
else:
raise ValueError(f"Unexpected camera topic {camera_topics[image_idx]}")
orig_to_new[orig_key] = new_key
episode_metadata[f"has_{new_key}"] = True
# record which images are missing
missing_keys = set(NEW_NAMES) - set(orig_to_new.values())
for missing in missing_keys:
episode_metadata[f"has_{missing}"] = False
episode_metadata["has_depth_0"] = out["depth"] is not None
instruction = out["lang"]
for i in range(len(out["actions"])):
observation = {
"state": out["state"][i].astype(np.float32),
}
for orig_key in out["images"]:
new_key = orig_to_new[orig_key]
observation[new_key] = out["images"][orig_key][i]
for missing in missing_keys:
observation[missing] = np.zeros(IMAGE_SIZE + (3,), dtype=np.uint8)
if episode_metadata["has_depth_0"]:
observation["depth_0"] = out["depth"][i]
else:
observation["depth_0"] = np.zeros(IMAGE_SIZE + (1,), dtype=np.uint16)
episode.append(
{
"observation": observation,
"action": out["actions"][i].astype(np.float32),
"is_first": i == 0,
"is_last": i == (len(out["actions"]) - 1),
"language_instruction": instruction,
}
)
episode_metadata["file_path"] = path
episode_metadata["has_language"] = bool(instruction)
# create output data sample
sample = {"steps": episode, "episode_metadata": episode_metadata}
# use episode path as key
return path, sample
def _split_generators(self, dl_manager: tfds.download.DownloadManager):
# each path is a directory that contains dated directories
paths = glob.glob(os.path.join(dl_manager.manual_dir, *("*" * (DEPTH - 1))))
train_inputs, val_inputs = [], []
for path in paths:
for dated_folder in os.listdir(path):
# a mystery left by the greats of the past
if "lmdb" in dated_folder:
continue
search_path = os.path.join(
path, dated_folder, "raw", "traj_group*", "traj*"
)
all_traj = glob.glob(search_path)
if not all_traj:
print(f"no trajs found in {search_path}")
continue
config_path = os.path.join(path, dated_folder, "config.json")
if os.path.exists(config_path):
with open(config_path, "rb") as f:
config = json.load(f)
camera_topics = config["agent"]["env"][1]["camera_topics"]
else:
# assumed camera topics if no config.json exists
camera_topics = [
"/D435/color/image_raw",
"/blue/image_raw",
"/yellow/image_raw",
"/wrist/image_raw",
]
all_inputs = [(t, camera_topics) for t in all_traj]
train_inputs += all_inputs[: int(len(all_inputs) * TRAIN_PROPORTION)]
val_inputs += all_inputs[int(len(all_inputs) * TRAIN_PROPORTION) :]
logging.info(
"Converting %d training and %d validation files.",
len(train_inputs),
len(val_inputs),
)
return {
"train": iter(train_inputs),
"val": iter(val_inputs),
}
"""Inspired by https://github.com/kpertsch/bridge_rlds_builder/blob/f0d16c5a8384c1476aa1c274a9aef3a5f76cbada/bridge_dataset/conversion_utils.py"""
import abc
import itertools
import multiprocessing as mp
from typing import Any, Callable, Dict, Iterable, Tuple, Union
import tensorflow_datasets as tfds
from absl import logging
from tensorflow_datasets.core import (
dataset_builder,
download,
example_serializer,
file_adapters,
naming,
)
from tensorflow_datasets.core import split_builder as split_builder_lib
from tensorflow_datasets.core import splits as splits_lib
from tensorflow_datasets.core import writer as writer_lib
from tqdm import tqdm
Key = Union[str, int]
Example = Dict[str, Any]
ExampleInput = Any
class MultiThreadedSplitBuilder(split_builder_lib.SplitBuilder):
"""Multithreaded version of tfds.core.SplitBuilder. Removes Apache Beam support, only supporting Python generators."""
def __init__(
self,
process_fn: Callable[[ExampleInput], Example],
num_workers: int,
chunksize: int,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
self._process_fn = process_fn
self.num_workers = num_workers
self.chunksize = chunksize
def submit_split_generation(
self,
split_name: splits_lib.Split,
generator: Iterable[Tuple[Key, ExampleInput]],
filename_template: naming.ShardedFileTemplate,
disable_shuffling: bool = False,
) -> splits_lib.SplitInfo:
if self._max_examples_per_split is not None:
logging.warning(
"Splits capped at %s examples max.", self._max_examples_per_split
)
generator = itertools.islice(generator, self._max_examples_per_split)
total_num_examples = self._max_examples_per_split
else:
# If dataset info has been pre-downloaded from the internet,
# we can use the pre-computed number of example for the progression bar.
split_info = self._split_dict.get(split_name)
if split_info and split_info.num_examples:
total_num_examples = split_info.num_examples
else:
total_num_examples = None
serialized_info = self._features.get_serialized_info()
writer = writer_lib.Writer(
serializer=example_serializer.ExampleSerializer(serialized_info),
filename_template=filename_template,
hash_salt=split_name,
disable_shuffling=disable_shuffling,
file_format=self._file_format,
shard_config=self._shard_config,
)
pbar = tqdm(
total=total_num_examples,
desc=f"Generating {split_name} examples...",
unit=" examples",
dynamic_ncols=True,
miniters=1,
)
with mp.Pool(
self.num_workers,
initializer=MultiThreadedSplitBuilder._worker_init,
initargs=(self._process_fn, self._features),
) as pool:
logging.info(
"Using %d workers with chunksize %d.", self.num_workers, self.chunksize
)
while True:
curr = pbar.n
iterator = itertools.islice(generator, self.chunksize)
results = pool.map(MultiThreadedSplitBuilder._worker_fn, iterator)
for key, example in results:
writer._shuffler.add(key, example)
writer._num_examples += 1
pbar.update(1)
if pbar.n == curr:
break
shard_lengths, total_size = writer.finalize()
return splits_lib.SplitInfo(
name=split_name,
shard_lengths=shard_lengths,
num_bytes=total_size,
filename_template=filename_template,
)
@staticmethod
def _worker_init(
process_fn: Callable[[ExampleInput], Example],
features: tfds.features.FeaturesDict,
):
global __process_fn
global __features
global __serializer
__process_fn = process_fn
__features = features
__serializer = example_serializer.ExampleSerializer(
features.get_serialized_info()
)
@staticmethod
def _worker_fn(example_input):
global __process_fn
global __features
global __serializer
key, example = __process_fn(example_input)
return key, __serializer.serialize_example(__features.encode_example(example))
class MultiThreadedDatasetBuilder(tfds.core.GeneratorBasedBuilder):
"""Multithreaded version of tfds.core.GeneratorBasedBuilder."""
# Defaults can be overridden by subclasses.
NUM_WORKERS = 16 # number of parallel workers
CHUNKSIZE = 1000 # number of examples to process in memory before writing to disk
@classmethod
@abc.abstractmethod
def _process_example(cls, example_input: ExampleInput) -> Example:
"""Process a single example.
This is the function that will be parallelized, so it should contain any heavy computation and I/O. It
should return a feature dictionary compatible with `self.info.features` (see the FeatureConnector
documenation) that is ready to be encoded and serialized.
"""
raise NotImplementedError()
@abc.abstractmethod
def _split_generators(
self,
dl_manager: download.DownloadManager,
) -> Dict[splits_lib.Split, Iterable[Tuple[Key, ExampleInput]]]:
"""Same as GeneratorBasedBuilder._split_generators, but returns generators of tuples (key,
example_input) rather than (key, example). `example_input` will be passed to
`_process_example` for further processing.
"""
raise NotImplementedError()
def _generate_examples(self, *args, **kwargs):
"""This is not actually called from TFDS code. I believe they left it in for legacy reasons. However,
it must be overridden for TFDS to recognize the class as a valid dataset builder.
"""
raise RuntimeError()
def _download_and_prepare(
self,
dl_manager: download.DownloadManager,
download_config: download.DownloadConfig,
) -> None:
"""Same as superclass `_download_and_prepare`, but removes Apache Beam stuff and uses
MultiThreadedSplitBuilder instead of SplitBuilder.
"""
split_builder = MultiThreadedSplitBuilder(
process_fn=type(self)._process_example,
num_workers=self.NUM_WORKERS,
chunksize=self.CHUNKSIZE,
split_dict=self.info.splits,
features=self.info.features,
dataset_size=self.info.dataset_size,
max_examples_per_split=download_config.max_examples_per_split,
beam_options=download_config.beam_options,
beam_runner=download_config.beam_runner,
file_format=self.info.file_format,
shard_config=download_config.get_shard_config(),
)
split_generators = self._split_generators(dl_manager)
dataset_builder._check_split_names(split_generators.keys())
# Writer fail if the number of example yield is `0`, so we return here.
if download_config.max_examples_per_split == 0:
return
# Start generating data for all splits
path_suffix = file_adapters.ADAPTER_FOR_FORMAT[
self.info.file_format
].FILE_SUFFIX
split_infos = []
for split_name, generator in split_generators.items():
filename_template = naming.ShardedFileTemplate(
split=split_name,
dataset_name=self.name,
data_dir=self.data_path,
filetype_suffix=path_suffix,
)
split_info = split_builder.submit_split_generation(
split_name=split_name,
generator=generator,
filename_template=filename_template,
disable_shuffling=self.info.disable_shuffling,
)
split_infos.append(split_info)
# Update the info object with the splits.
split_dict = splits_lib.SplitDict(split_infos)
self.info.set_splits(split_dict)
from setuptools import setup
setup(
name="dlimp-dataset-builder",
python_requires=">=3.10",
install_requires=[
"tensorflow_datasets>=4.9.2",
"tensorflow",
],
)
from setuptools import find_packages, setup
setup(
name="dlimp",
version="0.0.1",
packages=find_packages(),
python_requires=">=3.8",
install_requires=[
"tensorflow",
"tensorflow_datasets>=4.9.2",
],
extras_require={
"convert": [
"tqdm",
"tqdm-multiprocess==0.0.11",
],
"dev": [
"pre-commit==3.3.3",
],
},
)
FROM image.sourcefind.cn:5000/dcu/admin/base/pytorch:2.4.1-ubuntu22.04-dtk25.04-py3.10-fixpy
ENV DEBIAN_FRONTEND=noninteractive
# RUN yum update && yum install -y git cmake wget build-essential
# RUN source /opt/dtk-dtk25.04/env.sh
# # 安装pip相关依赖
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
docker run -it --shm-size=64G -v $PWD/Magma:/home/Magma -v /public/DL_DATA/AI:/home/AI -v /opt/hyhal:/opt/hyhal:ro --privileged=true --device=/dev/kfd --device=/dev/dri/ --group-add video --name magma e77c15729879 bash
# python -m torch.utils.collect_env
# Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
This Code of Conduct also applies outside the project spaces when there is a
reasonable belief that an individual's behavior may have a negative impact on
the project or its community.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at <opensource-conduct@fb.com>. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
\ No newline at end of file
# CoTracker
We want to make contributing to this project as easy and transparent as possible.
## Pull Requests
We actively welcome your pull requests.
1. Fork the repo and create your branch from `main`.
2. If you've changed APIs, update the documentation.
3. Make sure your code lints.
4. If you haven't already, complete the Contributor License Agreement ("CLA").
## Contributor License Agreement ("CLA")
In order to accept your pull request, we need you to submit a CLA. You only need
to do this once to work on any of Meta's open source projects.
Complete your CLA here: <https://code.facebook.com/cla>
## Issues
We use GitHub issues to track public bugs. Please ensure your description is
clear and has sufficient instructions to be able to reproduce the issue.
Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe
disclosure of security bugs. In those cases, please go through the process
outlined on that page and do not file a public issue.
## License
By contributing to CoTracker, you agree that your contributions will be licensed
under the LICENSE file in the root directory of this source tree.
\ No newline at end of file
Attribution-NonCommercial 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More_considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
j. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
k. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
l. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
\ No newline at end of file
# CoTracker3: Simpler and Better Point Tracking by Pseudo-Labelling Real Videos
**[Meta AI Research, GenAI](https://ai.facebook.com/research/)**; **[University of Oxford, VGG](https://www.robots.ox.ac.uk/~vgg/)**
[Nikita Karaev](https://nikitakaraevv.github.io/), [Iurii Makarov](https://linkedin.com/in/lvoursl), [Jianyuan Wang](https://jytime.github.io/), [Ignacio Rocco](https://www.irocco.info/), [Benjamin Graham](https://ai.facebook.com/people/benjamin-graham/), [Natalia Neverova](https://nneverova.github.io/), [Andrea Vedaldi](https://www.robots.ox.ac.uk/~vedaldi/), [Christian Rupprecht](https://chrirupp.github.io/)
### [Project Page](https://cotracker3.github.io/) | [Paper #1](https://arxiv.org/abs/2307.07635) | [Paper #2](https://arxiv.org/abs/2410.11831) | [X Thread](https://twitter.com/n_karaev/status/1742638906355470772) | [BibTeX](#citing-cotracker)
<a target="_blank" href="https://colab.research.google.com/github/facebookresearch/co-tracker/blob/main/notebooks/demo.ipynb">
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
</a>
<a href="https://huggingface.co/spaces/facebook/cotracker">
<img alt="Spaces" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue">
</a>
<img width="1100" src="./assets/teaser.png" />
**CoTracker** is a fast transformer-based model that can track any point in a video. It brings to tracking some of the benefits of Optical Flow.
CoTracker can track:
- **Any pixel** in a video
- A **quasi-dense** set of pixels together
- Points can be manually selected or sampled on a grid in any video frame
Try these tracking modes for yourself with our [Colab demo](https://colab.research.google.com/github/facebookresearch/co-tracker/blob/master/notebooks/demo.ipynb) or in the [Hugging Face Space 🤗](https://huggingface.co/spaces/facebook/cotracker).
**Updates:**
- [January 21, 2025] 📦 Kubric Dataset used for CoTracker3 now available! This dataset contains **6,000 high-resolution sequences** (512×512px, 120 frames) with slight camera motion, rendered using the Kubric engine. Check it out on [Hugging Face Dataset](https://huggingface.co/datasets/facebook/CoTracker3_Kubric).
- [October 15, 2024] 📣 We're releasing CoTracker3! State-of-the-art point tracking with a lightweight architecture trained with 1000x less data than previous top-performing models. Code for baseline models and the pseudo-labeling pipeline are available in the repo, as well as model checkpoints. Check out our [paper](https://arxiv.org/abs/2410.11831) for more details.
- [September 25, 2024] CoTracker2.1 is now available! This model has better performance on TAP-Vid benchmarks and follows the architecture of the original CoTracker. Try it out!
- [June 14, 2024] We have released the code for [VGGSfM](https://github.com/facebookresearch/vggsfm), a model for recovering camera poses and 3D structure from any image sequences based on point tracking! VGGSfM is the first fully differentiable SfM framework that unlocks scalability and outperforms conventional SfM methods on standard benchmarks.
- [December 27, 2023] CoTracker2 is now available! It can now track many more (up to **265*265**!) points jointly and it has a cleaner and more memory-efficient implementation. It also supports online processing. See the [updated paper](https://arxiv.org/abs/2307.07635) for more details. The old version remains available [here](https://github.com/facebookresearch/co-tracker/tree/8d364031971f6b3efec945dd15c468a183e58212).
- [September 5, 2023] You can now run our Gradio demo [locally](./gradio_demo/app.py).
## Quick start
The easiest way to use CoTracker is to load a pretrained model from `torch.hub`:
### Offline mode:
```pip install imageio[ffmpeg]```, then:
```python
import torch
# Download the video
url = 'https://github.com/facebookresearch/co-tracker/raw/refs/heads/main/assets/apple.mp4'
import imageio.v3 as iio
frames = iio.imread(url, plugin="FFMPEG") # plugin="pyav"
device = 'cuda'
grid_size = 10
video = torch.tensor(frames).permute(0, 3, 1, 2)[None].float().to(device) # B T C H W
# Run Offline CoTracker:
cotracker = torch.hub.load("facebookresearch/co-tracker", "cotracker3_offline").to(device)
pred_tracks, pred_visibility = cotracker(video, grid_size=grid_size) # B T N 2, B T N 1
```
### Online mode:
```python
cotracker = torch.hub.load("facebookresearch/co-tracker", "cotracker3_online").to(device)
# Run Online CoTracker, the same model with a different API:
# Initialize online processing
cotracker(video_chunk=video, is_first_step=True, grid_size=grid_size)
# Process the video
for ind in range(0, video.shape[1] - cotracker.step, cotracker.step):
pred_tracks, pred_visibility = cotracker(
video_chunk=video[:, ind : ind + cotracker.step * 2]
) # B T N 2, B T N 1
```
Online processing is more memory-efficient and allows for the processing of longer videos. However, in the example provided above, the video length is known! See [the online demo](./online_demo.py) for an example of tracking from an online stream with an unknown video length.
### Visualize predicted tracks:
After [installing](#installation-instructions) CoTracker, you can visualize tracks with:
```python
from cotracker.utils.visualizer import Visualizer
vis = Visualizer(save_dir="./saved_videos", pad_value=120, linewidth=3)
vis.visualize(video, pred_tracks, pred_visibility)
```
We offer a number of other ways to interact with CoTracker:
1. Interactive Gradio demo:
- A demo is available in the [`facebook/cotracker` Hugging Face Space 🤗](https://huggingface.co/spaces/facebook/cotracker).
- You can use the gradio demo locally by running [`python -m gradio_demo.app`](./gradio_demo/app.py) after installing the required packages: `pip install -r gradio_demo/requirements.txt`.
2. Jupyter notebook:
- You can run the notebook in
[Google Colab](https://colab.research.google.com/github/facebookresearch/co-tracker/blob/master/notebooks/demo.ipynb).
- Or explore the notebook located at [`notebooks/demo.ipynb`](./notebooks/demo.ipynb).
2. You can [install](#installation-instructions) CoTracker _locally_ and then:
- Run an *offline* demo with 10 ⨉ 10 points sampled on a grid on the first frame of a video (results will be saved to `./saved_videos/demo.mp4`)):
```bash
python demo.py --grid_size 10
```
- Run an *online* demo:
```bash
python online_demo.py
```
A GPU is strongly recommended for using CoTracker locally.
<img width="500" src="./assets/bmx-bumps.gif" />
## Installation Instructions
You can use a Pretrained Model via PyTorch Hub, as described above, or install CoTracker from this GitHub repo.
This is the best way if you need to run our local demo or evaluate/train CoTracker.
Ensure you have both _PyTorch_ and _TorchVision_ installed on your system. Follow the instructions [here](https://pytorch.org/get-started/locally/) for the installation.
We strongly recommend installing both PyTorch and TorchVision with CUDA support, although for small tasks CoTracker can be run on CPU.
### Install a Development Version
```bash
git clone https://github.com/facebookresearch/co-tracker
cd co-tracker
pip install -e .
pip install matplotlib flow_vis tqdm tensorboard
```
You can manually download all CoTracker3 checkpoints (baseline and scaled models, as well as single and sliding window architectures) from the links below and place them in the `checkpoints` folder as follows:
```bash
mkdir -p checkpoints
cd checkpoints
# download the online (multi window) model
wget https://huggingface.co/facebook/cotracker3/resolve/main/scaled_online.pth
# download the offline (single window) model
wget https://huggingface.co/facebook/cotracker3/resolve/main/scaled_offline.pth
cd ..
```
You can also download CoTracker3 checkpoints trained only on Kubric:
```bash
# download the online (sliding window) model
wget https://huggingface.co/facebook/cotracker3/resolve/main/baseline_online.pth
# download the offline (single window) model
wget https://huggingface.co/facebook/cotracker3/resolve/main/baseline_offline.pth
```
For old checkpoints, see [this section](#previous-version).
## Evaluation
To reproduce the results presented in the paper, download the following datasets:
- [TAP-Vid](https://github.com/deepmind/tapnet)
- [Dynamic Replica](https://dynamic-stereo.github.io/)
And install the necessary dependencies:
```bash
pip install hydra-core==1.1.0 mediapy
```
Then, execute the following command to evaluate the online model on TAP-Vid DAVIS:
```bash
python ./cotracker/evaluation/evaluate.py --config-name eval_tapvid_davis_first exp_dir=./eval_outputs dataset_root=your/tapvid/path
```
And the offline model:
```bash
python ./cotracker/evaluation/evaluate.py --config-name eval_tapvid_davis_first exp_dir=./eval_outputs dataset_root=/fsx-repligen/shared/datasets/tapvid offline_model=True window_len=60 checkpoint=./checkpoints/scaled_offline.pth
```
We run evaluations jointly on all the target points at a time for faster inference. With such evaluations, the numbers are similar to those presented in the paper. If you want to reproduce the exact numbers from the paper, add the flag `single_point=True`.
These are the numbers that you should be able to reproduce using the released checkpoint and the current version of the codebase:
| | Kinetics, $\delta_\text{avg}^\text{vis}$ | DAVIS, $\delta_\text{avg}^\text{vis}$ | RoboTAP, $\delta_\text{avg}^\text{vis}$ | RGB-S, $\delta_\text{avg}^\text{vis}$|
| :---: |:---: | :---: | :---: | :---: |
| CoTracker2, 27.12.23 | 61.8 | 74.6 | 69.6 | 73.4 |
| CoTracker2.1, 25.09.24 | 63 | 76.1 | 70.6 | 79.6 |
| CoTracker3 offline, 15.10.24 | 67.8 | **76.9** | 78.0 | **85.0** |
| CoTracker3 online, 15.10.24 | **68.3** | 76.7 | **78.8** | 82.7 |
## Training
### Baseline
To train the CoTracker as described in our paper, you first need to generate annotations for [Google Kubric](https://github.com/google-research/kubric) MOVI-f dataset.
Instructions for annotation generation can be found [here](https://github.com/deepmind/tapnet).
You can also find a discussion on dataset generation in [this issue](https://github.com/facebookresearch/co-tracker/issues/8).
Once you have the annotated dataset, you need to make sure you followed the steps for evaluation setup and install the training dependencies:
```bash
pip install pip==24.0
pip install pytorch_lightning==1.6.0 tensorboard opencv-python
```
Now you can launch training on Kubric.
Our model was trained for 50000 iterations on 32 GPUs (4 nodes with 8 GPUs).
Modify _dataset_root_ and _ckpt_path_ accordingly before running this command. For training on 4 nodes, add `--num_nodes 4`.
Here is an example of how to launch training of the online model on Kubric:
```bash
python train_on_kubric.py --batch_size 1 --num_steps 50000 \
--ckpt_path ./ --model_name cotracker_three --save_freq 200 --sequence_len 64 \
--eval_datasets tapvid_davis_first tapvid_stacking --traj_per_sample 384 \
--sliding_window_len 16 --train_datasets kubric --save_every_n_epoch 5 \
--evaluate_every_n_epoch 5 --model_stride 4 --dataset_root ${path_to_your_dataset} \
--num_nodes 4 --num_virtual_tracks 64 --mixed_precision --corr_radius 3 \
--wdecay 0.0005 --linear_layer_for_vis_conf --validate_at_start --add_huber_loss
```
Training the offline model on Kubric:
```bash
python train_on_kubric.py --batch_size 1 --num_steps 50000 \
--ckpt_path ./ --model_name cotracker_three --save_freq 200 --sequence_len 60 \
--eval_datasets tapvid_davis_first tapvid_stacking --traj_per_sample 512 \
--sliding_window_len 60 --train_datasets kubric --save_every_n_epoch 5 \
--evaluate_every_n_epoch 5 --model_stride 4 --dataset_root ${path_to_your_dataset} \
--num_nodes 4 --num_virtual_tracks 64 --mixed_precision --offline_model \
--random_frame_rate --query_sampling_method random --corr_radius 3 \
--wdecay 0.0005 --random_seq_len --linear_layer_for_vis_conf \
--validate_at_start --add_huber_loss
```
### Fine-tuning with pseudo labels
In order to launch training with pseudo-labelling, you need to collect your own dataset of real videos. There is a sample class available in [`cotracker/datasets/real_dataset.py`](./cotracker/datasets/real_dataset.py) with keyword-based filtering that we used for training. Your class should implement loading a video and storing it in the `CoTrackerData` class as a field, while pseudo labels will be generated in `train_on_real_data.py`.
You should have an existing Kubric-trained model for fine-tuning with pseudo labels. Here is an example of how you can launch fine-tuning of the online model:
```bash
python ./train_on_real_data.py --batch_size 1 --num_steps 15000 \
--ckpt_path ./ --model_name cotracker_three --save_freq 200 --sequence_len 64 \
--eval_datasets tapvid_stacking tapvid_davis_first --traj_per_sample 384 \
--save_every_n_epoch 15 --evaluate_every_n_epoch 15 --model_stride 4 \
--dataset_root ${path_to_your_dataset} --num_nodes 4 --real_data_splits 0 \
--num_virtual_tracks 64 --mixed_precision --random_frame_rate \
--restore_ckpt ./checkpoints/baseline_online.pth \
--lr 0.00005 --real_data_filter_sift --validate_at_start \
--sliding_window_len 16 --limit_samples 15000
```
And the offline model:
```bash
python train_on_real_data.py --batch_size 1 --num_steps 15000 \
--ckpt_path ./ --model_name cotracker_three --save_freq 200 --sequence_len 80 \
--eval_datasets tapvid_stacking tapvid_davis_first --traj_per_sample 384 --save_every_n_epoch 15 \
--evaluate_every_n_epoch 15 --model_stride 4 --dataset_root ${path_to_your_dataset} \
--num_nodes 4 --real_data_splits 0 --num_virtual_tracks 64 --mixed_precision \
--random_frame_rate --restore_ckpt ./checkpoints/baseline_offline.pth --lr 0.00005 \
--real_data_filter_sift --validate_at_start --offline_model --limit_samples 15000
```
## Development
### Building the documentation
To build CoTracker documentation, first install the dependencies:
```bash
pip install sphinx
pip install sphinxcontrib-bibtex
```
Then you can use this command to generate the documentation in the `docs/_build/html` folder:
```bash
make -C docs html
```
## Previous versions
### CoTracker v2
You could use CoTracker v2 with torch.hub in both offline and online modes.
#### Offline mode:
```pip install imageio[ffmpeg]```, then:
```python
import torch
# Download the video
url = 'https://github.com/facebookresearch/co-tracker/blob/main/assets/apple.mp4'
import imageio.v3 as iio
frames = iio.imread(url, plugin="FFMPEG") # plugin="pyav"
device = 'cuda'
grid_size = 10
video = torch.tensor(frames).permute(0, 3, 1, 2)[None].float().to(device) # B T C H W
# Run Offline CoTracker:
cotracker = torch.hub.load("facebookresearch/co-tracker", "cotracker2").to(device)
pred_tracks, pred_visibility = cotracker(video, grid_size=grid_size) # B T N 2, B T N 1
```
#### Online mode:
```python
cotracker = torch.hub.load("facebookresearch/co-tracker", "cotracker2_online").to(device)
# Run Online CoTracker, the same model with a different API:
# Initialize online processing
cotracker(video_chunk=video, is_first_step=True, grid_size=grid_size)
# Process the video
for ind in range(0, video.shape[1] - cotracker.step, cotracker.step):
pred_tracks, pred_visibility = cotracker(
video_chunk=video[:, ind : ind + cotracker.step * 2]
) # B T N 2, B T N 1
```
Checkpoint for v2 could be downloaded with the following command:
```bash
wget https://huggingface.co/facebook/cotracker/resolve/main/cotracker2.pth
```
### CoTracker v1
It is directly available via pytorch hub:
```python
import torch
import einops
import timm
import tqdm
cotracker = torch.hub.load("facebookresearch/co-tracker:v1.0", "cotracker_w8")
```
The old version of the code is available [here](https://github.com/facebookresearch/co-tracker/tree/8d364031971f6b3efec945dd15c468a183e58212).
You can also download the corresponding checkpoints:
```bash
wget https://dl.fbaipublicfiles.com/cotracker/cotracker_stride_4_wind_8.pth
wget https://dl.fbaipublicfiles.com/cotracker/cotracker_stride_4_wind_12.pth
wget https://dl.fbaipublicfiles.com/cotracker/cotracker_stride_8_wind_16.pth
```
## License
The majority of CoTracker is licensed under CC-BY-NC, however portions of the project are available under separate license terms: Particle Video Revisited is licensed under the MIT license, TAP-Vid and LocoTrack are licensed under the Apache 2.0 license.
## Acknowledgments
We would like to thank [PIPs](https://github.com/aharley/pips), [TAP-Vid](https://github.com/deepmind/tapnet), [LocoTrack](https://github.com/cvlab-kaist/locotrack) for publicly releasing their code and data. We also want to thank [Luke Melas-Kyriazi](https://lukemelas.github.io/) for proofreading the paper, [Jianyuan Wang](https://jytime.github.io/), [Roman Shapovalov](https://shapovalov.ro/) and [Adam W. Harley](https://adamharley.com/) for the insightful discussions.
## Citing CoTracker
If you find our repository useful, please consider giving it a star ⭐ and citing our research papers in your work:
```bibtex
@inproceedings{karaev23cotracker,
title = {CoTracker: It is Better to Track Together},
author = {Nikita Karaev and Ignacio Rocco and Benjamin Graham and Natalia Neverova and Andrea Vedaldi and Christian Rupprecht},
booktitle = {Proc. {ECCV}},
year = {2024}
}
```
```bibtex
@inproceedings{karaev24cotracker3,
title = {CoTracker3: Simpler and Better Point Tracking by Pseudo-Labelling Real Videos},
author = {Nikita Karaev and Iurii Makarov and Jianyuan Wang and Natalia Neverova and Andrea Vedaldi and Christian Rupprecht},
booktitle = {Proc. {arXiv:2410.11831}},
year = {2024}
}
```
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment