enable test_compute_stats

enable test_compute_stats
This commit is contained in:
Cadene 2024-04-10 17:10:46 +00:00
parent 4c3d8b061e
commit 9874652c2f
3 changed files with 83 additions and 40 deletions

View File

@ -1,10 +1,11 @@
import logging
import os import os
from pathlib import Path from pathlib import Path
import torch import torch
from torchvision.transforms import v2 from torchvision.transforms import v2
from lerobot.common.datasets.utils import compute_or_load_stats from lerobot.common.datasets.utils import compute_stats
from lerobot.common.transforms import NormalizeTransform, Prod from lerobot.common.transforms import NormalizeTransform, Prod
# DATA_DIR specifies to location where datasets are loaded. By default, DATA_DIR is None and # DATA_DIR specifies to location where datasets are loaded. By default, DATA_DIR is None and
@ -59,7 +60,15 @@ def make_dataset(
root=DATA_DIR, root=DATA_DIR,
transform=Prod(in_keys=clsfunc.image_keys, prod=1 / 255.0), transform=Prod(in_keys=clsfunc.image_keys, prod=1 / 255.0),
) )
stats = compute_or_load_stats(stats_dataset)
# load stats if the file exists already or compute stats and save it
precomputed_stats_path = stats_dataset.data_dir / "stats.pth"
if precomputed_stats_path.exists():
stats = torch.load(precomputed_stats_path)
else:
logging.info(f"compute_stats and save to {precomputed_stats_path}")
stats = compute_stats(stats_dataset)
torch.save(stats, stats_path)
else: else:
stats = torch.load(stats_path) stats = torch.load(stats_path)

View File

@ -1,5 +1,4 @@
import io import io
import logging
import zipfile import zipfile
from copy import deepcopy from copy import deepcopy
from math import ceil from math import ceil
@ -103,13 +102,18 @@ def load_data_with_delta_timestamps(
return data, is_pad return data, is_pad
def compute_or_load_stats(dataset, batch_size=32, max_num_samples=None): def get_stats_einops_patterns(dataset):
stats_path = dataset.data_dir / "stats.pth" """These einops patterns will be used to aggregate batches and compute statistics."""
if stats_path.exists(): stats_patterns = {
return torch.load(stats_path) "action": "b c -> c",
"observation.state": "b c -> c",
}
for key in dataset.image_keys:
stats_patterns[key] = "b c h w -> c 1 1"
return stats_patterns
logging.info(f"compute_stats and save to {stats_path}")
def compute_stats(dataset, batch_size=32, max_num_samples=None):
if max_num_samples is None: if max_num_samples is None:
max_num_samples = len(dataset) max_num_samples = len(dataset)
else: else:
@ -124,13 +128,8 @@ def compute_or_load_stats(dataset, batch_size=32, max_num_samples=None):
drop_last=False, drop_last=False,
) )
# these einops patterns will be used to aggregate batches and compute statistics # get einops patterns to aggregate batches and compute statistics
stats_patterns = { stats_patterns = get_stats_einops_patterns(dataset)
"action": "b c -> c",
"observation.state": "b c -> c",
}
for key in dataset.image_keys:
stats_patterns[key] = "b c h w -> c 1 1"
# mean and std will be computed incrementally while max and min will track the running value. # mean and std will be computed incrementally while max and min will track the running value.
mean, std, max, min = {}, {}, {}, {} mean, std, max, min = {}, {}, {}, {}
@ -201,7 +200,6 @@ def compute_or_load_stats(dataset, batch_size=32, max_num_samples=None):
"min": min[key], "min": min[key],
} }
torch.save(stats, stats_path)
return stats return stats

View File

@ -1,6 +1,12 @@
import os
from pathlib import Path
import einops
import pytest import pytest
import torch import torch
from lerobot.common.datasets.utils import compute_stats, get_stats_einops_patterns
from lerobot.common.datasets.xarm import XarmDataset
from lerobot.common.transforms import Prod
from lerobot.common.utils import init_hydra_config from lerobot.common.utils import init_hydra_config
import logging import logging
from lerobot.common.datasets.factory import make_dataset from lerobot.common.datasets.factory import make_dataset
@ -81,28 +87,58 @@ def test_factory(env_name, dataset_id, policy_name):
assert key in item, f"{key}" assert key in item, f"{key}"
# def test_compute_stats(): def test_compute_stats():
# """Check that the statistics are computed correctly according to the stats_patterns property. """Check that the statistics are computed correctly according to the stats_patterns property.
# We compare with taking a straight min, mean, max, std of all the data in one pass (which we can do We compare with taking a straight min, mean, max, std of all the data in one pass (which we can do
# because we are working with a small dataset). because we are working with a small dataset).
# """ """
# cfg = init_hydra_config( DATA_DIR = Path(os.environ["DATA_DIR"]) if "DATA_DIR" in os.environ else None
# DEFAULT_CONFIG_PATH, overrides=["env=aloha", "env.task=sim_transfer_cube_human"]
# ) # get transform to convert images from uint8 [0,255] to float32 [0,1]
# dataset = make_dataset(cfg) transform = Prod(in_keys=XarmDataset.image_keys, prod=1 / 255.0)
# # Get all of the data.
# all_data = dataset.data_dict dataset = XarmDataset(
# # Note: we set the batch size to be smaller than the whole dataset to make sure we are testing batched dataset_id="xarm_lift_medium",
# # computation of the statistics. While doing this, we also make sure it works when we don't divide the root=DATA_DIR,
# # dataset into even batches. transform=transform,
# computed_stats = buffer._compute_stats(batch_size=int(len(all_data) * 0.75)) )
# for k, pattern in buffer.stats_patterns.items():
# expected_mean = einops.reduce(all_data[k], pattern, "mean") # Note: we set the batch size to be smaller than the whole dataset to make sure we are testing batched
# assert torch.allclose(computed_stats[k]["mean"], expected_mean) # computation of the statistics. While doing this, we also make sure it works when we don't divide the
# assert torch.allclose( # dataset into even batches.
# computed_stats[k]["std"], computed_stats = compute_stats(dataset, batch_size=int(len(dataset) * 0.25))
# torch.sqrt(einops.reduce((all_data[k] - expected_mean) ** 2, pattern, "mean"))
# ) # get einops patterns to aggregate batches and compute statistics
# assert torch.allclose(computed_stats[k]["min"], einops.reduce(all_data[k], pattern, "min")) stats_patterns = get_stats_einops_patterns(dataset)
# assert torch.allclose(computed_stats[k]["max"], einops.reduce(all_data[k], pattern, "max"))
# get all frames from the dataset in the same dtype and range as during compute_stats
data_dict = transform(dataset.data_dict)
# compute stats based on all frames from the dataset without any batching
expected_stats = {}
for k, pattern in stats_patterns.items():
expected_stats[k] = {}
expected_stats[k]["mean"] = einops.reduce(data_dict[k], pattern, "mean")
expected_stats[k]["std"] = torch.sqrt(einops.reduce((data_dict[k] - expected_stats[k]["mean"]) ** 2, pattern, "mean"))
expected_stats[k]["min"] = einops.reduce(data_dict[k], pattern, "min")
expected_stats[k]["max"] = einops.reduce(data_dict[k], pattern, "max")
# test computed stats match expected stats
for k in stats_patterns:
assert torch.allclose(computed_stats[k]["mean"], expected_stats[k]["mean"])
assert torch.allclose(computed_stats[k]["std"], expected_stats[k]["std"])
assert torch.allclose(computed_stats[k]["min"], expected_stats[k]["min"])
assert torch.allclose(computed_stats[k]["max"], expected_stats[k]["max"])
# TODO(rcadene): check that the stats used for training are correct too
# # load stats that are expected to match the ones returned by computed_stats
# assert (dataset.data_dir / "stats.pth").exists()
# loaded_stats = torch.load(dataset.data_dir / "stats.pth")
# # test loaded stats match expected stats
# for k in stats_patterns:
# assert torch.allclose(loaded_stats[k]["mean"], expected_stats[k]["mean"])
# assert torch.allclose(loaded_stats[k]["std"], expected_stats[k]["std"])
# assert torch.allclose(loaded_stats[k]["min"], expected_stats[k]["min"])
# assert torch.allclose(loaded_stats[k]["max"], expected_stats[k]["max"])