Add files using upload-large-folder tool
Browse filesFiles changed (50)
- evals/action_anticipation_frozen/dataloader.pyAdded+236
- evals/action_anticipation_frozen/epickitchens.pyAdded+323
- evals/action_anticipation_frozen/eval.pyAdded+749
- evals/action_anticipation_frozen/losses.pyAdded+49
- evals/action_anticipation_frozen/metrics.pyAdded+58
- evals/action_anticipation_frozen/modelcustom/vit_encoder_predictor_concat_ar.pyAdded+188
- evals/action_anticipation_frozen/models.pyAdded+136
- evals/action_anticipation_frozen/utils.pyAdded+85
- evals/hub/__init__.pyAdded
- evals/hub/preprocessor.pyAdded+15
- evals/image_classification_frozen/eval.pyAdded+476
- evals/image_classification_frozen/modelcustom/vit_encoder.pyAdded+83
- evals/image_classification_frozen/models.pyAdded+44
- evals/main.pyAdded+112
- evals/main_distributed.pyAdded+230
- evals/scaffold.pyAdded+19
- evals/video_classification_frozen/eval.pyAdded+537
- evals/video_classification_frozen/modelcustom/vit_encoder_multiclip.pyAdded+149
- evals/video_classification_frozen/modelcustom/vit_encoder_multiclip_multilevel.pyAdded+155
- evals/video_classification_frozen/models.pyAdded+46
- evals/video_classification_frozen/utils.pyAdded+198
- make_module_static.ipynbAdded
- src/datasets/__pycache__/data_manager.cpython-310.pycAdded
- src/datasets/__pycache__/video_dataset.cpython-310.pycAdded
- src/datasets/imagenet1k.pyAdded+152
- src/datasets/utils/__pycache__/dataloader.cpython-310.pycAdded
- src/datasets/utils/__pycache__/weighted_sampler.cpython-310.pycAdded
- src/datasets/utils/dataloader.pyAdded+234
- src/datasets/utils/video/__pycache__/functional.cpython-310.pycAdded
- src/datasets/utils/video/__pycache__/randaugment.cpython-310.pycAdded
- src/datasets/utils/video/__pycache__/transforms.cpython-310.pycAdded
- src/datasets/utils/video/functional.pyAdded+110
- src/datasets/utils/video/randerase.pyAdded+170
- src/datasets/utils/video/transforms.pyAdded+1161
- src/datasets/utils/video/volume_transforms.pyAdded+159
- src/datasets/utils/weighted_sampler.pyAdded+336
- src/datasets/utils/worker_init_fn.pyAdded+76
- src/datasets/video_dataset.pyAdded+485
- src/masks/__pycache__/multiseq_multiblock3d.cpython-310.pycAdded
- src/masks/__pycache__/utils.cpython-310.pycAdded
- src/masks/multiseq_multiblock3d.pyAdded+282
- src/models/__pycache__/vision_transformer.cpython-310.pycAdded
- src/models/attentive_pooler.pyAdded+137
- src/models/utils/__pycache__/modules.cpython-310.pycAdded
- src/models/utils/patch_embed.pyAdded+52
- src/utils/__pycache__/distributed.cpython-310.pycAdded
- src/utils/__pycache__/monitoring.cpython-310.pycAdded
- src/utils/__pycache__/schedulers.cpython-310.pycAdded
- src/utils/__pycache__/tensors.cpython-310.pycAdded
- src/utils/__pycache__/wrappers.cpython-310.pycAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
from logging import getLogger
import torchimport torchvision.transforms as transforms
import src.datasets.utils.video.transforms as video_transformsimport src.datasets.utils.video.volume_transforms as volume_transformsfrom evals.action_anticipation_frozen.epickitchens import filter_annotations as ek100_filter_annotationsfrom evals.action_anticipation_frozen.epickitchens import make_webvid as ek100_make_webvidfrom src.datasets.utils.video.randerase import RandomErasing
_GLOBAL_SEED = 0logger = getLogger()
def init_data( base_path, annotations_path, batch_size, dataset, frames_per_clip=16, fps=5, crop_size=224, rank=0, world_size=1, drop_last=True, num_workers=10, pin_mem=True, persistent_workers=True, training=True, decode_video=True, anticipation_time_sec=0.0, decode_one_clip=False, random_resize_scale=(0.9, 1.0), reprob=0, auto_augment=False, motion_shift=False, anticipation_point=[0.1, 0.1],): # -- make video transformations transform = make_transforms( training=training, random_horizontal_flip=True, random_resize_aspect_ratio=(3 / 4, 4 / 3), random_resize_scale=random_resize_scale, reprob=reprob, auto_augment=auto_augment, motion_shift=motion_shift, crop_size=crop_size, )
make_webvid = None if "ek100" in dataset.lower(): make_webvid = ek100_make_webvid
dataset, data_loader, data_info = make_webvid( training=training, decode_one_clip=decode_one_clip, world_size=world_size, rank=rank, base_path=base_path, annotations_path=annotations_path, batch_size=batch_size, transform=transform, frames_per_clip=frames_per_clip, num_workers=num_workers, fps=fps, decode_video=decode_video, anticipation_time_sec=anticipation_time_sec, persistent_workers=persistent_workers, pin_memory=pin_mem, anticipation_point=anticipation_point, )
return dataset, data_loader, data_info
def filter_annotations( dataset, base_path, train_annotations_path, val_annotations_path, **kwargs,): _filter = None if "ek100" in dataset.lower(): _filter = ek100_filter_annotations
return _filter( base_path=base_path, train_annotations_path=train_annotations_path, val_annotations_path=val_annotations_path, **kwargs, )
def make_transforms( training=True, random_horizontal_flip=True, random_resize_aspect_ratio=(3 / 4, 4 / 3), random_resize_scale=(0.3, 1.0), reprob=0.0, auto_augment=False, motion_shift=False, crop_size=224, normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),):
transform = VideoTransform( training=training, random_horizontal_flip=random_horizontal_flip, random_resize_aspect_ratio=random_resize_aspect_ratio, random_resize_scale=random_resize_scale, reprob=reprob, auto_augment=auto_augment, motion_shift=motion_shift, crop_size=crop_size, normalize=normalize, )
return transform
class VideoTransform(object):
def __init__( self, training=True, random_horizontal_flip=True, random_resize_aspect_ratio=(3 / 4, 4 / 3), random_resize_scale=(0.3, 1.0), reprob=0.0, auto_augment=False, motion_shift=False, crop_size=224, normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ):
self.training = training
short_side_size = int(crop_size * 256 / 224) self.eval_transform = video_transforms.Compose( [ video_transforms.Resize(short_side_size, interpolation="bilinear"), video_transforms.CenterCrop(size=(crop_size, crop_size)), volume_transforms.ClipToTensor(), video_transforms.Normalize(mean=normalize[0], std=normalize[1]), ] )
self.random_horizontal_flip = random_horizontal_flip self.random_resize_aspect_ratio = random_resize_aspect_ratio self.random_resize_scale = random_resize_scale self.auto_augment = auto_augment self.motion_shift = motion_shift self.crop_size = crop_size self.normalize = torch.tensor(normalize)
self.autoaug_transform = video_transforms.create_random_augment( input_size=(crop_size, crop_size), auto_augment="rand-m7-n4-mstd0.5-inc1", interpolation="bicubic", )
self.spatial_transform = ( video_transforms.random_resized_crop_with_shift if motion_shift else video_transforms.random_resized_crop )
self.reprob = reprob self.erase_transform = RandomErasing( reprob, mode="pixel", max_count=1, num_splits=1, device="cpu", )
def __call__(self, buffer):
if not self.training: return self.eval_transform(buffer)
buffer = [transforms.ToPILImage()(frame) for frame in buffer]
if self.auto_augment: buffer = self.autoaug_transform(buffer)
buffer = [transforms.ToTensor()(img) for img in buffer] buffer = torch.stack(buffer) # T C H W buffer = buffer.permute(0, 2, 3, 1) # T H W C
buffer = tensor_normalize(buffer, self.normalize[0], self.normalize[1]) buffer = buffer.permute(3, 0, 1, 2) # T H W C -> C T H W
buffer = self.spatial_transform( images=buffer, target_height=self.crop_size, target_width=self.crop_size, scale=self.random_resize_scale, ratio=self.random_resize_aspect_ratio, ) if self.random_horizontal_flip: buffer, _ = video_transforms.horizontal_flip(0.5, buffer)
if self.reprob > 0: buffer = buffer.permute(1, 0, 2, 3) buffer = self.erase_transform(buffer) buffer = buffer.permute(1, 0, 2, 3)
return buffer
def tensor_normalize(tensor, mean, std): """ Normalize a given tensor by subtracting the mean and dividing the std. Args: tensor (tensor): tensor to normalize. mean (tensor or list): mean value to subtract. std (tensor or list): std to divide. """ if tensor.dtype == torch.uint8: tensor = tensor.float() tensor = tensor / 255.0 if isinstance(mean, list): mean = torch.tensor(mean) if isinstance(std, list): std = torch.tensor(std) tensor = tensor - mean tensor = tensor / std return tensor123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import loggingimport multiprocessingimport osimport randomfrom dataclasses import dataclassfrom itertools import islicefrom multiprocessing import Value
import numpy as npimport pandas as pdimport torchimport webdataset as wdsfrom decord import VideoReader, cpufrom torch.utils.data import DataLoader, IterableDatasetfrom torch.utils.data.distributed import DistributedSampler
from src.datasets.utils.worker_init_fn import pl_worker_init_function
multiprocessing.set_start_method("spawn", force=True)
class SharedEpoch: def __init__(self, epoch: int = 0): self.shared_epoch = Value("i", epoch)
def set_value(self, epoch): self.shared_epoch.value = epoch
def get_value(self): return self.shared_epoch.value
@dataclassclass DataInfo: dataloader: DataLoader sampler: DistributedSampler = None shared_epoch: SharedEpoch = None
def set_epoch(self, epoch): if self.shared_epoch is not None: self.shared_epoch.set_value(epoch) if self.sampler is not None and isinstance(self.sampler, DistributedSampler): self.sampler.set_epoch(epoch)
def get_dataset_size(shards_list): num_shards = len(shards_list) total_size = num_shards return total_size, num_shards
def log_and_continue(exn): """Call in an exception handler to ignore any exception, issue a warning, and continue.""" logging.warning(f"Handling webdataset error ({repr(exn)}). Ignoring.") return True
class split_by_node(wds.PipelineStage): """Node splitter that uses provided rank/world_size instead of from torch.distributed"""
def __init__( self, rank=0, world_size=1, ): self.rank = rank self.world_size = world_size
def run(self, src): if self.world_size > 1: yield from islice(src, self.rank, None, self.world_size) else: yield from src
class decode_videos_to_clips(wds.PipelineStage):
def __init__( self, annotations, frames_per_clip=16, fps=5, transform=None, anticipation_time_sec=[0.0, 0.0], anticipation_point=[0.25, 0.75], ): self.annotations = annotations self.frames_per_clip = frames_per_clip self.fps = fps self.transform = transform self.anticipation_time = anticipation_time_sec self.anticipation_point = anticipation_point
def run(self, src): for path in src: # -- get all action annotations for the video video_id = path.split("/")[-1].split(".")[0] ano = self.annotations[video_id]
# -- get action annotations and frame stamps start_frames = ano["start_frame"].values stop_frames = ano["stop_frame"].values
# -- load clips corresponding to action annotations try: vr = VideoReader(path, num_threads=-1, ctx=cpu(0)) vr.seek(0) # -- vfps = vr.get_avg_fps() fpc = self.frames_per_clip fstp = int(vfps / self.fps) nframes = int(fpc * fstp) except Exception as e: logging.info(f"Encountered exception loading video {e=}") continue
for i, (sf, ef) in enumerate(zip(start_frames, stop_frames)): labels_verb = int(ano["verb_class"].values[i]) labels_noun = int(ano["noun_class"].values[i])
# sample an anticipation time at = random.uniform(*self.anticipation_time) aframes = int(at * vfps)
# sample an anticipation frame b/w start and end of action ap = random.uniform(*self.anticipation_point) af = int(sf * ap + (1 - ap) * ef - aframes)
indices = np.arange(af - nframes, af, fstp).astype(np.int64) # If not enough frames in video for anticipation, just pad with # first frame indices[indices < 0] = 0
try: buffer = vr.get_batch(indices).asnumpy() except Exception as e: logging.info(f"Encountered exception getting indices {e=}") continue
if self.transform is not None: buffer = self.transform(buffer)
yield dict( video=buffer, verb=labels_verb, noun=labels_noun, anticipation_time=at, )
class ResampledShards(IterableDataset): """An iterable dataset yielding a list of urls."""
def __init__(self, urls, epoch, training): super().__init__() self.epoch = epoch self.training = training self.urls = np.array(urls) logging.info("Done initializing ResampledShards")
def __iter__(self): """Return an iterator over the shards.""" if self.training: epoch = self.epoch.get_value() gen = torch.Generator() gen.manual_seed(epoch) yield from self.urls[torch.randperm(len(self.urls), generator=gen)] else: yield from self.urls[torch.arange(len(self.urls))]
def get_video_wds_dataset( batch_size, input_shards, video_decoder, training, epoch=0, world_size=1, rank=0, num_workers=1, persistent_workers=True, pin_memory=True,): assert input_shards is not None _, num_shards = get_dataset_size(input_shards) logging.info(f"Total number of shards across all data is {num_shards=}")
epoch = SharedEpoch(epoch=epoch) pipeline = [ ResampledShards(input_shards, epoch=epoch, training=training), split_by_node(rank=rank, world_size=world_size), wds.split_by_worker, video_decoder, wds.to_tuple("video", "verb", "noun", "anticipation_time"), wds.batched(batch_size, partial=True, collation_fn=torch.utils.data.default_collate), ] dataset = wds.DataPipeline(*pipeline)
dataloader = torch.utils.data.DataLoader( dataset, batch_size=None, shuffle=False, num_workers=num_workers, persistent_workers=(num_workers > 0) and persistent_workers, worker_init_fn=pl_worker_init_function, pin_memory=pin_memory, )
return dataset, DataInfo(dataloader=dataloader, shared_epoch=epoch)
def filter_annotations( base_path, train_annotations_path, val_annotations_path, file_format=1,):
tdf = pd.read_csv(train_annotations_path) vdf = pd.read_csv(val_annotations_path)
# 1. Remove actions in val that are not in train tactions = set([(v, n) for v, n in zip(tdf["verb_class"].values, tdf["noun_class"].values)]) tverbs = set([v for v, _ in tactions]) tnouns = set([n for _, n in tactions]) keep_inds = [(v, n) in tactions for v, n in zip(vdf["verb_class"].values, vdf["noun_class"].values)] vdf = vdf[keep_inds]
# 2. Determine new class labels verb_classes = {k: i for i, k in enumerate(tverbs)} noun_classes = {k: i for i, k in enumerate(tnouns)} action_classes = {k: i for i, k in enumerate(tactions)}
val_verb_classes = set([verb_classes[v] for v in vdf["verb_class"].values]) val_noun_classes = set([noun_classes[n] for n in vdf["noun_class"].values]) val_action_classes = set([action_classes[a] for a in zip(vdf["verb_class"].values, vdf["noun_class"].values)])
def build_annotations(df): video_paths, annotations = [], {} unique_videos = list(dict.fromkeys(df["video_id"].values)) for uv in unique_videos: pid = uv.split("_")[0] # There are two common file formats for storing EK if file_format == 0: # File format 0: $base_path/$participant_id/videos/$video_id.MP4 fpath = os.path.join(base_path, pid, "videos", uv + ".MP4") else: # File format 1: $base_path/$participant_id/$video_id.MP4 fpath = os.path.join(base_path, pid, uv + ".MP4") if not os.path.exists(fpath): logging.info(f"file path not found {fpath=}") continue video_paths += [fpath] annotations[uv] = df[df["video_id"] == uv].sort_values(by="start_frame") return video_paths, annotations
train_annotations = build_annotations(tdf) val_annotations = build_annotations(vdf)
return dict( verbs=verb_classes, nouns=noun_classes, actions=action_classes, val_verbs=val_verb_classes, val_nouns=val_noun_classes, val_actions=val_action_classes, train=train_annotations, val=val_annotations, )
def make_webvid( base_path, annotations_path, batch_size, transform, frames_per_clip=16, fps=5, num_workers=8, world_size=1, rank=0, anticipation_time_sec=[0.0, 0.0], persistent_workers=True, pin_memory=True, training=True, anticipation_point=[0.1, 0.1], **kwargs,):
paths, annotations = annotations_path num_clips = sum([len(a) for a in annotations.values()])
video_decoder = decode_videos_to_clips( annotations=annotations, frames_per_clip=frames_per_clip, fps=fps, transform=transform, anticipation_time_sec=anticipation_time_sec, anticipation_point=anticipation_point, )
dataset, datainfo = get_video_wds_dataset( batch_size=batch_size, input_shards=paths, epoch=0, world_size=world_size, rank=rank, num_workers=num_workers, video_decoder=video_decoder, persistent_workers=persistent_workers, pin_memory=pin_memory, training=training, )
datainfo.dataloader.num_batches = num_clips // (world_size * batch_size) datainfo.dataloader.num_samples = num_clips
return dataset, datainfo.dataloader, datainfo123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import os
# -- FOR DISTRIBUTED TRAINING ENSURE ONLY 1 DEVICE VISIBLE PER PROCESStry: # -- WARNING: IF DOING DISTRIBUTED TRAINING ON A NON-SLURM CLUSTER, MAKE # -- SURE TO UPDATE THIS TO GET LOCAL-RANK ON NODE, OR ENSURE # -- THAT YOUR JOBS ARE LAUNCHED WITH ONLY 1 DEVICE VISIBLE # -- TO EACH PROCESS os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["SLURM_LOCALID"]except Exception: pass
import loggingimport pprintimport randomimport time
import numpy as npimport torchimport torch.multiprocessing as mpfrom torch.nn.parallel import DistributedDataParallel
from evals.action_anticipation_frozen.dataloader import filter_annotations, init_datafrom evals.action_anticipation_frozen.losses import sigmoid_focal_lossfrom evals.action_anticipation_frozen.metrics import ClassMeanRecallfrom evals.action_anticipation_frozen.models import init_classifier, init_modulefrom evals.action_anticipation_frozen.utils import init_optfrom src.utils.checkpoint_loader import robust_checkpoint_loaderfrom src.utils.distributed import init_distributedfrom src.utils.logging import AverageMeter, CSVLogger
logging.basicConfig()logger = logging.getLogger()logger.setLevel(logging.INFO)
_GLOBAL_SEED = 0random.seed(_GLOBAL_SEED)np.random.seed(_GLOBAL_SEED)torch.manual_seed(_GLOBAL_SEED)torch.cuda.manual_seed(_GLOBAL_SEED)torch.backends.cudnn.benchmark = True
pp = pprint.PrettyPrinter(indent=4)
def main(args_eval, resume_preempt=False): # ----------------------------------------------------------------------- # # PASSED IN PARAMS FROM CONFIG FILE # ----------------------------------------------------------------------- #
# -- VAL ONLY val_only = args_eval.get("val_only", False) if val_only: logger.info("VAL ONLY")
# -- EXPERIMENT pretrain_folder = args_eval.get("folder", None) resume_checkpoint = args_eval.get("resume_checkpoint", False) or resume_preempt val_only = args_eval.get("val_only", False) eval_tag = args_eval.get("tag", None)
# -- PRETRAIN args_pretrain = args_eval.get("model_kwargs") checkpoint = args_pretrain.get("checkpoint") module_name = args_pretrain.get("module_name") args_model = args_pretrain.get("pretrain_kwargs") args_wrapper = args_pretrain.get("wrapper_kwargs")
args_exp = args_eval.get("experiment")
# -- CLASSIFIER args_classifier = args_exp.get("classifier") num_probe_blocks = args_classifier.get("num_probe_blocks", 1) num_heads = args_classifier.get("num_heads")
# -- DATA args_data = args_exp.get("data") dataset = args_data.get("dataset") # Name of dataset (e.g., "EK100") base_path = args_data.get("base_path") # Root directory containing videos file_format = args_data.get("file_format", 1) num_workers = args_data.get("num_workers", 12) pin_mem = args_data.get("pin_memory", True) # -- / frame sampling hyper-params frames_per_clip = args_data.get("frames_per_clip") frames_per_second = args_data.get("frames_per_second") resolution = args_data.get("resolution", 224) # -- / anticipation details train_anticipation_time_sec = args_data.get("train_anticipation_time_sec") train_anticipation_point = args_data.get("train_anticipation_point") val_anticipation_point = args_data.get("val_anticipation_point", [0.0, 0.0]) val_anticipation_time_sec = args_data.get("anticipation_time_sec") # -- / data augmentations auto_augment = args_data.get("auto_augment") motion_shift = args_data.get("motion_shift") reprob = args_data.get("reprob") random_resize_scale = args_data.get("random_resize_scale") # -- train_annotations_path = args_data.get("dataset_train") val_annotations_path = args_data.get("dataset_val") train_data_path = base_path # os.path.join(base_path, "train") val_data_path = base_path # os.path.join(base_path, "test")
# -- OPTIMIZATION args_opt = args_exp.get("optimization") batch_size = args_opt.get("batch_size") num_epochs = args_opt.get("num_epochs") use_bfloat16 = args_opt.get("use_bfloat16") use_focal_loss = args_opt.get("use_focal_loss", False) criterion = sigmoid_focal_loss if use_focal_loss else torch.nn.CrossEntropyLoss() opt_kwargs = [ dict( ref_wd=kwargs.get("weight_decay"), final_wd=kwargs.get("final_weight_decay"), start_lr=kwargs.get("start_lr"), ref_lr=kwargs.get("lr"), final_lr=kwargs.get("final_lr"), warmup=kwargs.get("warmup"), ) for kwargs in args_opt.get("multihead_kwargs") ]
# ----------------------------------------------------------------------- #
try: mp.set_start_method("spawn") except Exception: pass
if not torch.cuda.is_available(): device = torch.device("cpu") else: device = torch.device("cuda:0") torch.cuda.set_device(device)
world_size, rank = init_distributed() logger.info(f"Initialized (rank/world-size) {rank}/{world_size}")
# -- log/checkpointing paths folder = os.path.join(pretrain_folder, "action_anticipation_frozen/") if eval_tag is not None: folder = os.path.join(folder, eval_tag) if not os.path.exists(folder): os.makedirs(folder, exist_ok=True) log_file = os.path.join(folder, f"log_r{rank}.csv") latest_path = os.path.join(folder, "latest.pt")
action_is_verb_noun = True if dataset in ["COIN_anticipation"]: action_is_verb_noun = False
# -- make csv_logger if rank == 0: if action_is_verb_noun: csv_logger = CSVLogger( log_file, ("%d", "epoch"), ("%.5f", "train-acc"), ("%.5f", "train-acc-verb"), ("%.5f", "train-acc-noun"), ("%.5f", "train-recall"), ("%.5f", "train-recall-verb"), ("%.5f", "train-recall-noun"), ("%.5f", "val-acc"), ("%.5f", "val-acc-verb"), ("%.5f", "val-acc-noun"), ("%.5f", "val-recall"), ("%.5f", "val-recall-verb"), ("%.5f", "val-recall-noun"), ) else: csv_logger = CSVLogger( log_file, ("%d", "epoch"), ("%.5f", "train-acc"), ("%.5f", "train-recall"), ("%.5f", "val-acc"), ("%.5f", "val-recall"), )
# -- process annotations to unify action class labels between train/val _annotations = filter_annotations( dataset, base_path, train_annotations_path, val_annotations_path, file_format=file_format, ) action_classes = _annotations["actions"] verb_classes = {} noun_classes = {} if action_is_verb_noun: verb_classes = _annotations["verbs"] noun_classes = _annotations["nouns"] # -- val_actions = _annotations["val_actions"] val_verbs = {} val_nouns = {} if action_is_verb_noun: val_verbs = _annotations["val_verbs"] val_nouns = _annotations["val_nouns"] # -- train_annotations = _annotations["train"] val_annotations = _annotations["val"]
# -- init models model = init_module( module_name=module_name, frames_per_clip=frames_per_clip, frames_per_second=frames_per_second, resolution=resolution, checkpoint=checkpoint, model_kwargs=args_model, wrapper_kwargs=args_wrapper, device=device, ) classifiers = init_classifier( embed_dim=model.embed_dim, num_heads=num_heads, verb_classes=verb_classes, noun_classes=noun_classes, action_classes=action_classes, num_blocks=num_probe_blocks, device=device, num_classifiers=len(opt_kwargs), )
# --init data train_set, train_loader, train_data_info = init_data( dataset=dataset, training=True, base_path=train_data_path, annotations_path=train_annotations, batch_size=batch_size, frames_per_clip=frames_per_clip, fps=frames_per_second, anticipation_time_sec=train_anticipation_time_sec, anticipation_point=train_anticipation_point, # -- random_resize_scale=random_resize_scale, reprob=reprob, auto_augment=auto_augment, motion_shift=motion_shift, # -- crop_size=resolution, world_size=world_size, rank=rank, num_workers=num_workers, pin_mem=pin_mem, persistent_workers=False, ) ipe = train_loader.num_batches logger.info(f"Dataloader created... iterations per epoch: {ipe}") _, val_loader, _ = init_data( dataset=dataset, training=False, base_path=val_data_path, annotations_path=val_annotations, batch_size=batch_size, frames_per_clip=frames_per_clip, fps=frames_per_second, anticipation_time_sec=val_anticipation_time_sec, anticipation_point=val_anticipation_point, crop_size=resolution, world_size=world_size, rank=rank, num_workers=num_workers, pin_mem=pin_mem, persistent_workers=False, ) val_ipe = val_loader.num_batches logger.info(f"Val dataloader created... iterations per epoch: {val_ipe}")
# -- optimizer and scheduler optimizer, scaler, scheduler, wd_scheduler = init_opt( classifiers=classifiers, opt_kwargs=opt_kwargs, iterations_per_epoch=ipe, num_epochs=num_epochs, use_bfloat16=use_bfloat16, ) classifiers = [DistributedDataParallel(c, static_graph=True) for c in classifiers]
# -- load training checkpoint start_epoch = 0 if resume_checkpoint and os.path.exists(latest_path): classifiers, optimizer, scaler, start_epoch = load_checkpoint( device=device, r_path=latest_path, classifiers=classifiers, opt=optimizer, scaler=scaler, val_only=val_only, ) for _ in range(start_epoch * ipe): [s.step() for s in scheduler] [wds.step() for wds in wd_scheduler] if val_only: start_epoch = 0
def save_checkpoint(epoch): save_dict = { "classifiers": [c.state_dict() for c in classifiers], "opt": [o.state_dict() for o in optimizer], "scaler": None if scaler is None else [s.state_dict() for s in scaler], "epoch": epoch, "batch_size": batch_size, "world_size": world_size, } if rank == 0: torch.save(save_dict, latest_path)
# -- Train action recognition model for epoch in range(start_epoch, num_epochs): logging.info(f"Epoch {epoch}")
train_data_info.set_epoch(epoch)
# report train action recognition (AR) if not val_only: logging.info("Training...") # with torch.autograd.detect_anomaly(): # TODO Remove train_metrics = train_one_epoch( action_is_verb_noun=action_is_verb_noun, ipe=ipe, device=device, model=model, classifiers=classifiers, scaler=scaler, optimizer=optimizer, scheduler=scheduler, wd_scheduler=wd_scheduler, data_loader=train_loader, use_bfloat16=use_bfloat16, verb_classes=verb_classes, noun_classes=noun_classes, action_classes=action_classes, criterion=criterion, )
# report val action anticipation (AA) val_metrics = validate( action_is_verb_noun=action_is_verb_noun, ipe=val_ipe, device=device, model=model, classifiers=classifiers, data_loader=val_loader, use_bfloat16=use_bfloat16, valid_verbs=val_verbs, valid_nouns=val_nouns, valid_actions=val_actions, verb_classes=verb_classes, noun_classes=noun_classes, action_classes=action_classes, criterion=criterion, ) if val_only: logger.info( "val acc (v/n): %.1f%% (%.1f%% %.1f%%) " "val recall (v/n): %.1f%% (%.1f%% %.1f%%) " % ( val_metrics["action"]["accuracy"], val_metrics["verb"]["accuracy"], val_metrics["noun"]["accuracy"], val_metrics["action"]["recall"], val_metrics["verb"]["recall"], val_metrics["noun"]["recall"], ) ) return
if action_is_verb_noun: logger.info( "[%5d] " "train acc (v/n): %.1f%% (%.1f%% %.1f%%) " "train recall (v/n): %.1f%% (%.1f%% %.1f%%) " "val acc (v/n): %.1f%% (%.1f%% %.1f%%) " "val recall (v/n): %.1f%% (%.1f%% %.1f%%) " % ( epoch + 1, train_metrics["action"]["accuracy"], train_metrics["verb"]["accuracy"], train_metrics["noun"]["accuracy"], train_metrics["action"]["recall"], train_metrics["verb"]["recall"], train_metrics["noun"]["recall"], val_metrics["action"]["accuracy"], val_metrics["verb"]["accuracy"], val_metrics["noun"]["accuracy"], val_metrics["action"]["recall"], val_metrics["verb"]["recall"], val_metrics["noun"]["recall"], ) ) if rank == 0: csv_logger.log( epoch + 1, train_metrics["action"]["accuracy"], train_metrics["verb"]["accuracy"], train_metrics["noun"]["accuracy"], train_metrics["action"]["recall"], train_metrics["verb"]["recall"], train_metrics["noun"]["recall"], val_metrics["action"]["accuracy"], val_metrics["verb"]["accuracy"], val_metrics["noun"]["accuracy"], val_metrics["action"]["recall"], val_metrics["verb"]["recall"], val_metrics["noun"]["recall"], ) else: logger.info( "[%5d] " "train acc (v/n): %.1f%% " "train recall (v/n): %.1f%% " "val acc (v/n): %.1f%% " "val recall (v/n): %.1f%% " % ( epoch + 1, train_metrics["action"]["accuracy"], train_metrics["action"]["recall"], val_metrics["action"]["accuracy"], val_metrics["action"]["recall"], ) ) if rank == 0: csv_logger.log( epoch + 1, train_metrics["action"]["accuracy"], train_metrics["action"]["recall"], val_metrics["action"]["accuracy"], val_metrics["action"]["recall"], )
save_checkpoint(epoch + 1)
def train_one_epoch( action_is_verb_noun, ipe, device, model, classifiers, scaler, optimizer, scheduler, wd_scheduler, data_loader, use_bfloat16, noun_classes, verb_classes, action_classes, criterion,): _data_loader = iter(data_loader) for c in classifiers: c.train(mode=True) if action_is_verb_noun: verb_metric_loggers = [ClassMeanRecall(num_classes=len(verb_classes), device=device, k=5) for _ in classifiers] noun_metric_loggers = [ClassMeanRecall(num_classes=len(noun_classes), device=device, k=5) for _ in classifiers] action_metric_loggers = [ClassMeanRecall(num_classes=len(action_classes), device=device, k=5) for _ in classifiers] data_elapsed_time_meter = AverageMeter()
for itr in range(ipe): itr_start_time = time.time()
try: udata = next(_data_loader) except Exception: _data_loader = iter(data_loader) udata = next(_data_loader)
[s.step() for s in scheduler] [wds.step() for wds in wd_scheduler]
with torch.cuda.amp.autocast(dtype=torch.bfloat16, enabled=use_bfloat16):
# Format of udata: ("video", "verb", "noun", "anticipation_time_sec") clips = udata[0].to(device) anticipation_times = udata[-1].to(device) # [B]
if action_is_verb_noun: # Map verb/nouns to unified class labels _verbs, _nouns = udata[1], udata[2] verb_labels, noun_labels, action_labels = [], [], [] for v, n in zip(_verbs, _nouns): verb_labels.append(verb_classes[int(v)]) noun_labels.append(noun_classes[int(n)]) action_labels.append(action_classes[(int(v), int(n))]) verb_labels = torch.tensor(verb_labels).to(device).to(_verbs.dtype) noun_labels = torch.tensor(noun_labels).to(device).to(_verbs.dtype) action_labels = torch.tensor(action_labels).to(device).to(_verbs.dtype) else: _actions = udata[1] action_labels = [action_classes[str(int(a))] for a in _actions] action_labels = torch.tensor(action_labels).to(device).to(_actions.dtype)
# -- data_elapsed_time_ms = (time.time() - itr_start_time) * 1000.0 data_elapsed_time_meter.update(data_elapsed_time_ms)
# Forward and prediction with torch.no_grad(): outputs = model(clips, anticipation_times) outputs = [c(outputs) for c in classifiers]
# Compute loss & update weights if action_is_verb_noun: verb_loss = [criterion(o["verb"], verb_labels) for o in outputs] noun_loss = [criterion(o["noun"], noun_labels) for o in outputs] action_loss = [criterion(o["action"], action_labels) for o in outputs] loss = [v + n + a for v, n, a in zip(verb_loss, noun_loss, action_loss)] else: loss = [criterion(o["action"], action_labels) for o in outputs] if use_bfloat16: [s.scale(l).backward() for s, l in zip(scaler, loss)] [s.step(o) for s, o in zip(scaler, optimizer)] [s.update() for s in scaler] else: [L.backward() for L in loss] [o.step() for o in optimizer] [o.zero_grad() for o in optimizer]
# Compute metrics for logging (e.g., accuracy and mean class recall) with torch.no_grad(): if action_is_verb_noun: verb_metrics = [m(o["verb"], verb_labels) for o, m in zip(outputs, verb_metric_loggers)] noun_metrics = [m(o["noun"], noun_labels) for o, m in zip(outputs, noun_metric_loggers)] action_metrics = [m(o["action"], action_labels) for o, m in zip(outputs, action_metric_loggers)]
if itr % 10 == 0 or itr == ipe - 1: if action_is_verb_noun: logger.info( "[%5d] " "acc (v/n): %.1f%% (%.1f%% %.1f%%) " "recall (v/n): %.1f%% (%.1f%% %.1f%%) " "[mem: %.2e] " "[data: %.1f ms]" % ( itr, max([a["accuracy"] for a in action_metrics]), max([v["accuracy"] for v in verb_metrics]), max([n["accuracy"] for n in noun_metrics]), max([a["recall"] for a in action_metrics]), max([v["recall"] for v in verb_metrics]), max([n["recall"] for n in noun_metrics]), torch.cuda.max_memory_allocated() / 1024.0**2, data_elapsed_time_meter.avg, ) ) else: logger.info( "[%5d] " "acc (v/n): %.1f%% " "recall (v/n): %.1f%% " "[mem: %.2e] " "[data: %.1f ms]" % ( itr, max([a["accuracy"] for a in action_metrics]), max([a["recall"] for a in action_metrics]), torch.cuda.max_memory_allocated() / 1024.0**2, data_elapsed_time_meter.avg, ) )
del _data_loader ret = dict( action=dict( accuracy=max([a["accuracy"] for a in action_metrics]), recall=max([a["recall"] for a in action_metrics]), ), ) if action_is_verb_noun: ret.update( dict( verb=dict( accuracy=max([v["accuracy"] for v in verb_metrics]), recall=max([v["recall"] for v in verb_metrics]), ), noun=dict( accuracy=max([n["accuracy"] for n in noun_metrics]), recall=max([n["recall"] for n in noun_metrics]), ), ) ) return ret
@torch.no_grad()def validate( action_is_verb_noun, ipe, device, model, classifiers, data_loader, use_bfloat16, valid_nouns, valid_verbs, valid_actions, noun_classes, verb_classes, action_classes, criterion,): logger.info("Running val...") _data_loader = iter(data_loader) for c in classifiers: c.train(mode=False) if action_is_verb_noun: verb_metric_loggers = [ClassMeanRecall(num_classes=len(verb_classes), device=device, k=5) for _ in classifiers] noun_metric_loggers = [ClassMeanRecall(num_classes=len(noun_classes), device=device, k=5) for _ in classifiers] action_metric_loggers = [ClassMeanRecall(num_classes=len(action_classes), device=device, k=5) for _ in classifiers]
for itr in range(ipe): try: udata = next(_data_loader) except Exception: _data_loader = iter(data_loader) udata = next(_data_loader)
with torch.cuda.amp.autocast(dtype=torch.bfloat16, enabled=use_bfloat16): # Format of udata: ("video", "verb", "noun", "anticipation_time_sec") clips = udata[0].to(device) anticipation_times = udata[-1].to(device) # [B]
if action_is_verb_noun: # Map verb/nouns to unified class labels _verbs, _nouns = udata[1], udata[2] verb_labels, noun_labels, action_labels = [], [], [] for v, n in zip(_verbs, _nouns): verb_labels.append(verb_classes[int(v)]) noun_labels.append(noun_classes[int(n)]) action_labels.append(action_classes[(int(v), int(n))]) verb_labels = torch.tensor(verb_labels).to(device).to(_verbs.dtype) noun_labels = torch.tensor(noun_labels).to(device).to(_verbs.dtype) action_labels = torch.tensor(action_labels).to(device).to(_verbs.dtype) else: _actions = udata[1] action_labels = [action_classes[str(int(a))] for a in _actions] action_labels = torch.tensor(action_labels).to(device).to(_actions.dtype)
# Forward and prediction outputs = model(clips, anticipation_times) outputs = [c(outputs) for c in classifiers]
if action_is_verb_noun: verb_loss = sum([criterion(o["verb"], verb_labels) for o in outputs]) noun_loss = sum([criterion(o["noun"], noun_labels) for o in outputs]) action_loss = sum([criterion(o["action"], action_labels) for o in outputs]) loss = verb_loss + noun_loss + action_loss else: loss = sum([criterion(o["action"], action_labels) for o in outputs])
action_metrics = [m(o["action"], action_labels) for o, m in zip(outputs, action_metric_loggers)] if action_is_verb_noun: verb_metrics = [m(o["verb"], verb_labels) for o, m in zip(outputs, verb_metric_loggers)] noun_metrics = [m(o["noun"], noun_labels) for o, m in zip(outputs, noun_metric_loggers)]
if itr % 10 == 0 or itr == ipe - 1: if action_is_verb_noun: logger.info( "[%5d] " "acc (v/n): %.1f%% (%.1f%% %.1f%%) " "recall (v/n): %.1f%% (%.1f%% %.1f%%) " "loss (v/n): %.3f (%.3f %.3f) " "[mem: %.2e] " % ( itr, max([a["accuracy"] for a in action_metrics]), max([v["accuracy"] for v in verb_metrics]), max([n["accuracy"] for n in noun_metrics]), max([a["recall"] for a in action_metrics]), max([v["recall"] for v in verb_metrics]), max([n["recall"] for n in noun_metrics]), loss, verb_loss, noun_loss, torch.cuda.max_memory_allocated() / 1024.0**2, ) ) else: logger.info( "[%5d] " "acc (v/n): %.1f%% " "recall (v/n): %.1f%% " "loss (v/n): %.3f " "[mem: %.2e] " % ( itr, max([a["accuracy"] for a in action_metrics]), max([a["recall"] for a in action_metrics]), loss, torch.cuda.max_memory_allocated() / 1024.0**2, ) )
del _data_loader ret = dict( action=dict( accuracy=max([a["accuracy"] for a in action_metrics]), recall=max([a["recall"] for a in action_metrics]), ), ) if action_is_verb_noun: ret.update( dict( verb=dict( accuracy=max([v["accuracy"] for v in verb_metrics]), recall=max([v["recall"] for v in verb_metrics]), ), noun=dict( accuracy=max([n["accuracy"] for n in noun_metrics]), recall=max([n["recall"] for n in noun_metrics]), ), ) ) return ret
def load_checkpoint(device, r_path, classifiers, opt, scaler, val_only=False): logger.info(f"read-path: {r_path}") checkpoint = robust_checkpoint_loader(r_path, map_location=torch.device("cpu"))
# -- loading encoder msg = [c.load_state_dict(pd) for c, pd in zip(classifiers, checkpoint["classifiers"])]
if val_only: logger.info(f"loaded pretrained classifier from epoch with msg: {msg}") return classifiers, opt, scaler, 0
epoch = checkpoint["epoch"] logger.info(f"loaded pretrained classifier from epoch {epoch} with msg: {msg}")
# -- loading optimizer [o.load_state_dict(c) for o, c in zip(opt, checkpoint["opt"])]
if scaler is not None: [s.load_state_dict(c) for s, c in zip(opt, checkpoint["scaler"])] logger.info(f"loaded optimizers from epoch {epoch}")
return classifiers, opt, scaler, epoch12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import torch.nn.functional as F
def sigmoid_focal_loss( inputs, targets, alpha=0.25, gamma=2.0, reduction="sum", detach=False,): """ Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
:param Tensor inputs: Prediction logits for each sample [B x K] :param Tensor targets: Class label for each sample [B] (long tensor) :param float alpha: Weight in range (0,1) to balance pos vs neg samples. :param float gamma: Exponent of modulating factor (1-p_t) to balance easy vs hard samples. :param str reduction: 'mean' | 'sum' """ B, K = inputs.size() # [batch_size, class logits]
# convert to one-hot targets targets = F.one_hot(targets, K).float() # [B, K]
p = F.sigmoid(inputs)
ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") p_t = p * targets + (1 - p) * (1 - targets) loss = ce_loss * ((1 - p_t) ** gamma)
if alpha >= 0: alpha_t = alpha * targets + (1 - alpha) * (1 - targets) loss = alpha_t * loss
if reduction == "mean": loss = loss.mean() elif reduction == "sum": loss = loss.sum()
if detach: loss = loss.detach()
return loss12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import torchimport torch.distributed as distimport torch.nn.functional as F
class ClassMeanRecall:
def __init__(self, num_classes: int, device: torch.device, k=5): self.num_classes = num_classes self.TP = torch.zeros(num_classes).to(device) self.FN = torch.zeros(num_classes).to(device) self.k = k
def __call__(self, logits, labels, valid_classes=None, eps=1e-8): """ :param logits: Tensors of shape [B, num_classes] :param labels: Tensors of shape [B] :param valid_classes: set """ k, tp_tensor, fn_tensor = self.k, self.TP, self.FN logits = F.sigmoid(logits)
if valid_classes is not None: _logits = torch.zeros(logits.shape).to(logits.device) for c in valid_classes: _logits[:, c] = logits[:, c] logits = _logits
preds = logits.topk(k, dim=1).indices
# Loop over batch and check whether all targets are within top-k logit # predictions for their respective class, if so TP else FN for p, gt in zip(preds, labels): if gt in p: tp_tensor[gt] += 1 else: fn_tensor[gt] += 1
# Aggregate TP/FN across all workers, but need to detach so that we # don't accidentally update tp_tensor and fn_tensor, which # only track local quantities. TP, FN = tp_tensor.clone(), fn_tensor.clone() dist.all_reduce(TP) dist.all_reduce(FN)
nch = torch.sum((TP + FN) > 0) # num classes hit; may not have TP/FP data for all classes yet recall = 100.0 * torch.sum(TP / (TP + FN + eps)) / nch # mean class recall topk = 100.0 * sum(TP) / int(sum(TP + FN)) # accuracy
return dict( recall=recall, accuracy=topk, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188"""Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in theLICENSE file in the root directory of this source tree.------------------------------------------------------------------------------
modelcustom API requirements:
API requirements for Encoder module: 1) Needs to be a pytorch module with 'forward()' function protocol: :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) :returns: (Tensor) Representations of video clip (shape=[batch_size x num_encoder_tokens x feature_dim])
API requirements for Predictor module: 1) Needs to be a pytorch module with 'forward()' function protocol: :param x: (Tensor) Video clip tokens (shape=[batch_size x num_encoder_tokens x feature_dim]) :param anticipation_time: (Tensor) Seconds into the future to predict for each sample in batch (shape=[batch_size]) :returns: (Tensor) Representations of future frames (shape=[batch_size x num_output_tokens x feature_dim]) 2) Needs to have a public attribute called 'embed_dim' (int) describing its output feature dimension."""
import logging
import torch
import src.models.predictor as vit_predimport src.models.vision_transformer as vit
logging.basicConfig()logger = logging.getLogger()logger.setLevel(logging.INFO)
def init_module( frames_per_clip: int, frames_per_second: int, resolution: int, checkpoint: str, # -- model_kwargs: dict, wrapper_kwargs: dict, **kwargs,): logger.info(f"Loading pretrained model from {checkpoint}") checkpoint = torch.load(checkpoint, map_location="cpu")
# ----------------------------------------------------------------------- # # Initialize Encoder # ----------------------------------------------------------------------- # enc_kwargs = model_kwargs["encoder"] enc_ckp_key = enc_kwargs.get("checkpoint_key") enc_model_name = enc_kwargs.get("model_name")
encoder = vit.__dict__[enc_model_name](img_size=resolution, num_frames=frames_per_clip, **enc_kwargs) pretrained_dict = checkpoint[enc_ckp_key] # -- pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} for k, v in encoder.state_dict().items(): if k not in pretrained_dict: logger.info(f'key "{k}" could not be found in loaded state dict') elif pretrained_dict[k].shape != v.shape: logger.info(f'key "{k}" is of different shape in model and loaded state dict') pretrained_dict[k] = v msg = encoder.load_state_dict(pretrained_dict, strict=False) logger.info(f"loaded pretrained model with msg: {msg}") print(encoder)
# ----------------------------------------------------------------------- # # Initialize Predictor # ----------------------------------------------------------------------- # prd_kwargs = model_kwargs["predictor"] prd_ckp_key = prd_kwargs.get("checkpoint_key") prd_model_name = prd_kwargs.get("model_name")
predictor = vit_pred.__dict__[prd_model_name]( img_size=resolution, embed_dim=encoder.embed_dim, patch_size=encoder.patch_size, tubelet_size=encoder.tubelet_size, **prd_kwargs, ) pretrained_dict = checkpoint[prd_ckp_key] # -- pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} for k, v in predictor.state_dict().items(): if k not in pretrained_dict: logger.info(f'key "{k}" could not be found in loaded state dict') elif pretrained_dict[k].shape != v.shape: logger.info( f'key "{k}" is of different shape in model and loaded state dict', pretrained_dict[k].shape, v.shape ) pretrained_dict[k] = v msg = predictor.load_state_dict(pretrained_dict, strict=False) logger.info(f"loaded pretrained predictor with msg: {msg}") print(predictor)
# ----------------------------------------------------------------------- # # Build Wrapper # ----------------------------------------------------------------------- # model = AnticipativeWrapper( encoder=encoder, predictor=predictor, frames_per_second=frames_per_second, crop_size=resolution, patch_size=encoder.patch_size, tubelet_size=encoder.tubelet_size, **wrapper_kwargs, ) model.embed_dim = encoder.embed_dim
return model
class AnticipativeWrapper(torch.nn.Module): """Use predictor for inference"""
def __init__( self, encoder, predictor, frames_per_second=4, crop_size=224, patch_size=16, tubelet_size=2, # -- wrapper kwargs no_predictor=False, num_output_frames=2, num_steps=1, no_encoder=False, ): super().__init__() self.encoder = encoder self.predictor = predictor self.grid_size = crop_size // patch_size self.tubelet_size = tubelet_size self.no_predictor = no_predictor self.num_output_frames = max(num_output_frames, tubelet_size) self.frames_per_second = frames_per_second self.num_steps = num_steps self.no_encoder = no_encoder
assert not (self.no_predictor and self.no_encoder), "Anticipative wrapper must use predictor or encoder"
def forward(self, x, anticipation_times): """ :param x: (Tensor) video of shape [B, C, T, H, W] :param anticipation_time: (Tensor) [B] seconds into the future to predict for each sample in batch """ x = self.encoder(x)
# determine 1D position of context tokens (x) # determine 1D position of prediction tokens # forward predictor with ctxt=x, tgt=None, masks_ctxt, masks_tgt if self.no_predictor: return x
# Will output representations of $num_output_frames, that are # $anticipation_time seconds into the future. B, N, D = x.size()
if self.no_encoder: x_accumulate = torch.rand(x.size(0), 0, x.size(2)).to(x.device) else: x_accumulate = x.clone()
# Position IDs of the encoder patch tokens [B, N] ctxt_positions = torch.arange(N).unsqueeze(0).repeat(B, 1).to(x.device)
# Position IDs of tokens to skip for each sample in batch [B] anticipation_steps = (anticipation_times * self.frames_per_second / self.tubelet_size).to(torch.int64) skip_positions = N + int(self.grid_size**2) * anticipation_steps
# Position IDs of tokens to predict [B, N_pred] N_pred = int(self.grid_size**2 * (self.num_output_frames // self.tubelet_size)) tgt_positions = torch.arange(N_pred).unsqueeze(0).repeat(B, 1).to(x.device) tgt_positions += skip_positions.unsqueeze(1).repeat(1, N_pred)
for _ in range(self.num_steps): x_pred = self.predictor(x, masks_x=ctxt_positions, masks_y=tgt_positions) x_accumulate = torch.cat([x_accumulate, x_pred], dim=1) x = torch.cat([x[:, N_pred:, :], x_pred], dim=1)
return x_accumulate123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import importlibimport logging
import torchimport torch.nn as nn
from src.models.attentive_pooler import AttentivePooler
logging.basicConfig()logger = logging.getLogger()logger.setLevel(logging.INFO)
class AttentiveClassifier(nn.Module):
def __init__( self, verb_classes: dict, noun_classes: dict, action_classes: dict, embed_dim: int, num_heads: int, depth: int, use_activation_checkpointing: bool, ): super().__init__() self.num_verb_classes = len(verb_classes) num_noun_classes = len(noun_classes) num_action_classes = len(action_classes) self.action_only = self.num_verb_classes == 0
self.pooler = AttentivePooler( num_queries=1 if self.action_only else 3, embed_dim=embed_dim, num_heads=num_heads, depth=depth, use_activation_checkpointing=use_activation_checkpointing, ) if not self.action_only: self.verb_classifier = nn.Linear(embed_dim, self.num_verb_classes, bias=True) self.noun_classifier = nn.Linear(embed_dim, num_noun_classes, bias=True) self.action_classifier = nn.Linear(embed_dim, num_action_classes, bias=True)
def forward(self, x): if torch.isnan(x).any(): print("Nan detected at output of encoder") exit(1)
x = self.pooler(x) # [B, 2, D] if not self.action_only: x_verb, x_noun, x_action = x[:, 0, :], x[:, 1, :], x[:, 2, :] x_verb = self.verb_classifier(x_verb) x_noun = self.noun_classifier(x_noun) x_action = self.action_classifier(x_action) return dict( verb=x_verb, noun=x_noun, action=x_action, ) else: x_action = x[:, 0, :] x_action = self.action_classifier(x_action) return dict(action=x_action)
def init_module( module_name, device, frames_per_clip, frames_per_second, resolution, checkpoint, model_kwargs, wrapper_kwargs,): """ Build (frozen) model and initialize from pretrained checkpoint
API requirements for "model" module: 1) Needs to be a pytorch module with 'forward()' function protocol: :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) :param anticipation_time: (Tensor) Seconds into the future to predict for each sample in batch (shape=[batch_size]) :returns: (Tensor) Representations of future frames (shape=[batch_size x num_output_tokens x feature_dim])
2) Needs to have a public attribute called 'embed_dim' (int) describing its output feature dimension. """ model = ( importlib.import_module(f"{module_name}") .init_module( frames_per_clip=frames_per_clip, frames_per_second=frames_per_second, resolution=resolution, checkpoint=checkpoint, model_kwargs=model_kwargs, wrapper_kwargs=wrapper_kwargs, ) .to(device) ) model.eval() for p in model.parameters(): p.requires_grad = False print(model) return model
def init_classifier( embed_dim: int, num_heads: int, num_blocks: int, device: torch.device, num_classifiers: int, action_classes: dict, verb_classes: dict, noun_classes: dict,): classifiers = [ AttentiveClassifier( verb_classes=verb_classes, noun_classes=noun_classes, action_classes=action_classes, embed_dim=embed_dim, num_heads=num_heads, depth=num_blocks, use_activation_checkpointing=True, ).to(device) for _ in range(num_classifiers) ] print(classifiers[0]) return classifiers12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import loggingimport math
import torch
logging.basicConfig()logger = logging.getLogger()logger.setLevel(logging.INFO)
def init_opt(classifiers, iterations_per_epoch, opt_kwargs, num_epochs, use_bfloat16=False): optimizers, schedulers, wd_schedulers, scalers = [], [], [], [] for c, kwargs in zip(classifiers, opt_kwargs): param_groups = [ { "params": (p for n, p in c.named_parameters()), "mc_warmup_steps": int(kwargs.get("warmup") * iterations_per_epoch), "mc_start_lr": kwargs.get("start_lr"), "mc_ref_lr": kwargs.get("ref_lr"), "mc_final_lr": kwargs.get("final_lr"), "mc_ref_wd": kwargs.get("ref_wd"), "mc_final_wd": kwargs.get("final_wd"), } ] logger.info("Using AdamW") optimizers += [torch.optim.AdamW(param_groups)] schedulers += [WarmupCosineLRSchedule(optimizers[-1], T_max=int(num_epochs * iterations_per_epoch))] wd_schedulers += [CosineWDSchedule(optimizers[-1], T_max=int(num_epochs * iterations_per_epoch))] scalers += [torch.cuda.amp.GradScaler() if use_bfloat16 else None] return optimizers, scalers, schedulers, wd_schedulers
class WarmupCosineLRSchedule(object):
def __init__(self, optimizer, T_max, last_epoch=-1): self.optimizer = optimizer self.T_max = T_max self._step = 0.0
def step(self): self._step += 1 for group in self.optimizer.param_groups: ref_lr = group.get("mc_ref_lr") final_lr = group.get("mc_final_lr") start_lr = group.get("mc_start_lr") warmup_steps = group.get("mc_warmup_steps") T_max = self.T_max - warmup_steps if self._step < warmup_steps: progress = float(self._step) / float(max(1, warmup_steps)) new_lr = start_lr + progress * (ref_lr - start_lr) else: # -- progress after warmup progress = float(self._step - warmup_steps) / float(max(1, T_max)) new_lr = max( final_lr, final_lr + (ref_lr - final_lr) * 0.5 * (1.0 + math.cos(math.pi * progress)), ) group["lr"] = new_lr
class CosineWDSchedule(object):
def __init__(self, optimizer, T_max): self.optimizer = optimizer self.T_max = T_max self._step = 0.0
def step(self): self._step += 1 progress = self._step / self.T_max
for group in self.optimizer.param_groups: ref_wd = group.get("mc_ref_wd") final_wd = group.get("mc_final_wd") new_wd = final_wd + (ref_wd - final_wd) * 0.5 * (1.0 + math.cos(math.pi * progress)) if final_wd <= ref_wd: new_wd = max(final_wd, new_wd) else: new_wd = min(final_wd, new_wd) group["weight_decay"] = new_wd123456789101112131415# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
def _make_transforms(crop_size=256): from ..video_classification_frozen.utils import make_transforms
return make_transforms(crop_size=crop_size, training=False)
def vjepa2_preprocessor(*, pretrained: bool = True, **kwargs): crop_size = kwargs.get("crop_size", 256) return _make_transforms(crop_size=crop_size)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import os
# -- FOR DISTRIBUTED TRAINING ENSURE ONLY 1 DEVICE VISIBLE PER PROCESStry: # -- WARNING: IF DOING DISTRIBUTED TRAINING ON A NON-SLURM CLUSTER, MAKE # -- SURE TO UPDATE THIS TO GET LOCAL-RANK ON NODE, OR ENSURE # -- THAT YOUR JOBS ARE LAUNCHED WITH ONLY 1 DEVICE VISIBLE # -- TO EACH PROCESS os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["SLURM_LOCALID"]except Exception: pass
import loggingimport mathimport pprint
import numpy as npimport torchimport torch.multiprocessing as mpimport torchvision.transforms as transformsfrom timm.data import create_transform as timm_make_transformsfrom torch.nn.parallel import DistributedDataParallel
from evals.image_classification_frozen.models import init_modulefrom src.datasets.data_manager import init_datafrom src.models.attentive_pooler import AttentiveClassifierfrom src.models.utils.modules import Block, CrossAttentionBlockfrom src.utils.checkpoint_loader import robust_checkpoint_loaderfrom src.utils.distributed import AllReduce, init_distributedfrom src.utils.logging import AverageMeter, CSVLogger
logging.basicConfig()logger = logging.getLogger()logger.setLevel(logging.INFO)
_GLOBAL_SEED = 0np.random.seed(_GLOBAL_SEED)torch.manual_seed(_GLOBAL_SEED)torch.backends.cudnn.benchmark = True
pp = pprint.PrettyPrinter(indent=4)
def main(args_eval, resume_preempt=False):
# ----------------------------------------------------------------------- # # PASSED IN PARAMS FROM CONFIG FILE # ----------------------------------------------------------------------- #
# -- VAL ONLY val_only = args_eval.get("val_only", False) if val_only: logger.info("VAL ONLY")
# -- EXPERIMENT pretrain_folder = args_eval.get("folder", None) resume_checkpoint = args_eval.get("resume_checkpoint", False) or resume_preempt eval_tag = args_eval.get("tag", None)
# -- PRETRAIN args_pretrain = args_eval.get("model_kwargs") checkpoint = args_pretrain.get("checkpoint") module_name = args_pretrain.get("module_name") args_model = args_pretrain.get("pretrain_kwargs") args_wrapper = args_pretrain.get("wrapper_kwargs")
args_exp = args_eval.get("experiment")
# -- CLASSIFIER args_classifier = args_exp.get("classifier") num_probe_blocks = args_classifier.get("num_probe_blocks", 1) num_heads = args_classifier.get("num_heads", 16)
# -- DATA args_data = args_exp.get("data") dataset_name = args_data.get("dataset_name") num_classes = args_data.get("num_classes") root_path = args_data.get("root_path", None) image_folder = args_data.get("image_folder", None) resolution = args_data.get("resolution", 224) normalization = args_data.get("normalization", None)
# -- OPTIMIZATION args_opt = args_exp.get("optimization") batch_size = args_opt.get("batch_size") num_epochs = args_opt.get("num_epochs") use_bfloat16 = args_opt.get("use_bfloat16") opt_kwargs = [ dict( ref_wd=kwargs.get("weight_decay"), final_wd=kwargs.get("final_weight_decay"), start_lr=kwargs.get("start_lr"), ref_lr=kwargs.get("lr"), final_lr=kwargs.get("final_lr"), warmup=kwargs.get("warmup"), ) for kwargs in args_opt.get("multihead_kwargs") ] # ----------------------------------------------------------------------- #
try: mp.set_start_method("spawn") except Exception: pass
if not torch.cuda.is_available(): device = torch.device("cpu") else: device = torch.device("cuda:0") torch.cuda.set_device(device)
world_size, rank = init_distributed() logger.info(f"Initialized (rank/world-size) {rank}/{world_size}")
# -- log/checkpointing paths folder = os.path.join(pretrain_folder, "image_classification_frozen/") if eval_tag is not None: folder = os.path.join(folder, eval_tag) if not os.path.exists(folder): os.makedirs(folder, exist_ok=True) log_file = os.path.join(folder, f"log_r{rank}.csv") latest_path = os.path.join(folder, "latest.pt")
# -- make csv_logger if rank == 0: csv_logger = CSVLogger(log_file, ("%d", "epoch"), ("%.5f", "loss"), ("%.5f", "acc"))
# -- init models encoder = init_module( module_name=module_name, resolution=resolution, checkpoint=checkpoint, model_kwargs=args_model, wrapper_kwargs=args_wrapper, device=device, ) # -- init classifier classifiers = [ AttentiveClassifier( embed_dim=encoder.embed_dim, num_heads=num_heads, depth=num_probe_blocks, num_classes=num_classes, use_activation_checkpointing=True, ).to(device) for _ in opt_kwargs ] classifiers = [DistributedDataParallel(c, static_graph=True) for c in classifiers] print(classifiers[0])
train_loader, train_sampler = make_dataloader( dataset_name=dataset_name, root_path=root_path, img_size=resolution, image_folder=image_folder, batch_size=batch_size, world_size=world_size, rank=rank, training=True, normalization=normalization, ) val_loader, _ = make_dataloader( dataset_name=dataset_name, root_path=root_path, img_size=resolution, image_folder=image_folder, batch_size=batch_size, world_size=world_size, rank=rank, training=False, normalization=normalization, ) ipe = len(train_loader) logger.info(f"Dataloader created... iterations per epoch: {ipe}")
# -- optimizer and scheduler optimizer, scaler, scheduler, wd_scheduler = init_opt( classifiers=classifiers, opt_kwargs=opt_kwargs, iterations_per_epoch=ipe, num_epochs=num_epochs, use_bfloat16=use_bfloat16, )
# -- load training checkpoint start_epoch = 0 if resume_checkpoint and os.path.exists(latest_path): classifiers, optimizer, scaler, start_epoch = load_checkpoint( device=device, r_path=latest_path, classifiers=classifiers, opt=optimizer, scaler=scaler, val_only=val_only, ) for _ in range(start_epoch * ipe): [s.step() for s in scheduler] [wds.step() for wds in wd_scheduler]
def save_checkpoint(epoch): all_classifier_dicts = [c.state_dict() for c in classifiers] all_opt_dicts = [o.state_dict() for o in optimizer]
save_dict = { "classifiers": all_classifier_dicts, "opt": all_opt_dicts, "scaler": None if scaler is None else [s.state_dict() for s in scaler], "epoch": epoch, "batch_size": batch_size, "world_size": world_size, } if rank == 0: torch.save(save_dict, latest_path)
# TRAIN LOOP for epoch in range(start_epoch, num_epochs): logger.info("Epoch %d" % (epoch + 1)) train_sampler.set_epoch(epoch) if val_only: train_acc = -1.0 else: train_acc = run_one_epoch( device=device, training=True, encoder=encoder, classifiers=classifiers, scaler=scaler, optimizer=optimizer, scheduler=scheduler, wd_scheduler=wd_scheduler, data_loader=train_loader, use_bfloat16=use_bfloat16, )
val_acc = run_one_epoch( device=device, training=False, encoder=encoder, classifiers=classifiers, scaler=scaler, optimizer=optimizer, scheduler=scheduler, wd_scheduler=wd_scheduler, data_loader=val_loader, use_bfloat16=use_bfloat16, )
logger.info("[%5d] train: %.3f%% test: %.3f%%" % (epoch + 1, train_acc, val_acc)) if rank == 0: csv_logger.log(epoch + 1, train_acc, val_acc)
if val_only: return
save_checkpoint(epoch + 1)
def run_one_epoch( device, training, encoder, classifiers, scaler, optimizer, scheduler, wd_scheduler, data_loader, use_bfloat16,):
for c in classifiers: c.train(mode=training)
criterion = torch.nn.CrossEntropyLoss() top1_meters = [AverageMeter() for _ in classifiers] for itr, data in enumerate(data_loader): if training: [s.step() for s in scheduler] [wds.step() for wds in wd_scheduler]
with torch.cuda.amp.autocast(dtype=torch.float16, enabled=use_bfloat16): imgs, labels = data[0].to(device), data[1].to(device) with torch.no_grad(): outputs = encoder(imgs) if not training: outputs = [c(outputs) for c in classifiers] if training: outputs = [c(outputs) for c in classifiers]
losses = [criterion(o, labels) for o in outputs] top1_accs = [100.0 * o.max(dim=1).indices.eq(labels).sum() / len(imgs) for o in outputs] top1_accs = [float(AllReduce.apply(t)) for t in top1_accs] for t1m, t1a in zip(top1_meters, top1_accs): t1m.update(t1a)
if training: if use_bfloat16: [s.scale(l).backward() for s, l in zip(scaler, losses)] [s.step(o) for s, o in zip(scaler, optimizer)] [s.update() for s in scaler] else: [loss.backward() for loss in losses] [o.step() for o in optimizer] [o.zero_grad() for o in optimizer]
_agg_top1 = np.array([t1m.avg for t1m in top1_meters]) if itr % 20 == 0: logger.info( "[%5d] %.3f%% [%.3f%% %.3f%%] [mem: %.2e]" % ( itr, _agg_top1.max(), _agg_top1.mean(), _agg_top1.min(), torch.cuda.max_memory_allocated() / 1024.0**2, ) )
return _agg_top1.max()
def load_checkpoint(device, r_path, classifiers, opt, scaler, val_only=False): checkpoint = robust_checkpoint_loader(r_path, map_location=torch.device("cpu")) logger.info(f"read-path: {r_path}")
# -- loading encoder msg = [c.load_state_dict(pd) for c, pd in zip(classifiers, checkpoint["classifiers"])]
if val_only: logger.info(f"loaded pretrained classifier from epoch with msg: {msg}") return classifiers, opt, scaler, 0
epoch = checkpoint["epoch"] logger.info(f"loaded pretrained classifier from epoch {epoch} with msg: {msg}")
# -- loading optimizer [o.load_state_dict(c) for o, c in zip(opt, checkpoint["opt"])]
if scaler is not None: [s.load_state_dict(c) for s, c in zip(scaler, checkpoint["scaler"])] logger.info(f"loaded optimizers from epoch {epoch}")
return classifiers, opt, scaler, epoch
DEFAULT_NORMALIZATION = ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
def make_dataloader( dataset_name, root_path, image_folder, batch_size, world_size, rank, img_size=224, training=False, subset_file=None, normalization=None,): if normalization is None: normalization = DEFAULT_NORMALIZATION
if training: logger.info("implementing auto-augment strategy") transform = timm_make_transforms( input_size=img_size, is_training=training, auto_augment="original", interpolation="bicubic", re_prob=0.25, re_mode="pixel", re_count=1, mean=normalization[0], std=normalization[1], ) else: transform = transforms.Compose( [ transforms.Resize(size=int(img_size * 256 / 224)), transforms.CenterCrop(size=img_size), transforms.ToTensor(), transforms.Normalize(normalization[0], normalization[1]), ] )
data_loader, data_sampler = init_data( data=dataset_name, transform=transform, batch_size=batch_size, world_size=world_size, rank=rank, root_path=root_path, image_folder=image_folder, training=training, drop_last=False, subset_file=subset_file, ) return data_loader, data_sampler
def init_opt(classifiers, iterations_per_epoch, opt_kwargs, num_epochs, use_bfloat16=False): optimizers, schedulers, wd_schedulers, scalers = [], [], [], [] for c, kwargs in zip(classifiers, opt_kwargs): param_groups = [ { "params": (p for n, p in c.named_parameters()), "mc_warmup_steps": int(kwargs.get("warmup") * iterations_per_epoch), "mc_start_lr": kwargs.get("start_lr"), "mc_ref_lr": kwargs.get("ref_lr"), "mc_final_lr": kwargs.get("final_lr"), "mc_ref_wd": kwargs.get("ref_wd"), "mc_final_wd": kwargs.get("final_wd"), } ] logger.info("Using AdamW") optimizers += [torch.optim.AdamW(param_groups)] schedulers += [WarmupCosineLRSchedule(optimizers[-1], T_max=int(num_epochs * iterations_per_epoch))] wd_schedulers += [CosineWDSchedule(optimizers[-1], T_max=int(num_epochs * iterations_per_epoch))] scalers += [torch.cuda.amp.GradScaler() if use_bfloat16 else None] return optimizers, scalers, schedulers, wd_schedulers
class WarmupCosineLRSchedule(object):
def __init__(self, optimizer, T_max, last_epoch=-1): self.optimizer = optimizer self.T_max = T_max self._step = 0.0
def step(self): self._step += 1 for group in self.optimizer.param_groups: ref_lr = group.get("mc_ref_lr") final_lr = group.get("mc_final_lr") start_lr = group.get("mc_start_lr") warmup_steps = group.get("mc_warmup_steps") T_max = self.T_max - warmup_steps if self._step < warmup_steps: progress = float(self._step) / float(max(1, warmup_steps)) new_lr = start_lr + progress * (ref_lr - start_lr) else: # -- progress after warmup progress = float(self._step - warmup_steps) / float(max(1, T_max)) new_lr = max( final_lr, final_lr + (ref_lr - final_lr) * 0.5 * (1.0 + math.cos(math.pi * progress)), ) group["lr"] = new_lr
class CosineWDSchedule(object):
def __init__(self, optimizer, T_max): self.optimizer = optimizer self.T_max = T_max self._step = 0.0
def step(self): self._step += 1 progress = self._step / self.T_max
for group in self.optimizer.param_groups: ref_wd = group.get("mc_ref_wd") final_wd = group.get("mc_final_wd") new_wd = final_wd + (ref_wd - final_wd) * 0.5 * (1.0 + math.cos(math.pi * progress)) if final_wd <= ref_wd: new_wd = max(final_wd, new_wd) else: new_wd = min(final_wd, new_wd) group["weight_decay"] = new_wd1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in theLICENSE file in the root directory of this source tree.------------------------------------------------------------------------------
modelcustom API requirements:
API requirements for Encoder module: 1) Needs to be a pytorch module with 'forward()' function protocol: :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) :returns: (Tensor) Representations of video clip (shape=[batch_size x num_encoder_tokens x feature_dim]) 2) Needs to have a public attribute called 'embed_dim' (int) describing its output feature dimension.
API requirements for Predictor module: 1) Needs to be a pytorch module with 'forward()' function protocol: :param x: (Tensor) Video clip tokens (shape=[batch_size x num_encoder_tokens x feature_dim]) :param anticipation_time: (Tensor) Seconds into the future to predict for each sample in batch (shape=[batch_size]) :returns: (Tensor) Representations of future frames (shape=[batch_size x num_output_tokens x feature_dim]) 2) Needs to have a public attribute called 'embed_dim' (int) describing its output feature dimension."""
import logging
import torch
import src.models.vision_transformer as vit
logging.basicConfig()logger = logging.getLogger()logger.setLevel(logging.INFO)
def init_module( resolution: int, checkpoint: str, # -- model_kwargs: dict, wrapper_kwargs: dict, **kwargs,): logger.info(f"Loading pretrained model from {checkpoint=}") checkpoint = torch.load(checkpoint, map_location="cpu")
img_as_video_nframes = wrapper_kwargs.get("img_as_video_nframes") # -- enc_kwargs = model_kwargs["encoder"] enc_ckp_key = enc_kwargs.get("checkpoint_key") enc_model_name = enc_kwargs.get("model_name")
model = vit.__dict__[enc_model_name]( input_size=resolution, num_frames=img_as_video_nframes, **enc_kwargs, )
def forward_prehook(module, input): input = input[0] # [B, C, H, W] input = input.unsqueeze(2).repeat(1, 1, img_as_video_nframes, 1, 1) return input
model.register_forward_pre_hook(forward_prehook)
pretrained_dict = checkpoint[enc_ckp_key] # -- pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} for k, v in model.state_dict().items(): if k not in pretrained_dict: logger.info(f'key "{k}" could not be found in loaded state dict') elif pretrained_dict[k].shape != v.shape: logger.info(f'key "{k}" is of different shape in model and loaded state dict') pretrained_dict[k] = v msg = model.load_state_dict(pretrained_dict, strict=False) logger.info(f"loaded pretrained model with msg: {msg}") print(model)
del checkpoint return model1234567891011121314151617181920212223242526272829303132333435363738394041424344# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import importlibimport logging
logging.basicConfig()logger = logging.getLogger()logger.setLevel(logging.INFO)
def init_module( module_name, device, resolution, checkpoint, model_kwargs, wrapper_kwargs,): """ Build (frozen) model and initialize from pretrained checkpoint
API requirements for Encoder module: 1) Needs to be a pytorch module with 'forward()' function protocol: :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) :returns: (Tensor) Representations of video clip (shape=[batch_size x num_encoder_tokens x feature_dim]) """ model = ( importlib.import_module(f"{module_name}") .init_module( resolution=resolution, checkpoint=checkpoint, model_kwargs=model_kwargs, wrapper_kwargs=wrapper_kwargs, ) .to(device) ) model.eval() for p in model.parameters(): p.requires_grad = False print(model) return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import argparseimport multiprocessing as mpimport osimport pprint
import yaml
from evals.scaffold import main as eval_mainfrom src.utils.distributed import init_distributed
parser = argparse.ArgumentParser()parser.add_argument("--val_only", action="store_true", help="only run eval", default=False)parser.add_argument("--fname", type=str, help="name of config file to load", default="configs.yaml")parser.add_argument( "--devices", type=str, nargs="+", default=["cuda:0", "cuda:1", "cuda:2", "cuda:3", "cuda:4", "cuda:5", "cuda:6", "cuda:7"], help="which devices to use on local machine",)parser.add_argument( "--debugmode", type=bool, default=False, help="Setting this to true will not spin up new processes. " "The main code runs the main process, which makes it easier to debug with checkpointing.",)parser.add_argument( "--folder", type=str, help="location to save logs", default="",)parser.add_argument("--override_config_folder", action="store_true")parser.add_argument("--checkpoint", type=str, help="location of pretrained ckpt")parser.add_argument("--model_name", type=str, help="Model name")parser.add_argument("--batch_size", type=int)parser.add_argument("--use_fsdp", action="store_true")
def process_main(args, rank, fname, world_size, devices): import logging import os
os.environ["CUDA_VISIBLE_DEVICES"] = str(devices[rank].split(":")[-1])
logging.basicConfig() logger = logging.getLogger() if rank == 0: logger.setLevel(logging.INFO) else: logger.setLevel(logging.ERROR)
logger.info(f"called-params {fname}")
# Load config params = None with open(fname, "r") as y_file: params = yaml.load(y_file, Loader=yaml.FullLoader) if args.val_only: params["val_only"] = True
if args.checkpoint: params["model_kwargs"]["checkpoint"] = args.checkpoint
if args.model_name: params["model_kwargs"]["pretrain_kwargs"]["encoder"]["model_name"] = args.model_name
if args.batch_size: params["experiment"]["optimization"]["batch_size"] = args.batch_size
if args.override_config_folder: params["folder"] = args.folder params["use_fsdp"] = args.use_fsdp logger.info("loaded params...")
if rank == 0: pprint.PrettyPrinter(indent=4).pprint(params)
# Init distributed (access to comm between GPUS on same machine) world_size, rank = init_distributed(rank_and_world_size=(rank, world_size)) logger.info(f"Running... (rank: {rank}/{world_size})")
# Launch the eval with loaded config eval_main(params["eval_name"], args_eval=params)
if __name__ == "__main__": args = parser.parse_args() if args.debugmode: # FSDP debugging (use torchrun) if args.use_fsdp: process_main( args=args, rank=int(os.environ["RANK"]), fname=args.fname, world_size=int(os.environ["WORLD_SIZE"]), devices=args.devices, ) # Single-GPU debugging else: process_main(args=args, rank=0, fname=args.fname, world_size=1, devices=["cuda:0"]) else: num_gpus = len(args.devices) mp.set_start_method("spawn") for rank in range(num_gpus): mp.Process(target=process_main, args=(args, rank, args.fname, num_gpus, args.devices)).start()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import argparseimport osimport pprintimport time
import submititimport yaml
from evals.scaffold import main as eval_mainfrom src.utils.logging import get_logger
logger = get_logger(force=True)
try: USER = os.getlogin()except OSError: USER = "default"
parser = argparse.ArgumentParser()parser.add_argument("--val_only", action="store_true", help="only run eval", default=False)parser.add_argument( "--folder", type=str, help="location to save submitit logs", default=f"/home/{USER}/submitit/",)parser.add_argument("--override_config_folder", action="store_true")parser.add_argument("--checkpoint", type=str, help="location of pretrained ckpt")parser.add_argument("--model_name", type=str, help="Model name")parser.add_argument("--batch_size", type=int)parser.add_argument("--nodes", type=int)parser.add_argument("--exclude", type=str, help="nodes to exclude from training", default=None)parser.add_argument( "--batch-launch", action="store_true", help="whether fname points to a file to batch-lauch several config files",)parser.add_argument( "--fname", type=str, help="yaml file containing config file names to launch", default="configs.yaml",)parser.add_argument( "--account", type=str, default="jepa", help="Cluster account to use when submitting jobs",)parser.add_argument( "--partition", type=str, default="learn", help="cluster partition to submit jobs on",)parser.add_argument( "--qos", type=str, default="lowest", help="If specified, qos value to use when submitting jobs",)parser.add_argument("--time", type=int, default=4300, help="time in minutes to run job")parser.add_argument("--use_fsdp", action="store_true")
class Trainer:
def __init__(self, args_eval=None, resume_preempt=None): self.eval_name = args_eval["eval_name"] self.args_eval = args_eval self.resume_preempt = resume_preempt
def __call__(self): eval_name = self.eval_name args_eval = self.args_eval resume_preempt = self.resume_preempt logger.info("loaded eval params...") pp = pprint.PrettyPrinter(indent=4) pp.pprint(args_eval)
eval_main(eval_name, args_eval=args_eval, resume_preempt=resume_preempt)
def checkpoint(self): fb_trainer = Trainer(self.args_eval, True) return submitit.helpers.DelayedSubmission( fb_trainer, )
def launch_evals_with_parsed_args( args_for_evals, submitit_folder, account="jepa", partition="learn", qos=None, timeout=4300, nodes=1, tasks_per_node=1, mem_per_gpu="210G", cpus_per_task=32, delay_seconds=10, exclude_nodes=None, save_configs=False, dependency=None,): if not isinstance(args_for_evals, list): logger.info(f"Passed in eval-args of type {type(args_for_evals)}") args_for_evals = [args_for_evals]
time.sleep(delay_seconds) logger.info("Launching evaluations in separate jobs...") executor = submitit.AutoExecutor(folder=os.path.join(submitit_folder, "job_%j"), slurm_max_num_timeout=20) executor.update_parameters( slurm_partition=partition, slurm_account=account, slurm_qos=qos, slurm_mem_per_gpu=mem_per_gpu, slurm_array_parallelism=64, timeout_min=timeout, nodes=nodes, tasks_per_node=tasks_per_node, cpus_per_task=cpus_per_task, gpus_per_node=tasks_per_node, dependency=dependency, )
if exclude_nodes is not None: executor.update_parameters(slurm_exclude=exclude_nodes)
jobs, trainers = [], [] with executor.batch(): for ae in args_for_evals: fb_trainer = Trainer(ae) job = executor.submit( fb_trainer, ) trainers.append(fb_trainer) jobs.append(job)
for job, ae in zip(jobs, args_for_evals): logger.info(f"Launched eval job with id {job.job_id}") if save_configs: params_path = os.path.join(job._paths.folder, "eval-params.yaml") if not os.path.exists(params_path): with open(params_path, "w") as f: yaml.dump(ae, f) logger.info(f"Wrote eval config to {params_path}")
def launch_evals():
# ---------------------------------------------------------------------- # # 1. Put config file names in a list # ---------------------------------------------------------------------- # config_fnames = [args.fname]
# -- If batch-launch is True, then the args.fname yaml file is not a # -- config, but actually specifies a list of other config files # -- to run in a slurm job array if args.batch_launch: with open(args.fname, "r") as y_file: config_fnames = yaml.load(y_file, Loader=yaml.FullLoader) # ---------------------------------------------------------------------- #
# ---------------------------------------------------------------------- # # 2. Parse each yaml config file as a dict and place in list # ---------------------------------------------------------------------- # nodes, tasks_per_node = None, None configs = [] for f in config_fnames: with open(f, "r") as y_file: _params = yaml.load(y_file, Loader=yaml.FullLoader)
if args.val_only: _params["val_only"] = True
if args.checkpoint: _params["model_kwargs"]["checkpoint"] = args.checkpoint
if args.model_name: _params["model_kwargs"]["pretrain_kwargs"]["encoder"]["model_name"] = args.model_name
if args.batch_size: _params["experiment"]["optimization"]["batch_size"] = args.batch_size
if args.nodes: _params["nodes"] = args.nodes
if args.override_config_folder: _params["folder"] = args.folder _params["use_fsdp"] = args.use_fsdp
nodes = int(_params.get("nodes")) tasks_per_node = int(_params.get("tasks_per_node")) mem_per_gpu = _params.get("mem_per_gpu", "220G") cpus_per_task = _params.get("cpus_per_task", 32) configs += [_params]
logger.info(f"Loaded {len(configs)} config files") logger.info(f"Running all jobs with {nodes=} / {tasks_per_node=}") # ---------------------------------------------------------------------- #
# ---------------------------------------------------------------------- # # 3. Launch evals with parsed config files # ---------------------------------------------------------------------- # launch_evals_with_parsed_args( args_for_evals=configs, account=args.account, submitit_folder=args.folder, partition=args.partition, qos=args.qos, mem_per_gpu=mem_per_gpu, timeout=args.time, nodes=nodes, tasks_per_node=tasks_per_node, cpus_per_task=cpus_per_task, exclude_nodes=args.exclude, ) # ---------------------------------------------------------------------- #
if __name__ == "__main__": args = parser.parse_args() launch_evals()12345678910111213141516171819# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import importlib
from src.utils.logging import get_logger
logger = get_logger("Eval runner scaffold")
def main(eval_name, args_eval, resume_preempt=False): logger.info(f"Running evaluation: {eval_name}") if eval_name.startswith("app."): import_path = f"{eval_name}.eval" else: import_path = f"evals.{eval_name}.eval" return importlib.import_module(import_path).main(args_eval=args_eval, resume_preempt=resume_preempt)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import os
# -- FOR DISTRIBUTED TRAINING ENSURE ONLY 1 DEVICE VISIBLE PER PROCESStry: # -- WARNING: IF DOING DISTRIBUTED TRAINING ON A NON-SLURM CLUSTER, MAKE # -- SURE TO UPDATE THIS TO GET LOCAL-RANK ON NODE, OR ENSURE # -- THAT YOUR JOBS ARE LAUNCHED WITH ONLY 1 DEVICE VISIBLE # -- TO EACH PROCESS os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["SLURM_LOCALID"]except Exception: pass
import loggingimport mathimport pprint
import numpy as npimport torchimport torch.multiprocessing as mpimport torch.nn.functional as Ffrom torch.nn.parallel import DistributedDataParallel
from evals.video_classification_frozen.models import init_modulefrom evals.video_classification_frozen.utils import make_transformsfrom src.datasets.data_manager import init_datafrom src.models.attentive_pooler import AttentiveClassifierfrom src.utils.checkpoint_loader import robust_checkpoint_loaderfrom src.utils.distributed import AllReduce, init_distributedfrom src.utils.logging import AverageMeter, CSVLogger
logging.basicConfig()logger = logging.getLogger()logger.setLevel(logging.INFO)
_GLOBAL_SEED = 0np.random.seed(_GLOBAL_SEED)torch.manual_seed(_GLOBAL_SEED)torch.backends.cudnn.benchmark = True
pp = pprint.PrettyPrinter(indent=4)
def main(args_eval, resume_preempt=False):
# ----------------------------------------------------------------------- # # PASSED IN PARAMS FROM CONFIG FILE # ----------------------------------------------------------------------- #
# -- VAL ONLY val_only = args_eval.get("val_only", False) if val_only: logger.info("VAL ONLY")
# -- EXPERIMENT pretrain_folder = args_eval.get("folder", None) resume_checkpoint = args_eval.get("resume_checkpoint", False) or resume_preempt eval_tag = args_eval.get("tag", None) num_workers = args_eval.get("num_workers", 12)
# -- PRETRAIN args_pretrain = args_eval.get("model_kwargs") checkpoint = args_pretrain.get("checkpoint") module_name = args_pretrain.get("module_name") args_model = args_pretrain.get("pretrain_kwargs") args_wrapper = args_pretrain.get("wrapper_kwargs")
args_exp = args_eval.get("experiment")
# -- CLASSIFIER args_classifier = args_exp.get("classifier") num_probe_blocks = args_classifier.get("num_probe_blocks", 1) num_heads = args_classifier.get("num_heads", 16)
# -- DATA args_data = args_exp.get("data") dataset_type = args_data.get("dataset_type", "VideoDataset") num_classes = args_data.get("num_classes") train_data_path = [args_data.get("dataset_train")] val_data_path = [args_data.get("dataset_val")] resolution = args_data.get("resolution", 224) num_segments = args_data.get("num_segments", 1) frames_per_clip = args_data.get("frames_per_clip", 16) frame_step = args_data.get("frame_step", 4) duration = args_data.get("clip_duration", None) num_views_per_segment = args_data.get("num_views_per_segment", 1) normalization = args_data.get("normalization", None)
# -- OPTIMIZATION args_opt = args_exp.get("optimization") batch_size = args_opt.get("batch_size") num_epochs = args_opt.get("num_epochs") use_bfloat16 = args_opt.get("use_bfloat16") opt_kwargs = [ dict( ref_wd=kwargs.get("weight_decay"), final_wd=kwargs.get("final_weight_decay"), start_lr=kwargs.get("start_lr"), ref_lr=kwargs.get("lr"), final_lr=kwargs.get("final_lr"), warmup=kwargs.get("warmup"), ) for kwargs in args_opt.get("multihead_kwargs") ] # ----------------------------------------------------------------------- #
try: mp.set_start_method("spawn") except Exception: pass
if not torch.cuda.is_available(): device = torch.device("cpu") else: device = torch.device("cuda:0") torch.cuda.set_device(device)
world_size, rank = init_distributed() logger.info(f"Initialized (rank/world-size) {rank}/{world_size}")
# -- log/checkpointing paths folder = os.path.join(pretrain_folder, "video_classification_frozen/") if eval_tag is not None: folder = os.path.join(folder, eval_tag) if not os.path.exists(folder): os.makedirs(folder, exist_ok=True) log_file = os.path.join(folder, f"log_r{rank}.csv") latest_path = os.path.join(folder, "latest.pt")
# -- make csv_logger if rank == 0: csv_logger = CSVLogger(log_file, ("%d", "epoch"), ("%.5f", "loss"), ("%.5f", "acc"))
# Initialize model
# -- init models encoder = init_module( module_name=module_name, frames_per_clip=frames_per_clip, resolution=resolution, checkpoint=checkpoint, model_kwargs=args_model, wrapper_kwargs=args_wrapper, device=device, ) # -- init classifier classifiers = [ AttentiveClassifier( embed_dim=encoder.embed_dim, num_heads=num_heads, depth=num_probe_blocks, num_classes=num_classes, use_activation_checkpointing=True, ).to(device) for _ in opt_kwargs ] classifiers = [DistributedDataParallel(c, static_graph=True) for c in classifiers] print(classifiers[0])
train_loader, train_sampler = make_dataloader( dataset_type=dataset_type, root_path=train_data_path, img_size=resolution, frames_per_clip=frames_per_clip, frame_step=frame_step, eval_duration=duration, num_segments=num_segments, num_views_per_segment=1, allow_segment_overlap=True, batch_size=batch_size, world_size=world_size, rank=rank, training=True, num_workers=num_workers, normalization=normalization, ) val_loader, _ = make_dataloader( dataset_type=dataset_type, root_path=val_data_path, img_size=resolution, frames_per_clip=frames_per_clip, frame_step=frame_step, num_segments=num_segments, eval_duration=duration, num_views_per_segment=num_views_per_segment, allow_segment_overlap=True, batch_size=batch_size, world_size=world_size, rank=rank, training=False, num_workers=num_workers, normalization=normalization, ) ipe = len(train_loader) logger.info(f"Dataloader created... iterations per epoch: {ipe}")
# -- optimizer and scheduler optimizer, scaler, scheduler, wd_scheduler = init_opt( classifiers=classifiers, opt_kwargs=opt_kwargs, iterations_per_epoch=ipe, num_epochs=num_epochs, use_bfloat16=use_bfloat16, )
# -- load training checkpoint start_epoch = 0 if resume_checkpoint and os.path.exists(latest_path): classifiers, optimizer, scaler, start_epoch = load_checkpoint( device=device, r_path=latest_path, classifiers=classifiers, opt=optimizer, scaler=scaler, val_only=val_only, ) for _ in range(start_epoch * ipe): [s.step() for s in scheduler] [wds.step() for wds in wd_scheduler]
def save_checkpoint(epoch): all_classifier_dicts = [c.state_dict() for c in classifiers] all_opt_dicts = [o.state_dict() for o in optimizer]
save_dict = { "classifiers": all_classifier_dicts, "opt": all_opt_dicts, "scaler": None if scaler is None else [s.state_dict() for s in scaler], "epoch": epoch, "batch_size": batch_size, "world_size": world_size, } if rank == 0: torch.save(save_dict, latest_path)
# TRAIN LOOP for epoch in range(start_epoch, num_epochs): logger.info("Epoch %d" % (epoch + 1)) train_sampler.set_epoch(epoch) if val_only: train_acc = -1.0 else: train_acc = run_one_epoch( device=device, training=True, encoder=encoder, classifiers=classifiers, scaler=scaler, optimizer=optimizer, scheduler=scheduler, wd_scheduler=wd_scheduler, data_loader=train_loader, use_bfloat16=use_bfloat16, )
val_acc = run_one_epoch( device=device, training=False, encoder=encoder, classifiers=classifiers, scaler=scaler, optimizer=optimizer, scheduler=scheduler, wd_scheduler=wd_scheduler, data_loader=val_loader, use_bfloat16=use_bfloat16, )
logger.info("[%5d] train: %.3f%% test: %.3f%%" % (epoch + 1, train_acc, val_acc)) if rank == 0: csv_logger.log(epoch + 1, train_acc, val_acc)
if val_only: return
save_checkpoint(epoch + 1)
def run_one_epoch( device, training, encoder, classifiers, scaler, optimizer, scheduler, wd_scheduler, data_loader, use_bfloat16,):
for c in classifiers: c.train(mode=training)
criterion = torch.nn.CrossEntropyLoss() top1_meters = [AverageMeter() for _ in classifiers] for itr, data in enumerate(data_loader): if training: [s.step() for s in scheduler] [wds.step() for wds in wd_scheduler]
with torch.cuda.amp.autocast(dtype=torch.float16, enabled=use_bfloat16): # Load data and put on GPU clips = [ [dij.to(device, non_blocking=True) for dij in di] # iterate over spatial views of clip for di in data[0] # iterate over temporal index of clip ] clip_indices = [d.to(device, non_blocking=True) for d in data[2]] labels = data[1].to(device) batch_size = len(labels)
# Forward and prediction with torch.no_grad(): outputs = encoder(clips, clip_indices) if not training: outputs = [[c(o) for o in outputs] for c in classifiers] if training: outputs = [[c(o) for o in outputs] for c in classifiers]
# Compute loss losses = [[criterion(o, labels) for o in coutputs] for coutputs in outputs] with torch.no_grad(): outputs = [sum([F.softmax(o, dim=1) for o in coutputs]) / len(coutputs) for coutputs in outputs] top1_accs = [100.0 * coutputs.max(dim=1).indices.eq(labels).sum() / batch_size for coutputs in outputs] top1_accs = [float(AllReduce.apply(t1a)) for t1a in top1_accs] for t1m, t1a in zip(top1_meters, top1_accs): t1m.update(t1a)
if training: if use_bfloat16: [[s.scale(lij).backward() for lij in li] for s, li in zip(scaler, losses)] [s.step(o) for s, o in zip(scaler, optimizer)] [s.update() for s in scaler] else: [[lij.backward() for lij in li] for li in losses] [o.step() for o in optimizer] [o.zero_grad() for o in optimizer]
_agg_top1 = np.array([t1m.avg for t1m in top1_meters]) if itr % 10 == 0: logger.info( "[%5d] %.3f%% [%.3f%% %.3f%%] [mem: %.2e]" % ( itr, _agg_top1.max(), _agg_top1.mean(), _agg_top1.min(), torch.cuda.max_memory_allocated() / 1024.0**2, ) )
return _agg_top1.max()
def load_checkpoint(device, r_path, classifiers, opt, scaler, val_only=False): checkpoint = robust_checkpoint_loader(r_path, map_location=torch.device("cpu")) logger.info(f"read-path: {r_path}")
# -- loading encoder pretrained_dict = checkpoint["classifiers"] msg = [c.load_state_dict(pd) for c, pd in zip(classifiers, pretrained_dict)]
if val_only: logger.info(f"loaded pretrained classifier from epoch with msg: {msg}") return classifiers, opt, scaler, 0
epoch = checkpoint["epoch"] logger.info(f"loaded pretrained classifier from epoch {epoch} with msg: {msg}")
# -- loading optimizer [o.load_state_dict(pd) for o, pd in zip(opt, checkpoint["opt"])]
if scaler is not None: [s.load_state_dict(pd) for s, pd in zip(scaler, checkpoint["scaler"])]
logger.info(f"loaded optimizers from epoch {epoch}")
return classifiers, opt, scaler, epoch
def load_pretrained(encoder, pretrained, checkpoint_key="target_encoder"): logger.info(f"Loading pretrained model from {pretrained}") checkpoint = robust_checkpoint_loader(pretrained, map_location="cpu") try: pretrained_dict = checkpoint[checkpoint_key] except Exception: pretrained_dict = checkpoint["encoder"]
pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} for k, v in encoder.state_dict().items(): if k not in pretrained_dict: logger.info(f"key '{k}' could not be found in loaded state dict") elif pretrained_dict[k].shape != v.shape: logger.info(f"{pretrained_dict[k].shape} | {v.shape}") logger.info(f"key '{k}' is of different shape in model and loaded state dict") exit(1) pretrained_dict[k] = v msg = encoder.load_state_dict(pretrained_dict, strict=False) print(encoder) logger.info(f"loaded pretrained model with msg: {msg}") logger.info(f"loaded pretrained encoder from epoch: {checkpoint['epoch']}\n path: {pretrained}") del checkpoint return encoder
DEFAULT_NORMALIZATION = ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
def make_dataloader( root_path, batch_size, world_size, rank, dataset_type="VideoDataset", img_size=224, frames_per_clip=16, frame_step=4, num_segments=8, eval_duration=None, num_views_per_segment=1, allow_segment_overlap=True, training=False, num_workers=12, subset_file=None, normalization=None,): if normalization is None: normalization = DEFAULT_NORMALIZATION
# Make Video Transforms transform = make_transforms( training=training, num_views_per_clip=num_views_per_segment, random_horizontal_flip=False, random_resize_aspect_ratio=(0.75, 4 / 3), random_resize_scale=(0.08, 1.0), reprob=0.25, auto_augment=True, motion_shift=False, crop_size=img_size, normalize=normalization, )
data_loader, data_sampler = init_data( data=dataset_type, root_path=root_path, transform=transform, batch_size=batch_size, world_size=world_size, rank=rank, clip_len=frames_per_clip, frame_sample_rate=frame_step, duration=eval_duration, num_clips=num_segments, allow_clip_overlap=allow_segment_overlap, num_workers=num_workers, drop_last=False, subset_file=subset_file, ) return data_loader, data_sampler
def init_opt(classifiers, iterations_per_epoch, opt_kwargs, num_epochs, use_bfloat16=False): optimizers, schedulers, wd_schedulers, scalers = [], [], [], [] for c, kwargs in zip(classifiers, opt_kwargs): param_groups = [ { "params": (p for n, p in c.named_parameters()), "mc_warmup_steps": int(kwargs.get("warmup") * iterations_per_epoch), "mc_start_lr": kwargs.get("start_lr"), "mc_ref_lr": kwargs.get("ref_lr"), "mc_final_lr": kwargs.get("final_lr"), "mc_ref_wd": kwargs.get("ref_wd"), "mc_final_wd": kwargs.get("final_wd"), } ] logger.info("Using AdamW") optimizers += [torch.optim.AdamW(param_groups)] schedulers += [WarmupCosineLRSchedule(optimizers[-1], T_max=int(num_epochs * iterations_per_epoch))] wd_schedulers += [CosineWDSchedule(optimizers[-1], T_max=int(num_epochs * iterations_per_epoch))] scalers += [torch.cuda.amp.GradScaler() if use_bfloat16 else None] return optimizers, scalers, schedulers, wd_schedulers
class WarmupCosineLRSchedule(object):
def __init__(self, optimizer, T_max, last_epoch=-1): self.optimizer = optimizer self.T_max = T_max self._step = 0.0
def step(self): self._step += 1 for group in self.optimizer.param_groups: ref_lr = group.get("mc_ref_lr") final_lr = group.get("mc_final_lr") start_lr = group.get("mc_start_lr") warmup_steps = group.get("mc_warmup_steps") T_max = self.T_max - warmup_steps if self._step < warmup_steps: progress = float(self._step) / float(max(1, warmup_steps)) new_lr = start_lr + progress * (ref_lr - start_lr) else: # -- progress after warmup progress = float(self._step - warmup_steps) / float(max(1, T_max)) new_lr = max( final_lr, final_lr + (ref_lr - final_lr) * 0.5 * (1.0 + math.cos(math.pi * progress)), ) group["lr"] = new_lr
class CosineWDSchedule(object):
def __init__(self, optimizer, T_max): self.optimizer = optimizer self.T_max = T_max self._step = 0.0
def step(self): self._step += 1 progress = self._step / self.T_max
for group in self.optimizer.param_groups: ref_wd = group.get("mc_ref_wd") final_wd = group.get("mc_final_wd") new_wd = final_wd + (ref_wd - final_wd) * 0.5 * (1.0 + math.cos(math.pi * progress)) if final_wd <= ref_wd: new_wd = max(final_wd, new_wd) else: new_wd = min(final_wd, new_wd) group["weight_decay"] = new_wd123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149"""Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in theLICENSE file in the root directory of this source tree.------------------------------------------------------------------------------
modelcustom API requirements:
API requirements for Encoder module: 1) Needs to be a pytorch module with 'forward()' function protocol: :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) :returns: (Tensor) Representations of video clip (shape=[batch_size x num_encoder_tokens x feature_dim]) 2) Needs to have a public attribute called 'embed_dim' (int) describing its output feature dimension.
API requirements for Predictor module: 1) Needs to be a pytorch module with 'forward()' function protocol: :param x: (Tensor) Video clip tokens (shape=[batch_size x num_encoder_tokens x feature_dim]) :param anticipation_time: (Tensor) Seconds into the future to predict for each sample in batch (shape=[batch_size]) :returns: (Tensor) Representations of future frames (shape=[batch_size x num_output_tokens x feature_dim]) 2) Needs to have a public attribute called 'embed_dim' (int) describing its output feature dimension."""
import logging
import torchimport torch.nn as nn
import src.models.vision_transformer as vitfrom src.masks.utils import apply_masksfrom src.models.utils.pos_embs import get_1d_sincos_pos_embed
logging.basicConfig()logger = logging.getLogger()logger.setLevel(logging.INFO)
def init_module( resolution: int, frames_per_clip: int, checkpoint: str, # -- model_kwargs: dict, wrapper_kwargs: dict,): logger.info(f"Loading pretrained model from {checkpoint}") checkpoint = torch.load(checkpoint, map_location="cpu")
enc_kwargs = model_kwargs["encoder"] enc_ckp_key = enc_kwargs.get("checkpoint_key") enc_model_name = enc_kwargs.get("model_name")
model = vit.__dict__[enc_model_name](img_size=resolution, num_frames=frames_per_clip, **enc_kwargs)
pretrained_dict = checkpoint[enc_ckp_key] # -- pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} for k, v in model.state_dict().items(): if k not in pretrained_dict: logger.info(f'key "{k}" could not be found in loaded state dict') elif pretrained_dict[k].shape != v.shape: logger.info(f'key "{k}" is of different shape in model and loaded state dict') pretrained_dict[k] = v msg = model.load_state_dict(pretrained_dict, strict=False) logger.info(f"loaded pretrained model with msg: {msg}") print(model)
model = ClipAggregation( model, tubelet_size=model.tubelet_size, **wrapper_kwargs, ) del checkpoint return model
class ClipAggregation(nn.Module): """ Process each clip indepdnently and concatenate all tokens """
def __init__( self, model, tubelet_size=2, max_frames=128, use_pos_embed=False, ): super().__init__() self.model = model self.tubelet_size = tubelet_size self.embed_dim = embed_dim = model.embed_dim self.num_heads = model.num_heads
# 1D-temporal pos-embedding self.pos_embed = None if use_pos_embed: max_T = max_frames // tubelet_size self.pos_embed = nn.Parameter(torch.zeros(1, max_T, embed_dim), requires_grad=False) sincos = get_1d_sincos_pos_embed(embed_dim, max_T) self.pos_embed.copy_(torch.from_numpy(sincos).float().unsqueeze(0))
def forward(self, x, clip_indices=None):
num_clips = len(x) num_views_per_clip = len(x[0]) B, C, F, H, W = x[0][0].size()
# Concatenate all spatial and temporal views along batch dimension x = [torch.cat(xi, dim=0) for xi in x] x = torch.cat(x, dim=0)
outputs = self.model(x)
def multiviews_postprocess(outputs): _, N, D = outputs.size() T = F // self.tubelet_size # num temporal indices S = N // T # num spatial tokens
# Unroll outputs into a 2D array [spatial_views x temporal_views] eff_B = B * num_views_per_clip all_outputs = [[] for _ in range(num_views_per_clip)] for i in range(num_clips): o = outputs[i * eff_B : (i + 1) * eff_B] for j in range(num_views_per_clip): all_outputs[j].append(o[j * B : (j + 1) * B])
for i, outputs in enumerate(all_outputs): # Concatenate along temporal dimension outputs = [o.reshape(B, T, S, D) for o in outputs] outputs = torch.cat(outputs, dim=1).flatten(1, 2) # Compute positional embedding if (self.pos_embed is not None) and (clip_indices is not None): _indices = [c[:, :: self.tubelet_size] for c in clip_indices] pos_embed = self.pos_embed.repeat(B, 1, 1) # [B, max_T, D] pos_embed = apply_masks(pos_embed, _indices, concat=False) # list(Tensor([B, T, D])) pos_embed = torch.cat(pos_embed, dim=1) # concatenate along temporal dimension pos_embed = pos_embed.unsqueeze(2).repeat(1, 1, S, 1) # [B, T*num_clips, S, D] pos_embed = pos_embed.flatten(1, 2) outputs += pos_embed all_outputs[i] = outputs
return all_outputs
return multiviews_postprocess(outputs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in theLICENSE file in the root directory of this source tree.------------------------------------------------------------------------------
modelcustom API requirements:
API requirements for Encoder module: 1) Needs to be a pytorch module with 'forward()' function protocol: :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) :returns: (Tensor) Representations of video clip (shape=[batch_size x num_encoder_tokens x feature_dim]) 2) Needs to have a public attribute called 'embed_dim' (int) describing its output feature dimension.
API requirements for Predictor module: 1) Needs to be a pytorch module with 'forward()' function protocol: :param x: (Tensor) Video clip tokens (shape=[batch_size x num_encoder_tokens x feature_dim]) :param anticipation_time: (Tensor) Seconds into the future to predict for each sample in batch (shape=[batch_size]) :returns: (Tensor) Representations of future frames (shape=[batch_size x num_output_tokens x feature_dim]) 2) Needs to have a public attribute called 'embed_dim' (int) describing its output feature dimension."""
import logging
import torchimport torch.nn as nn
import src.models.vision_transformer as vitfrom src.masks.utils import apply_masksfrom src.models.utils.pos_embs import get_1d_sincos_pos_embed
logging.basicConfig()logger = logging.getLogger()logger.setLevel(logging.INFO)
def init_module( resolution: int, frames_per_clip: int, checkpoint: str, # -- model_kwargs: dict, wrapper_kwargs: dict,): logger.info(f"Loading pretrained model from {checkpoint}") checkpoint = torch.load(checkpoint, map_location="cpu")
enc_kwargs = model_kwargs["encoder"] enc_ckp_key = enc_kwargs.get("checkpoint_key") enc_model_name = enc_kwargs.get("model_name")
out_layers = wrapper_kwargs.get("out_layers")
model = vit.__dict__[enc_model_name]( img_size=resolution, num_frames=frames_per_clip, out_layers=out_layers, **enc_kwargs )
pretrained_dict = checkpoint[enc_ckp_key] # -- pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} for k, v in model.state_dict().items(): if k not in pretrained_dict: logger.info(f'key "{k}" could not be found in loaded state dict') elif pretrained_dict[k].shape != v.shape: logger.info(f'key "{k}" is of different shape in model and loaded state dict') pretrained_dict[k] = v msg = model.load_state_dict(pretrained_dict, strict=False) logger.info(f"loaded pretrained model with msg: {msg}") print(model)
model = ClipAggregation( model, tubelet_size=model.tubelet_size, **wrapper_kwargs, ) del checkpoint return model
class ClipAggregation(nn.Module): """ Process each clip indepdnently and concatenate all tokens """
def __init__( self, model, tubelet_size=2, max_frames=128, use_pos_embed=False, out_layers=None, ): super().__init__() self.model = model self.tubelet_size = tubelet_size self.embed_dim = embed_dim = model.embed_dim self.num_heads = model.num_heads
# 1D-temporal pos-embedding self.pos_embed = None if use_pos_embed: max_T = max_frames // tubelet_size self.pos_embed = nn.Parameter(torch.zeros(1, max_T, embed_dim), requires_grad=False) sincos = get_1d_sincos_pos_embed(embed_dim, max_T) self.pos_embed.copy_(torch.from_numpy(sincos).float().unsqueeze(0))
def forward(self, x, clip_indices=None):
num_clips = len(x) num_views_per_clip = len(x[0]) B, C, F, H, W = x[0][0].size()
# Concatenate all spatial and temporal views along batch dimension x = [torch.cat(xi, dim=0) for xi in x] x = torch.cat(x, dim=0)
outputs = self.model(x) outputs = torch.cat(outputs, dim=1)
def multiviews_postprocess(outputs): _, N, D = outputs.size() T = F // self.tubelet_size # num temporal indices S = N // T # num spatial tokens
# Unroll outputs into a 2D array [spatial_views x temporal_views] eff_B = B * num_views_per_clip all_outputs = [[] for _ in range(num_views_per_clip)] for i in range(num_clips): o = outputs[i * eff_B : (i + 1) * eff_B] for j in range(num_views_per_clip): all_outputs[j].append(o[j * B : (j + 1) * B])
for i, outputs in enumerate(all_outputs): # Concatenate along temporal dimension outputs = [o.reshape(B, T, S, D) for o in outputs] outputs = torch.cat(outputs, dim=1).flatten(1, 2) # Compute positional embedding if (self.pos_embed is not None) and (clip_indices is not None): _indices = [c[:, :: self.tubelet_size] for c in clip_indices] pos_embed = self.pos_embed.repeat(B, 1, 1) # [B, max_T, D] pos_embed = apply_masks(pos_embed, _indices, concat=False) # list(Tensor([B, T, D])) pos_embed = torch.cat(pos_embed, dim=1) # concatenate along temporal dimension pos_embed = pos_embed.unsqueeze(2).repeat(1, 1, S, 1) # [B, T*num_clips, S, D] pos_embed = pos_embed.flatten(1, 2) outputs += pos_embed all_outputs[i] = outputs
return all_outputs
return multiviews_postprocess(outputs)12345678910111213141516171819202122232425262728293031323334353637383940414243444546# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import importlibimport logging
logging.basicConfig()logger = logging.getLogger()logger.setLevel(logging.INFO)
def init_module( module_name, device, frames_per_clip, resolution, checkpoint, model_kwargs, wrapper_kwargs,): """ Build (frozen) model and initialize from pretrained checkpoint
API requirements for Encoder module: 1) Needs to be a pytorch module with 'forward()' function protocol: :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) :returns: (Tensor) Representations of video clip (shape=[batch_size x num_encoder_tokens x feature_dim]) """ model = ( importlib.import_module(f"{module_name}") .init_module( frames_per_clip=frames_per_clip, resolution=resolution, checkpoint=checkpoint, model_kwargs=model_kwargs, wrapper_kwargs=wrapper_kwargs, ) .to(device) ) model.eval() for p in model.parameters(): p.requires_grad = False print(model) return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import numpy as npimport torchimport torchvision.transforms as transforms
import src.datasets.utils.video.transforms as video_transformsimport src.datasets.utils.video.volume_transforms as volume_transformsfrom src.datasets.utils.video.randerase import RandomErasing
def make_transforms( training=True, random_horizontal_flip=True, random_resize_aspect_ratio=(3 / 4, 4 / 3), random_resize_scale=(0.3, 1.0), reprob=0.0, auto_augment=False, motion_shift=False, crop_size=224, num_views_per_clip=1, normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),):
if not training and num_views_per_clip > 1: print("Making EvalVideoTransform, multi-view") _frames_augmentation = EvalVideoTransform( num_views_per_clip=num_views_per_clip, short_side_size=crop_size, normalize=normalize, )
else: _frames_augmentation = VideoTransform( training=training, random_horizontal_flip=random_horizontal_flip, random_resize_aspect_ratio=random_resize_aspect_ratio, random_resize_scale=random_resize_scale, reprob=reprob, auto_augment=auto_augment, motion_shift=motion_shift, crop_size=crop_size, normalize=normalize, ) return _frames_augmentation
class VideoTransform(object):
def __init__( self, training=True, random_horizontal_flip=True, random_resize_aspect_ratio=(3 / 4, 4 / 3), random_resize_scale=(0.3, 1.0), reprob=0.0, auto_augment=False, motion_shift=False, crop_size=224, normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ):
self.training = training
short_side_size = int(crop_size * 256 / 224) self.eval_transform = video_transforms.Compose( [ video_transforms.Resize(short_side_size, interpolation="bilinear"), video_transforms.CenterCrop(size=(crop_size, crop_size)), volume_transforms.ClipToTensor(), video_transforms.Normalize(mean=normalize[0], std=normalize[1]), ] )
self.random_horizontal_flip = random_horizontal_flip self.random_resize_aspect_ratio = random_resize_aspect_ratio self.random_resize_scale = random_resize_scale self.auto_augment = auto_augment self.motion_shift = motion_shift self.crop_size = crop_size self.normalize = torch.tensor(normalize)
self.autoaug_transform = video_transforms.create_random_augment( input_size=(crop_size, crop_size), auto_augment="rand-m7-n4-mstd0.5-inc1", interpolation="bicubic", )
self.spatial_transform = ( video_transforms.random_resized_crop_with_shift if motion_shift else video_transforms.random_resized_crop )
self.reprob = reprob self.erase_transform = RandomErasing( reprob, mode="pixel", max_count=1, num_splits=1, device="cpu", )
def __call__(self, buffer):
if not self.training: return [self.eval_transform(buffer)]
buffer = [transforms.ToPILImage()(frame) for frame in buffer]
if self.auto_augment: buffer = self.autoaug_transform(buffer)
buffer = [transforms.ToTensor()(img) for img in buffer] buffer = torch.stack(buffer) # T C H W buffer = buffer.permute(0, 2, 3, 1) # T H W C
buffer = tensor_normalize(buffer, self.normalize[0], self.normalize[1]) buffer = buffer.permute(3, 0, 1, 2) # T H W C -> C T H W
buffer = self.spatial_transform( images=buffer, target_height=self.crop_size, target_width=self.crop_size, scale=self.random_resize_scale, ratio=self.random_resize_aspect_ratio, ) if self.random_horizontal_flip: buffer, _ = video_transforms.horizontal_flip(0.5, buffer)
if self.reprob > 0: buffer = buffer.permute(1, 0, 2, 3) buffer = self.erase_transform(buffer) buffer = buffer.permute(1, 0, 2, 3)
return [buffer]
class EvalVideoTransform(object):
def __init__( self, num_views_per_clip=1, short_side_size=224, normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ): self.views_per_clip = num_views_per_clip self.short_side_size = short_side_size self.spatial_resize = video_transforms.Resize(short_side_size, interpolation="bilinear") self.to_tensor = video_transforms.Compose( [ volume_transforms.ClipToTensor(), video_transforms.Normalize(mean=normalize[0], std=normalize[1]), ] )
def __call__(self, buffer):
# Sample several spatial views of each clip buffer = np.array(self.spatial_resize(buffer)) T, H, W, C = buffer.shape
num_views = self.views_per_clip side_len = self.short_side_size spatial_step = (max(H, W) - side_len) // (num_views - 1)
all_views = [] for i in range(num_views): start = i * spatial_step if H > W: view = buffer[:, start : start + side_len, :, :] else: view = buffer[:, :, start : start + side_len, :] view = self.to_tensor(view) all_views.append(view)
return all_views
def tensor_normalize(tensor, mean, std): """ Normalize a given tensor by subtracting the mean and dividing the std. Args: tensor (tensor): tensor to normalize. mean (tensor or list): mean value to subtract. std (tensor or list): std to divide. """ if tensor.dtype == torch.uint8: tensor = tensor.float() tensor = tensor / 255.0 if isinstance(mean, list): mean = torch.tensor(mean) if isinstance(std, list): std = torch.tensor(std) tensor = tensor - mean tensor = tensor / std return tensor123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import osimport subprocessimport timefrom logging import getLogger
import numpy as npimport torchimport torchvision
_GLOBAL_SEED = 0logger = getLogger()
class ImageNet(torchvision.datasets.ImageFolder):
def __init__( self, root, image_folder="imagenet_full_size/061417/", tar_file="imagenet_full_size-061417.tar.gz", transform=None, train=True, job_id=None, local_rank=None, index_targets=False, ): """ ImageNet
Dataset wrapper
:param root: root network directory for ImageNet data :param image_folder: path to images inside root network directory :param tar_file: zipped image_folder inside root network directory :param train: whether to load train data (or validation) :param job_id: scheduler job-id used to create dir on local machine :param index_targets: whether to index the id of each labeled image """
suffix = "train/" if train else "val/" data_path = os.path.join(root, image_folder, suffix) logger.info(f"data-path {data_path}")
super(ImageNet, self).__init__(root=data_path, transform=transform) logger.info("Initialized ImageNet")
if index_targets: self.targets = [] for sample in self.samples: self.targets.append(sample[1]) self.targets = np.array(self.targets) self.samples = np.array(self.samples)
mint = None self.target_indices = [] for t in range(len(self.classes)): indices = np.squeeze(np.argwhere(self.targets == t)).tolist() self.target_indices.append(indices) mint = len(indices) if mint is None else min(mint, len(indices)) logger.debug(f"num-labeled target {t} {len(indices)}") logger.info(f"min. labeled indices {mint}")
class ImageNetSubset(object):
def __init__(self, dataset, subset_file): """ ImageNetSubset
:param dataset: ImageNet dataset object :param subset_file: '.txt' file containing IDs of IN1K images to keep """ self.dataset = dataset self.subset_file = subset_file self.filter_dataset_(subset_file)
def filter_dataset_(self, subset_file): """Filter self.dataset to a subset""" root = self.dataset.root class_to_idx = self.dataset.class_to_idx # -- update samples to subset of IN1k targets/samples new_samples = [] logger.info(f"Using {subset_file}") with open(subset_file, "r") as rfile: for line in rfile: class_name = line.split("_")[0] target = class_to_idx[class_name] img = line.split("\n")[0] new_samples.append((os.path.join(root, class_name, img), target)) self.samples = new_samples
@property def classes(self): return self.dataset.classes
def __len__(self): return len(self.samples)
def __getitem__(self, index): path, target = self.samples[index] img = self.dataset.loader(path) if self.dataset.transform is not None: img = self.dataset.transform(img) if self.dataset.target_transform is not None: target = self.dataset.target_transform(target) return img, target
def make_imagenet1k( transform, batch_size, collator=None, pin_mem=True, num_workers=8, world_size=1, rank=0, root_path=None, image_folder=None, training=True, drop_last=True, persistent_workers=False, subset_file=None,): dataset = ImageNet( root=root_path, image_folder=image_folder, transform=transform, train=training, index_targets=False, ) if subset_file is not None: dataset = ImageNetSubset(dataset, subset_file) logger.info("ImageNet dataset created") dist_sampler = torch.utils.data.distributed.DistributedSampler(dataset=dataset, num_replicas=world_size, rank=rank) data_loader = torch.utils.data.DataLoader( dataset, collate_fn=collator, sampler=dist_sampler, batch_size=batch_size, drop_last=drop_last, pin_memory=pin_mem, num_workers=num_workers, persistent_workers=persistent_workers, ) logger.info("ImageNet unsupervised data loader created")
return dataset, data_loader, dist_sampler123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import bisectimport csvimport ioimport time
import numpy as npimport torchfrom torch.utils.data import _utilsfrom torch.utils.data.dataloader import ExceptionWrapper, _DatasetKind, _MultiProcessingDataLoaderIter
from src.utils.monitoring import ResourceMonitoringThread
class ConcatIndices: """Helper to map indices of concatenated/mixed datasets to the sample index for the corresponding dataset."""
cumulative_sizes: np.ndarray
def __init__(self, sizes): self.cumulative_sizes = np.cumsum(sizes)
def __len__(self): return self.cumulative_sizes[-1]
def __getitem__(self, idx): # Returns a pair (dataset_idx, sample_idx) if idx < 0 or idx >= len(self): raise ValueError(f"index must be between 0 and the total size ({len(self)})") dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx) if dataset_idx == 0: return dataset_idx, idx return dataset_idx, idx - self.cumulative_sizes[dataset_idx - 1]
class CSVLogger(object): """An append-to CSV abstraction. File I/O requires a flush."""
def __init__(self, fname, header): """Write header to internal buffers.""" self.fname = fname self.buffer = io.StringIO() self.writer = csv.writer(self.buffer, quoting=csv.QUOTE_NONNUMERIC) self.writer.writerow(header) self.initialized = False
def writerow(self, row) -> None: """Write row to internal buffers.""" self.writer.writerow(row)
def flush(self) -> None: """Flush buffer to file.""" # Overwrite old file mode = "a+" if self.initialized else "w"
with open(self.fname, mode, newline="") as f: f.write(self.buffer.getvalue())
self.buffer = io.StringIO() self.writer = csv.writer(self.buffer, quoting=csv.QUOTE_NONNUMERIC) self.initialized = True
class MonitoredDataset(torch.utils.data.Dataset): """Implement resource monitoring on a per-worker basis.
The sampling occurs every monitor_interval seconds and writes the log every log_interval seconds to a file specified by log_filename, which maps a worker id to a file using the '%w' placeholder.
Warning: Do not call this dataset before it is consumed in the DataLoader. """
def __init__( self, dataset: torch.utils.data.Dataset, log_filename: str, log_interval: float, monitor_interval: float ): self.dataset = dataset self.log_filename = str(log_filename) self.log_interval = log_interval self.monitor_interval = monitor_interval self._csv_log = None self._monitoring_thread = None self._last_log_time = None # Patch getitems dynamically if hasattr(self.dataset, "__getitems__") and self.dataset.__getitems__:
def __getitems__(self, index): self.maybe_start_resource_monitoring() return self.dataset.__getitems__(index)
self.__getitems__ = __getitems__
def __del__(self): self.stop_resource_monitoring()
def __getitem__(self, index): self.maybe_start_resource_monitoring() return self.dataset.__getitem__(index)
def __len__(self): return len(self.dataset)
def _elapsed_log_time(self): if self._last_log_time is None: return float("inf") else: return time.perf_counter() - self._last_log_time
def _update_log_time(self): self._last_log_time = time.perf_counter()
def maybe_start_resource_monitoring(self): if self._monitoring_thread is None:
def callback_fn(resource_sample): worker_info = torch.utils.data.get_worker_info() worker_id = worker_info.id
if self._csv_log is None: header = [f.name for f in resource_sample.fields()] log_filename = self.log_filename.replace("%w", str(worker_id)) self._csv_log = CSVLogger(log_filename, header) row_values = resource_sample.as_tuple() self._csv_log.writerow(row_values)
if self._elapsed_log_time() > self.log_interval: self._csv_log.flush() self._update_log_time()
self._monitoring_thread = ResourceMonitoringThread( None, self.monitor_interval, stats_callback_fn=callback_fn ) self._monitoring_thread.start()
def stop_resource_monitoring(self): if self._monitoring_thread: self._monitoring_thread.stop()
class NondeterministicDataLoader(torch.utils.data.DataLoader): """Override torch dataloader to return out of order."""
def __init__(self, *args, **kwargs): """Pass through constructor.""" super().__init__(*args, **kwargs)
def _get_iterator(self): if self.num_workers: self.check_worker_number_rationality() return _SloppyMultiProcessingDataLoaderIter(self) else: return super()._get_iterator()
class _SloppyMultiProcessingDataLoaderIter(_MultiProcessingDataLoaderIter):
def __init__(self, *args, **kwargs): """Pass through constructor.""" super().__init__(*args, **kwargs)
def _next_data(self): """Adds out of order returns.""" while True: # If the worker responsible for `self._rcvd_idx` has already ended # and was unable to fulfill this task (due to exhausting an `IterableDataset`), # we try to advance `self._rcvd_idx` to find the next valid index. # # This part needs to run in the loop because both the `self._get_data()` # call and `_IterableDatasetStopIteration` check below can mark # extra worker(s) as dead. while self._rcvd_idx < self._send_idx: info = self._task_info[self._rcvd_idx] if info is None: # Found a reordered tombstone del self._task_info[self._rcvd_idx] self._rcvd_idx += 1 self._try_put_index() else: worker_id = info[0] # has data or is still active if len(info) == 2 or self._workers_status[worker_id]: break del self._task_info[self._rcvd_idx] self._rcvd_idx += 1 else: # no valid `self._rcvd_idx` is found (i.e., didn't break) if not self._persistent_workers: self._shutdown_workers() raise StopIteration
# Now `self._rcvd_idx` is the batch index we want to fetch
# Check if the next sample has already been generated if len(self._task_info[self._rcvd_idx]) == 2: data = self._task_info.pop(self._rcvd_idx)[1] return self._process_data(data)
assert not self._shutdown and self._tasks_outstanding > 0 idx, data = self._get_data() self._tasks_outstanding -= 1 if self._dataset_kind == _DatasetKind.Iterable: # Check for _IterableDatasetStopIteration if isinstance(data, _utils.worker._IterableDatasetStopIteration): if self._persistent_workers: self._workers_status[data.worker_id] = False else: self._mark_worker_as_unavailable(data.worker_id) self._try_put_index() continue
if idx != self._rcvd_idx: # Tombstone to receive later self._task_info[idx] = None if isinstance(data, ExceptionWrapper): data.reraise() return data else: del self._task_info[idx] return self._process_data(data)
def get_worker_info(): worker_info = torch.utils.data.get_worker_info() if worker_info is None: num_workers = 1 worker_id = 0 else: num_workers = worker_info.num_workers worker_id = worker_info.id return num_workers, worker_id123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import numbers
import cv2import numpy as npimport PILimport torchfrom torchvision.transforms import functional as tvf
def _is_tensor_clip(clip): return torch.is_tensor(clip) and clip.ndimension() == 4
def crop_clip(clip, min_h, min_w, h, w): if isinstance(clip[0], np.ndarray) or isinstance(clip[0], torch.Tensor): if clip[0].shape[-1] == 3: cropped = [img[min_h : min_h + h, min_w : min_w + w, :] for img in clip] else: assert clip[0].shape[0] == 3 cropped = [img[:, min_h : min_h + h, min_w : min_w + w] for img in clip]
elif isinstance(clip[0], PIL.Image.Image): cropped = [img.crop((min_w, min_h, min_w + w, min_h + h)) for img in clip]
else: raise TypeError( "Expected numpy.ndarray or PIL.Image or torch.Tensor):" + "but got list of {0}".format(type(clip[0])) ) return cropped
def resize_clip(clip, size, interpolation="bilinear"): if isinstance(clip[0], np.ndarray) or isinstance(clip[0], torch.Tensor): if isinstance(size, numbers.Number): if clip[0].shape[-1] == 3: im_h, im_w, im_c = clip[0].shape else: assert clip[0].shape[0] == 3 im_c, im_h, im_w = clip[0].shape # Min spatial dim already matches minimal size if (im_w <= im_h and im_w == size) or (im_h <= im_w and im_h == size): return clip new_h, new_w = get_resize_sizes(im_h, im_w, size) size = (new_w, new_h) else: size = size[0], size[1]
if isinstance(clip[0], np.ndarray): if interpolation == "bilinear": np_inter = cv2.INTER_LINEAR else: np_inter = cv2.INTER_NEAREST scaled = [cv2.resize(img, size, interpolation=np_inter) for img in clip] else: # isinstance(clip[0], torch.Tensor) if interpolation == "bilinear": np_inter = tvf.InterpolationMode.BILINEAR else: np_inter = tvf.InterpolationMode.NEAREST size = (size[1], size[0]) # torchvision transformers expect the size in (h, w) order. scaled = [tvf.resize(img, size, interpolation=np_inter) for img in clip] elif isinstance(clip[0], PIL.Image.Image): if isinstance(size, numbers.Number): im_w, im_h = clip[0].size # Min spatial dim already matches minimal size if (im_w <= im_h and im_w == size) or (im_h <= im_w and im_h == size): return clip new_h, new_w = get_resize_sizes(im_h, im_w, size) size = (new_w, new_h) else: size = size[1], size[0] if interpolation == "bilinear": pil_inter = PIL.Image.BILINEAR else: pil_inter = PIL.Image.NEAREST scaled = [img.resize(size, pil_inter) for img in clip] else: raise TypeError( "Expected numpy.ndarray or PIL.Image or torch.Tensor" + "but got list of {0}".format(type(clip[0])) ) return scaled
def get_resize_sizes(im_h, im_w, size): if im_w < im_h: ow = size oh = int(size * im_h / im_w) else: oh = size ow = int(size * im_w / im_h) return oh, ow
def normalize(clip, mean, std, inplace=False): if not _is_tensor_clip(clip): raise TypeError("tensor is not a torch clip.")
if not inplace: clip = clip.clone()
dtype = clip.dtype mean = torch.as_tensor(mean, dtype=dtype, device=clip.device) std = torch.as_tensor(std, dtype=dtype, device=clip.device) clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None])
return clip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170# Copyright (c) Meta Platforms, Inc. and affiliates.
# Copyright 2020 Ross Wightman
# Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# This implementation is based on# https://github.com/rwightman/pytorch-image-models/blob/master/timm/data/random_erasing.py# published under an Apache License 2.0.
import mathimport random
import torch
def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float32, device="cuda"): # NOTE I've seen CUDA illegal memory access errors being caused by the normal_() # paths, flip the order so normal is run on CPU if this becomes a problem # Issue has been fixed in master https://github.com/pytorch/pytorch/issues/19508 if per_pixel: return torch.empty(patch_size, dtype=dtype, device=device).normal_() elif rand_color: return torch.empty((patch_size[0], 1, 1), dtype=dtype, device=device).normal_() else: return torch.zeros((patch_size[0], 1, 1), dtype=dtype, device=device)
class RandomErasing: """Randomly selects a rectangle region in an image and erases its pixels. 'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/pdf/1708.04896.pdf This variant of RandomErasing is intended to be applied to either a batch or single image tensor after it has been normalized by dataset mean and std. Args: probability: Probability that the Random Erasing operation will be performed. min_area: Minimum percentage of erased area wrt input image area. max_area: Maximum percentage of erased area wrt input image area. min_aspect: Minimum aspect ratio of erased area. mode: pixel color mode, one of 'const', 'rand', or 'pixel' 'const' - erase block is constant color of 0 for all channels 'rand' - erase block is same per-channel random (normal) color 'pixel' - erase block is per-pixel random (normal) color max_count: maximum number of erasing blocks per image, area per box is scaled by count. per-image count is randomly chosen between 1 and this value. """
def __init__( self, probability=0.5, min_area=0.02, max_area=1 / 3, min_aspect=0.3, max_aspect=None, mode="const", min_count=1, max_count=None, num_splits=0, device="cuda", cube=True, ): self.probability = probability self.min_area = min_area self.max_area = max_area max_aspect = max_aspect or 1 / min_aspect self.log_aspect_ratio = (math.log(min_aspect), math.log(max_aspect)) self.min_count = min_count self.max_count = max_count or min_count self.num_splits = num_splits mode = mode.lower() self.rand_color = False self.per_pixel = False self.cube = cube if mode == "rand": self.rand_color = True # per block random normal elif mode == "pixel": self.per_pixel = True # per pixel random normal else: assert not mode or mode == "const" self.device = device
def _erase(self, img, chan, img_h, img_w, dtype): if random.random() > self.probability: return area = img_h * img_w count = self.min_count if self.min_count == self.max_count else random.randint(self.min_count, self.max_count) for _ in range(count): for _ in range(10): target_area = random.uniform(self.min_area, self.max_area) * area / count aspect_ratio = math.exp(random.uniform(*self.log_aspect_ratio)) h = int(round(math.sqrt(target_area * aspect_ratio))) w = int(round(math.sqrt(target_area / aspect_ratio))) if w < img_w and h < img_h: top = random.randint(0, img_h - h) left = random.randint(0, img_w - w) img[:, top : top + h, left : left + w] = _get_pixels( self.per_pixel, self.rand_color, (chan, h, w), dtype=dtype, device=self.device, ) break
def _erase_cube( self, img, batch_start, batch_size, chan, img_h, img_w, dtype, ): if random.random() > self.probability: return area = img_h * img_w count = self.min_count if self.min_count == self.max_count else random.randint(self.min_count, self.max_count) for _ in range(count): for _ in range(100): target_area = random.uniform(self.min_area, self.max_area) * area / count aspect_ratio = math.exp(random.uniform(*self.log_aspect_ratio)) h = int(round(math.sqrt(target_area * aspect_ratio))) w = int(round(math.sqrt(target_area / aspect_ratio))) if w < img_w and h < img_h: top = random.randint(0, img_h - h) left = random.randint(0, img_w - w) for i in range(batch_start, batch_size): img_instance = img[i] img_instance[:, top : top + h, left : left + w] = _get_pixels( self.per_pixel, self.rand_color, (chan, h, w), dtype=dtype, device=self.device, ) break
def __call__(self, input): if len(input.size()) == 3: self._erase(input, *input.size(), input.dtype) else: batch_size, chan, img_h, img_w = input.size() # skip first slice of batch if num_splits is set (for clean portion of samples) batch_start = batch_size // self.num_splits if self.num_splits > 1 else 0 if self.cube: self._erase_cube( input, batch_start, batch_size, chan, img_h, img_w, input.dtype, ) else: for i in range(batch_start, batch_size): self._erase(input[i], chan, img_h, img_w, input.dtype) return input123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import mathimport numbersimport random
import numpy as npimport PILimport torchimport torchvisionimport torchvision.transforms.functional as Ffrom PIL import Imagefrom torch import Tensorfrom torchvision import transforms
import src.datasets.utils.video.functional as FFfrom src.datasets.utils.video.randaugment import rand_augment_transform
_pil_interpolation_to_str = { Image.NEAREST: "PIL.Image.NEAREST", Image.BILINEAR: "PIL.Image.BILINEAR", Image.BICUBIC: "PIL.Image.BICUBIC", Image.LANCZOS: "PIL.Image.LANCZOS", Image.HAMMING: "PIL.Image.HAMMING", Image.BOX: "PIL.Image.BOX",}
_RANDOM_INTERPOLATION = (Image.BILINEAR, Image.BICUBIC)PAD_FRAME_METHODS = ["circulant"]
def _pil_interp(method): if method == "bicubic": return Image.BICUBIC elif method == "lanczos": return Image.LANCZOS elif method == "hamming": return Image.HAMMING else: return Image.BILINEAR
def random_short_side_scale_jitter(images, min_size, max_size, boxes=None, inverse_uniform_sampling=False): """ Perform a spatial short scale jittering on the given images and corresponding boxes. Args: images (tensor): images to perform scale jitter. Dimension is `num frames` x `channel` x `height` x `width`. min_size (int): the minimal size to scale the frames. max_size (int): the maximal size to scale the frames. boxes (ndarray): optional. Corresponding boxes to images. Dimension is `num boxes` x 4. inverse_uniform_sampling (bool): if True, sample uniformly in [1 / max_scale, 1 / min_scale] and take a reciprocal to get the scale. If False, take a uniform sample from [min_scale, max_scale]. Returns: (tensor): the scaled images with dimension of `num frames` x `channel` x `new height` x `new width`. (ndarray or None): the scaled boxes with dimension of `num boxes` x 4. """ if inverse_uniform_sampling: size = int(round(1.0 / np.random.uniform(1.0 / max_size, 1.0 / min_size))) else: size = int(round(np.random.uniform(min_size, max_size)))
height = images.shape[2] width = images.shape[3] if (width <= height and width == size) or (height <= width and height == size): return images, boxes new_width = size new_height = size if width < height: new_height = int(math.floor((float(height) / width) * size)) if boxes is not None: boxes = boxes * float(new_height) / height else: new_width = int(math.floor((float(width) / height) * size)) if boxes is not None: boxes = boxes * float(new_width) / width
return ( torch.nn.functional.interpolate( images, size=(new_height, new_width), mode="bilinear", align_corners=False, ), boxes, )
def crop_boxes(boxes, x_offset, y_offset): """ Peform crop on the bounding boxes given the offsets. Args: boxes (ndarray or None): bounding boxes to peform crop. The dimension is `num boxes` x 4. x_offset (int): cropping offset in the x axis. y_offset (int): cropping offset in the y axis. Returns: cropped_boxes (ndarray or None): the cropped boxes with dimension of `num boxes` x 4. """ cropped_boxes = boxes.copy() cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset
return cropped_boxes
def random_crop(images, size, boxes=None): """ Perform random spatial crop on the given images and corresponding boxes. Args: images (tensor): images to perform random crop. The dimension is `num frames` x `channel` x `height` x `width`. size (int): the size of height and width to crop on the image. boxes (ndarray or None): optional. Corresponding boxes to images. Dimension is `num boxes` x 4. Returns: cropped (tensor): cropped images with dimension of `num frames` x `channel` x `size` x `size`. cropped_boxes (ndarray or None): the cropped boxes with dimension of `num boxes` x 4. """ if images.shape[2] == size and images.shape[3] == size: return images height = images.shape[2] width = images.shape[3] y_offset = 0 if height > size: y_offset = int(np.random.randint(0, height - size)) x_offset = 0 if width > size: x_offset = int(np.random.randint(0, width - size)) cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size]
cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None
return cropped, cropped_boxes
def horizontal_flip(prob, images, boxes=None): """ Perform horizontal flip on the given images and corresponding boxes. Args: prob (float): probility to flip the images. images (tensor): images to perform horizontal flip, the dimension is `num frames` x `channel` x `height` x `width`. boxes (ndarray or None): optional. Corresponding boxes to images. Dimension is `num boxes` x 4. Returns: images (tensor): images with dimension of `num frames` x `channel` x `height` x `width`. flipped_boxes (ndarray or None): the flipped boxes with dimension of `num boxes` x 4. """ if boxes is None: flipped_boxes = None else: flipped_boxes = boxes.copy()
if np.random.uniform() < prob: images = images.flip((-1))
if len(images.shape) == 3: width = images.shape[2] elif len(images.shape) == 4: width = images.shape[3] else: raise NotImplementedError("Dimension does not supported") if boxes is not None: flipped_boxes[:, [0, 2]] = width - boxes[:, [2, 0]] - 1
return images, flipped_boxes
def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None): """ Perform uniform spatial sampling on the images and corresponding boxes. Args: images (tensor): images to perform uniform crop. The dimension is `num frames` x `channel` x `height` x `width`. size (int): size of height and weight to crop the images. spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width is larger than height. Or 0, 1, or 2 for top, center, and bottom crop if height is larger than width. boxes (ndarray or None): optional. Corresponding boxes to images. Dimension is `num boxes` x 4. scale_size (int): optinal. If not None, resize the images to scale_size before performing any crop. Returns: cropped (tensor): images with dimension of `num frames` x `channel` x `size` x `size`. cropped_boxes (ndarray or None): the cropped boxes with dimension of `num boxes` x 4. """ assert spatial_idx in [0, 1, 2] ndim = len(images.shape) if ndim == 3: images = images.unsqueeze(0) height = images.shape[2] width = images.shape[3]
if scale_size is not None: if width <= height: width, height = scale_size, int(height / width * scale_size) else: width, height = int(width / height * scale_size), scale_size images = torch.nn.functional.interpolate( images, size=(height, width), mode="bilinear", align_corners=False, )
y_offset = int(math.ceil((height - size) / 2)) x_offset = int(math.ceil((width - size) / 2))
if height > width: if spatial_idx == 0: y_offset = 0 elif spatial_idx == 2: y_offset = height - size else: if spatial_idx == 0: x_offset = 0 elif spatial_idx == 2: x_offset = width - size cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size] cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None if ndim == 3: cropped = cropped.squeeze(0) return cropped, cropped_boxes
def clip_boxes_to_image(boxes, height, width): """ Clip an array of boxes to an image with the given height and width. Args: boxes (ndarray): bounding boxes to perform clipping. Dimension is `num boxes` x 4. height (int): given image height. width (int): given image width. Returns: clipped_boxes (ndarray): the clipped boxes with dimension of `num boxes` x 4. """ clipped_boxes = boxes.copy() clipped_boxes[:, [0, 2]] = np.minimum(width - 1.0, np.maximum(0.0, boxes[:, [0, 2]])) clipped_boxes[:, [1, 3]] = np.minimum(height - 1.0, np.maximum(0.0, boxes[:, [1, 3]])) return clipped_boxes
def blend(images1, images2, alpha): """ Blend two images with a given weight alpha. Args: images1 (tensor): the first images to be blended, the dimension is `num frames` x `channel` x `height` x `width`. images2 (tensor): the second images to be blended, the dimension is `num frames` x `channel` x `height` x `width`. alpha (float): the blending weight. Returns: (tensor): blended images, the dimension is `num frames` x `channel` x `height` x `width`. """ return images1 * alpha + images2 * (1 - alpha)
def grayscale(images): """ Get the grayscale for the input images. The channels of images should be in order BGR. Args: images (tensor): the input images for getting grayscale. Dimension is `num frames` x `channel` x `height` x `width`. Returns: img_gray (tensor): blended images, the dimension is `num frames` x `channel` x `height` x `width`. """ # R -> 0.299, G -> 0.587, B -> 0.114. img_gray = torch.tensor(images) gray_channel = 0.299 * images[:, 2] + 0.587 * images[:, 1] + 0.114 * images[:, 0] img_gray[:, 0] = gray_channel img_gray[:, 1] = gray_channel img_gray[:, 2] = gray_channel return img_gray
def color_jitter(images, img_brightness=0, img_contrast=0, img_saturation=0): """ Perfrom a color jittering on the input images. The channels of images should be in order BGR. Args: images (tensor): images to perform color jitter. Dimension is `num frames` x `channel` x `height` x `width`. img_brightness (float): jitter ratio for brightness. img_contrast (float): jitter ratio for contrast. img_saturation (float): jitter ratio for saturation. Returns: images (tensor): the jittered images, the dimension is `num frames` x `channel` x `height` x `width`. """
jitter = [] if img_brightness != 0: jitter.append("brightness") if img_contrast != 0: jitter.append("contrast") if img_saturation != 0: jitter.append("saturation")
if len(jitter) > 0: order = np.random.permutation(np.arange(len(jitter))) for idx in range(0, len(jitter)): if jitter[order[idx]] == "brightness": images = brightness_jitter(img_brightness, images) elif jitter[order[idx]] == "contrast": images = contrast_jitter(img_contrast, images) elif jitter[order[idx]] == "saturation": images = saturation_jitter(img_saturation, images) return images
def brightness_jitter(var, images): """ Perfrom brightness jittering on the input images. The channels of images should be in order BGR. Args: var (float): jitter ratio for brightness. images (tensor): images to perform color jitter. Dimension is `num frames` x `channel` x `height` x `width`. Returns: images (tensor): the jittered images, the dimension is `num frames` x `channel` x `height` x `width`. """ alpha = 1.0 + np.random.uniform(-var, var)
img_bright = torch.zeros(images.shape) images = blend(images, img_bright, alpha) return images
def contrast_jitter(var, images): """ Perfrom contrast jittering on the input images. The channels of images should be in order BGR. Args: var (float): jitter ratio for contrast. images (tensor): images to perform color jitter. Dimension is `num frames` x `channel` x `height` x `width`. Returns: images (tensor): the jittered images, the dimension is `num frames` x `channel` x `height` x `width`. """ alpha = 1.0 + np.random.uniform(-var, var)
img_gray = grayscale(images) img_gray[:] = torch.mean(img_gray, dim=(1, 2, 3), keepdim=True) images = blend(images, img_gray, alpha) return images
def saturation_jitter(var, images): """ Perfrom saturation jittering on the input images. The channels of images should be in order BGR. Args: var (float): jitter ratio for saturation. images (tensor): images to perform color jitter. Dimension is `num frames` x `channel` x `height` x `width`. Returns: images (tensor): the jittered images, the dimension is `num frames` x `channel` x `height` x `width`. """ alpha = 1.0 + np.random.uniform(-var, var) img_gray = grayscale(images) images = blend(images, img_gray, alpha)
return images
def lighting_jitter(images, alphastd, eigval, eigvec): """ Perform AlexNet-style PCA jitter on the given images. Args: images (tensor): images to perform lighting jitter. Dimension is `num frames` x `channel` x `height` x `width`. alphastd (float): jitter ratio for PCA jitter. eigval (list): eigenvalues for PCA jitter. eigvec (list[list]): eigenvectors for PCA jitter. Returns: out_images (tensor): the jittered images, the dimension is `num frames` x `channel` x `height` x `width`. """ if alphastd == 0: return images # generate alpha1, alpha2, alpha3. alpha = np.random.normal(0, alphastd, size=(1, 3)) eig_vec = np.array(eigvec) eig_val = np.reshape(eigval, (1, 3)) rgb = np.sum( eig_vec * np.repeat(alpha, 3, axis=0) * np.repeat(eig_val, 3, axis=0), axis=1, ) out_images = torch.zeros_like(images) if len(images.shape) == 3: # C H W channel_dim = 0 elif len(images.shape) == 4: # T C H W channel_dim = 1 else: raise NotImplementedError(f"Unsupported dimension {len(images.shape)}")
for idx in range(images.shape[channel_dim]): # C H W if len(images.shape) == 3: out_images[idx] = images[idx] + rgb[2 - idx] # T C H W elif len(images.shape) == 4: out_images[:, idx] = images[:, idx] + rgb[2 - idx] else: raise NotImplementedError(f"Unsupported dimension {len(images.shape)}")
return out_images
def color_normalization(images, mean, stddev): """ Perform color nomration on the given images. Args: images (tensor): images to perform color normalization. Dimension is `num frames` x `channel` x `height` x `width`. mean (list): mean values for normalization. stddev (list): standard deviations for normalization.
Returns: out_images (tensor): the noramlized images, the dimension is `num frames` x `channel` x `height` x `width`. """ if len(images.shape) == 3: assert len(mean) == images.shape[0], "channel mean not computed properly" assert len(stddev) == images.shape[0], "channel stddev not computed properly" elif len(images.shape) == 4: assert len(mean) == images.shape[1], "channel mean not computed properly" assert len(stddev) == images.shape[1], "channel stddev not computed properly" else: raise NotImplementedError(f"Unsupported dimension {len(images.shape)}")
out_images = torch.zeros_like(images) for idx in range(len(mean)): # C H W if len(images.shape) == 3: out_images[idx] = (images[idx] - mean[idx]) / stddev[idx] elif len(images.shape) == 4: out_images[:, idx] = (images[:, idx] - mean[idx]) / stddev[idx] else: raise NotImplementedError(f"Unsupported dimension {len(images.shape)}") return out_images
def _get_param_spatial_crop(scale, ratio, height, width, num_repeat=10, log_scale=True, switch_hw=False): """ Given scale, ratio, height and width, return sampled coordinates of the videos. """ for _ in range(num_repeat): area = height * width target_area = random.uniform(*scale) * area if log_scale: log_ratio = (math.log(ratio[0]), math.log(ratio[1])) aspect_ratio = math.exp(random.uniform(*log_ratio)) else: aspect_ratio = random.uniform(*ratio)
w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio)))
if np.random.uniform() < 0.5 and switch_hw: w, h = h, w
if 0 < w <= width and 0 < h <= height: i = random.randint(0, height - h) j = random.randint(0, width - w) return i, j, h, w
# Fallback to central crop in_ratio = float(width) / float(height) if in_ratio < min(ratio): w = width h = int(round(w / min(ratio))) elif in_ratio > max(ratio): h = height w = int(round(h * max(ratio))) else: # whole image w = width h = height i = (height - h) // 2 j = (width - w) // 2 return i, j, h, w
def random_resized_crop( images, target_height, target_width, scale=(0.8, 1.0), ratio=(3.0 / 4.0, 4.0 / 3.0),): """ Crop the given images to random size and aspect ratio. A crop of random size (default: of 0.08 to 1.0) of the original size and a random aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop is finally resized to given size. This is popularly used to train the Inception networks.
Args: images: Images to perform resizing and cropping. target_height: Desired height after cropping. target_width: Desired width after cropping. scale: Scale range of Inception-style area based random resizing. ratio: Aspect ratio range of Inception-style area based random resizing. """
height = images.shape[2] width = images.shape[3]
i, j, h, w = _get_param_spatial_crop(scale, ratio, height, width) cropped = images[:, :, i : i + h, j : j + w] return torch.nn.functional.interpolate( cropped, size=(target_height, target_width), mode="bilinear", align_corners=False, )
def random_resized_crop_with_shift( images, target_height, target_width, scale=(0.8, 1.0), ratio=(3.0 / 4.0, 4.0 / 3.0),): """ This is similar to random_resized_crop. However, it samples two different boxes (for cropping) for the first and last frame. It then linearly interpolates the two boxes for other frames.
Args: images: Images to perform resizing and cropping. target_height: Desired height after cropping. target_width: Desired width after cropping. scale: Scale range of Inception-style area based random resizing. ratio: Aspect ratio range of Inception-style area based random resizing. """ t = images.shape[1] height = images.shape[2] width = images.shape[3]
i, j, h, w = _get_param_spatial_crop(scale, ratio, height, width) i_, j_, h_, w_ = _get_param_spatial_crop(scale, ratio, height, width) i_s = [int(i) for i in torch.linspace(i, i_, steps=t).tolist()] j_s = [int(i) for i in torch.linspace(j, j_, steps=t).tolist()] h_s = [int(i) for i in torch.linspace(h, h_, steps=t).tolist()] w_s = [int(i) for i in torch.linspace(w, w_, steps=t).tolist()] out = torch.zeros((3, t, target_height, target_width)) for ind in range(t): out[:, ind : ind + 1, :, :] = torch.nn.functional.interpolate( images[ :, ind : ind + 1, i_s[ind] : i_s[ind] + h_s[ind], j_s[ind] : j_s[ind] + w_s[ind], ], size=(target_height, target_width), mode="bilinear", align_corners=False, ) return out
def create_random_augment( input_size, auto_augment=None, interpolation="bilinear",): """ Get video randaug transform.
Args: input_size: The size of the input video in tuple. auto_augment: Parameters for randaug. An example: "rand-m7-n4-mstd0.5-inc1" (m is the magnitude and n is the number of operations to apply). interpolation: Interpolation method. """ if isinstance(input_size, tuple): img_size = input_size[-2:] else: img_size = input_size
if auto_augment: assert isinstance(auto_augment, str) if isinstance(img_size, tuple): img_size_min = min(img_size) else: img_size_min = img_size aa_params = {"translate_const": int(img_size_min * 0.45)} if interpolation and interpolation != "random": aa_params["interpolation"] = _pil_interp(interpolation) if auto_augment.startswith("rand"): return transforms.Compose([rand_augment_transform(auto_augment, aa_params)]) raise NotImplementedError
def random_sized_crop_img( im, size, jitter_scale=(0.08, 1.0), jitter_aspect=(3.0 / 4.0, 4.0 / 3.0), max_iter=10,): """ Performs Inception-style cropping (used for training). """ assert len(im.shape) == 3, "Currently only support image for random_sized_crop" h, w = im.shape[1:3] i, j, h, w = _get_param_spatial_crop( scale=jitter_scale, ratio=jitter_aspect, height=h, width=w, num_repeat=max_iter, log_scale=False, switch_hw=True, ) cropped = im[:, i : i + h, j : j + w] return torch.nn.functional.interpolate( cropped.unsqueeze(0), size=(size, size), mode="bilinear", align_corners=False, ).squeeze(0)
def circulant_frame_padding(video: Tensor, total_frames: int) -> Tensor: """ Applies circulant frame padding (repeating the video) to a specified size.
Args: video: The input video to be padded. Expected (C, T, H, W) total_frames: The number of frames after padding.
Returns The video padded to total_frames. """ start_frames = video.shape[1] if start_frames == total_frames: return video
num_repeats = total_frames // start_frames + (total_frames % start_frames > 0)
return video.repeat((1, num_repeats) + (1,) * (video.ndim - 2))[:, :total_frames]
def frame_pad(video: Tensor, total_frames: int, pad_frame_method: str) -> Tensor: if pad_frame_method not in PAD_FRAME_METHODS: raise ValueError(f"Unrecognized pad_frame_method {pad_frame_method}")
if pad_frame_method == "circulant": return circulant_frame_padding(video, total_frames)
return None
# The following code are modified based on timm lib, we will replace the following# contents with dependency from PyTorchVideo.# https://github.com/facebookresearch/pytorchvideoclass RandomResizedCropAndInterpolation: """Crop the given PIL Image to random size and aspect ratio with random interpolation. A crop of random size (default: of 0.08 to 1.0) of the original size and a random aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop is finally resized to given size. This is popularly used to train the Inception networks. Args: size: expected output size of each edge scale: range of size of the origin size cropped ratio: range of aspect ratio of the origin aspect ratio cropped interpolation: Default: PIL.Image.BILINEAR """
def __init__( self, size, scale=(0.08, 1.0), ratio=(3.0 / 4.0, 4.0 / 3.0), interpolation="bilinear", ): if isinstance(size, tuple): self.size = size else: self.size = (size, size) if (scale[0] > scale[1]) or (ratio[0] > ratio[1]): print("range should be of kind (min, max)")
if interpolation == "random": self.interpolation = _RANDOM_INTERPOLATION else: self.interpolation = _pil_interp(interpolation) self.scale = scale self.ratio = ratio
@staticmethod def get_params(img, scale, ratio): """Get parameters for ``crop`` for a random sized crop. Args: img (PIL Image): Image to be cropped. scale (tuple): range of size of the origin size cropped ratio (tuple): range of aspect ratio of the origin aspect ratio cropped Returns: tuple: params (i, j, h, w) to be passed to ``crop`` for a random sized crop. """ area = img.size[0] * img.size[1]
for _ in range(10): target_area = random.uniform(*scale) * area log_ratio = (math.log(ratio[0]), math.log(ratio[1])) aspect_ratio = math.exp(random.uniform(*log_ratio))
w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio)))
if w <= img.size[0] and h <= img.size[1]: i = random.randint(0, img.size[1] - h) j = random.randint(0, img.size[0] - w) return i, j, h, w
# Fallback to central crop in_ratio = img.size[0] / img.size[1] if in_ratio < min(ratio): w = img.size[0] h = int(round(w / min(ratio))) elif in_ratio > max(ratio): h = img.size[1] w = int(round(h * max(ratio))) else: # whole image w = img.size[0] h = img.size[1] i = (img.size[1] - h) // 2 j = (img.size[0] - w) // 2 return i, j, h, w
def __call__(self, img): """ Args: img (PIL Image): Image to be cropped and resized. Returns: PIL Image: Randomly cropped and resized image. """ i, j, h, w = self.get_params(img, self.scale, self.ratio) if isinstance(self.interpolation, (tuple, list)): interpolation = random.choice(self.interpolation) else: interpolation = self.interpolation return F.resized_crop(img, i, j, h, w, self.size, interpolation)
def __repr__(self): if isinstance(self.interpolation, (tuple, list)): interpolate_str = " ".join([_pil_interpolation_to_str[x] for x in self.interpolation]) else: interpolate_str = _pil_interpolation_to_str[self.interpolation] format_string = self.__class__.__name__ + "(size={0}".format(self.size) format_string += ", scale={0}".format(tuple(round(s, 4) for s in self.scale)) format_string += ", ratio={0}".format(tuple(round(r, 4) for r in self.ratio)) format_string += ", interpolation={0})".format(interpolate_str) return format_string
class Compose(object): """Composes several transforms Args: transforms (list of ``Transform`` objects): list of transforms to compose """
def __init__(self, transforms): self.transforms = transforms
def __call__(self, clip): for t in self.transforms: clip = t(clip) return clip
class RandomHorizontalFlip(object): """Horizontally flip the list of given images randomly with a probability 0.5 """
def __call__(self, clip): """ Args: img (PIL.Image or numpy.ndarray): List of images to be cropped in format (h, w, c) in numpy.ndarray Returns: PIL.Image or numpy.ndarray: Randomly flipped clip """ if random.random() < 0.5: if isinstance(clip[0], np.ndarray): return [np.fliplr(img) for img in clip] elif isinstance(clip[0], PIL.Image.Image): return [img.transpose(PIL.Image.FLIP_LEFT_RIGHT) for img in clip] else: raise TypeError("Expected numpy.ndarray or PIL.Image" + " but got list of {0}".format(type(clip[0]))) return clip
class RandomResize(object): """Resizes a list of (H x W x C) numpy.ndarray to the final size The larger the original image is, the more times it takes to interpolate Args: interpolation (str): Can be one of 'nearest', 'bilinear' defaults to nearest size (tuple): (widht, height) """
def __init__(self, ratio=(3.0 / 4.0, 4.0 / 3.0), interpolation="nearest"): self.ratio = ratio self.interpolation = interpolation
def __call__(self, clip): scaling_factor = random.uniform(self.ratio[0], self.ratio[1])
if isinstance(clip[0], np.ndarray): im_h, im_w, im_c = clip[0].shape elif isinstance(clip[0], PIL.Image.Image): im_w, im_h = clip[0].size
new_w = int(im_w * scaling_factor) new_h = int(im_h * scaling_factor) new_size = (new_w, new_h) resized = FF.resize_clip(clip, new_size, interpolation=self.interpolation) return resized
class Resize(object): """Resizes a list of (H x W x C) numpy.ndarray to the final size The larger the original image is, the more times it takes to interpolate Args: interpolation (str): Can be one of 'nearest', 'bilinear' defaults to nearest size (tuple): (widht, height) """
def __init__(self, size, interpolation="nearest"): self.size = size self.interpolation = interpolation
def __call__(self, clip): resized = FF.resize_clip(clip, self.size, interpolation=self.interpolation) return resized
class RandomCrop(object): """Extract random crop at the same location for a list of images Args: size (sequence or int): Desired output size for the crop in format (h, w) """
def __init__(self, size): if isinstance(size, numbers.Number): size = (size, size)
self.size = size
def __call__(self, clip): """ Args: img (PIL.Image or numpy.ndarray): List of images to be cropped in format (h, w, c) in numpy.ndarray Returns: PIL.Image or numpy.ndarray: Cropped list of images """ h, w = self.size if isinstance(clip[0], np.ndarray): im_h, im_w, im_c = clip[0].shape elif isinstance(clip[0], PIL.Image.Image): im_w, im_h = clip[0].size else: raise TypeError("Expected numpy.ndarray or PIL.Image" + "but got list of {0}".format(type(clip[0]))) if w > im_w or h > im_h: error_msg = ( "Initial image size should be larger then " "cropped size but got cropped sizes : ({w}, {h}) while " "initial image is ({im_w}, {im_h})".format(im_w=im_w, im_h=im_h, w=w, h=h) ) raise ValueError(error_msg)
x1 = random.randint(0, im_w - w) y1 = random.randint(0, im_h - h) cropped = FF.crop_clip(clip, y1, x1, h, w)
return cropped
class ThreeCrop(object): """Extract random crop at the same location for a list of images Args: size (sequence or int): Desired output size for the crop in format (h, w) """
def __init__(self, size): if isinstance(size, numbers.Number): size = (size, size)
self.size = size
def __call__(self, clip): """ Args: img (PIL.Image or numpy.ndarray): List of images to be cropped in format (h, w, c) in numpy.ndarray Returns: PIL.Image or numpy.ndarray: Cropped list of images """ h, w = self.size if isinstance(clip[0], np.ndarray): im_h, im_w, im_c = clip[0].shape elif isinstance(clip[0], PIL.Image.Image): im_w, im_h = clip[0].size else: raise TypeError("Expected numpy.ndarray or PIL.Image" + "but got list of {0}".format(type(clip[0]))) if w != im_w and h != im_h: clip = FF.resize_clip(clip, self.size, interpolation="bilinear") im_h, im_w, im_c = clip[0].shape
step = np.max((np.max((im_w, im_h)) - self.size[0]) // 2, 0) cropped = [] for i in range(3): if im_h > self.size[0]: x1 = 0 y1 = i * step cropped.extend(FF.crop_clip(clip, y1, x1, h, w)) else: x1 = i * step y1 = 0 cropped.extend(FF.crop_clip(clip, y1, x1, h, w)) return cropped
class RandomRotation(object): """Rotate entire clip randomly by a random angle within given bounds Args: degrees (sequence or int): Range of degrees to select from If degrees is a number instead of sequence like (min, max), the range of degrees, will be (-degrees, +degrees). """
def __init__(self, degrees): if isinstance(degrees, numbers.Number): if degrees < 0: raise ValueError("If degrees is a single number," "must be positive") degrees = (-degrees, degrees) else: if len(degrees) != 2: raise ValueError("If degrees is a sequence," "it must be of len 2.")
self.degrees = degrees
def __call__(self, clip): """ Args: img (PIL.Image or numpy.ndarray): List of images to be cropped in format (h, w, c) in numpy.ndarray Returns: PIL.Image or numpy.ndarray: Cropped list of images """ import skimage
angle = random.uniform(self.degrees[0], self.degrees[1]) if isinstance(clip[0], np.ndarray): rotated = [skimage.transform.rotate(img, angle) for img in clip] elif isinstance(clip[0], PIL.Image.Image): rotated = [img.rotate(angle) for img in clip] else: raise TypeError("Expected numpy.ndarray or PIL.Image" + "but got list of {0}".format(type(clip[0])))
return rotated
class CenterCrop(object): """Extract center crop at the same location for a list of images Args: size (sequence or int): Desired output size for the crop in format (h, w) """
def __init__(self, size): if isinstance(size, numbers.Number): size = (size, size)
self.size = size
def __call__(self, clip): """ Args: img (PIL.Image or numpy.ndarray): List of images to be cropped in format (h, w, c) in numpy.ndarray Returns: PIL.Image or numpy.ndarray: Cropped list of images """ h, w = self.size if isinstance(clip[0], np.ndarray) or isinstance(clip[0], torch.Tensor): if clip[0].shape[-1] == 3: im_h, im_w, im_c = clip[0].shape else: assert clip[0].shape[0] == 3 im_c, im_h, im_w = clip[0].shape elif isinstance(clip[0], PIL.Image.Image): im_w, im_h = clip[0].size else: raise TypeError( "Expected numpy.ndarray or PIL.Image or torch.Tensor" + "but got list of {0}".format(type(clip[0])) ) if w > im_w or h > im_h: error_msg = ( "Initial image size should be larger then " "cropped size but got cropped sizes : ({w}, {h}) while " "initial image is ({im_w}, {im_h})".format(im_w=im_w, im_h=im_h, w=w, h=h) ) raise ValueError(error_msg)
x1 = int(round((im_w - w) / 2.0)) y1 = int(round((im_h - h) / 2.0)) cropped = FF.crop_clip(clip, y1, x1, h, w)
return cropped
class ColorJitter(object): """ Randomly change the brightness, contrast and saturation and hue of the clip
Args: brightness (float): How much to jitter brightness. brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]. contrast (float): How much to jitter contrast. contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]. saturation (float): How much to jitter saturation. saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation]. hue(float): How much to jitter hue. hue_factor is chosen uniformly from [-hue, hue]. Should be >=0 and <= 0.5. """
def __init__(self, brightness=0, contrast=0, saturation=0, hue=0): self.brightness = brightness self.contrast = contrast self.saturation = saturation self.hue = hue
def get_params(self, brightness, contrast, saturation, hue): if brightness > 0: brightness_factor = random.uniform(max(0, 1 - brightness), 1 + brightness) else: brightness_factor = None
if contrast > 0: contrast_factor = random.uniform(max(0, 1 - contrast), 1 + contrast) else: contrast_factor = None
if saturation > 0: saturation_factor = random.uniform(max(0, 1 - saturation), 1 + saturation) else: saturation_factor = None
if hue > 0: hue_factor = random.uniform(-hue, hue) else: hue_factor = None return brightness_factor, contrast_factor, saturation_factor, hue_factor
def __call__(self, clip): """ Args: clip (list): list of PIL.Image Returns: list PIL.Image : list of transformed PIL.Image """ if isinstance(clip[0], np.ndarray): raise TypeError("Color jitter not yet implemented for numpy arrays") elif isinstance(clip[0], PIL.Image.Image): brightness, contrast, saturation, hue = self.get_params( self.brightness, self.contrast, self.saturation, self.hue )
# Create img transform function sequence img_transforms = [] if brightness is not None: img_transforms.append(lambda img: torchvision.transforms.functional.adjust_brightness(img, brightness)) if saturation is not None: img_transforms.append(lambda img: torchvision.transforms.functional.adjust_saturation(img, saturation)) if hue is not None: img_transforms.append(lambda img: torchvision.transforms.functional.adjust_hue(img, hue)) if contrast is not None: img_transforms.append(lambda img: torchvision.transforms.functional.adjust_contrast(img, contrast)) random.shuffle(img_transforms)
# Apply to all images jittered_clip = [] for img in clip: for func in img_transforms: jittered_img = func(img) jittered_clip.append(jittered_img)
else: raise TypeError("Expected numpy.ndarray or PIL.Image" + "but got list of {0}".format(type(clip[0]))) return jittered_clip
class Normalize(object): """Normalize a clip with mean and standard deviation. Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels, this transform will normalize each channel of the input ``torch.*Tensor`` i.e. ``input[channel] = (input[channel] - mean[channel]) / std[channel]`` .. note:: This transform acts out of place, i.e., it does not mutates the input tensor. Args: mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channel. """
def __init__(self, mean, std): self.mean = mean self.std = std
def __call__(self, clip): """ Args: clip (Tensor): Tensor clip of size (T, C, H, W) to be normalized. Returns: Tensor: Normalized Tensor clip. """ return FF.normalize(clip, self.mean, self.std)
def __repr__(self): return self.__class__.__name__ + "(mean={0}, std={1})".format(self.mean, self.std)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import numpy as npimport torchfrom PIL import Image
def convert_img(img): """Converts (H, W, C) numpy.ndarray to (C, W, H) format""" if len(img.shape) == 3: img = img.transpose(2, 0, 1) if len(img.shape) == 2: img = np.expand_dims(img, 0) return img
class ClipToTensor(object): """Convert a list of m (H x W x C) numpy.ndarrays in the range [0, 255] to a torch.FloatTensor of shape (C x m x H x W) in the range [0, 1.0] """
def __init__(self, channel_nb=3, div_255=True, numpy=False): self.channel_nb = channel_nb self.div_255 = div_255 self.numpy = numpy
def __call__(self, clip): """ Args: clip (list of numpy.ndarray): clip (list of images) to be converted to tensor. """ # Retrieve shape if isinstance(clip[0], np.ndarray): h, w, ch = clip[0].shape assert ch == self.channel_nb, "Got {0} instead of 3 channels".format(ch) elif isinstance(clip[0], Image.Image): w, h = clip[0].size elif isinstance(clip[0], torch.Tensor): tensor_clip = torch.stack(clip) # Converting (T, C, H, W) -> (C, T, H, W) to match what `convert_img` followed by # `np_clip[:, img_idx, :, :] = img` does for other data types. tensor_clip = tensor_clip.permute(1, 0, 2, 3) if not isinstance(tensor_clip, torch.FloatTensor): tensor_clip = tensor_clip.float() if self.div_255: tensor_clip = torch.div(tensor_clip, 255) return tensor_clip else: raise TypeError( "Expected numpy.ndarray or PIL.Image or torch.Tensor\ but got list of {0}".format( type(clip[0]) ) )
np_clip = np.zeros([self.channel_nb, len(clip), int(h), int(w)])
# Convert for img_idx, img in enumerate(clip): if isinstance(img, np.ndarray): pass elif isinstance(img, Image.Image): img = np.array(img, copy=False) else: raise TypeError( "Expected numpy.ndarray or PIL.Image\ but got list of {0}".format( type(clip[0]) ) ) img = convert_img(img) np_clip[:, img_idx, :, :] = img
if self.numpy: if self.div_255: np_clip = np_clip / 255.0 return np_clip
else: tensor_clip = torch.from_numpy(np_clip)
if not isinstance(tensor_clip, torch.FloatTensor): tensor_clip = tensor_clip.float() if self.div_255: tensor_clip = torch.div(tensor_clip, 255) return tensor_clip
# Note this norms data to -1/1class ClipToTensor_K(object): """Convert a list of m (H x W x C) numpy.ndarrays in the range [0, 255] to a torch.FloatTensor of shape (C x m x H x W) in the range [0, 1.0] """
def __init__(self, channel_nb=3, div_255=True, numpy=False): self.channel_nb = channel_nb self.div_255 = div_255 self.numpy = numpy
def __call__(self, clip): """ Args: clip (list of numpy.ndarray): clip (list of images) to be converted to tensor. """ # Retrieve shape if isinstance(clip[0], np.ndarray): h, w, ch = clip[0].shape assert ch == self.channel_nb, "Got {0} instead of 3 channels".format(ch) elif isinstance(clip[0], Image.Image): w, h = clip[0].size else: raise TypeError( "Expected numpy.ndarray or PIL.Image\ but got list of {0}".format( type(clip[0]) ) )
np_clip = np.zeros([self.channel_nb, len(clip), int(h), int(w)])
# Convert for img_idx, img in enumerate(clip): if isinstance(img, np.ndarray): pass elif isinstance(img, Image.Image): img = np.array(img, copy=False) else: raise TypeError( "Expected numpy.ndarray or PIL.Image\ but got list of {0}".format( type(clip[0]) ) ) img = convert_img(img) np_clip[:, img_idx, :, :] = img if self.numpy: if self.div_255: np_clip = (np_clip - 127.5) / 127.5 return np_clip
else: tensor_clip = torch.from_numpy(np_clip)
if not isinstance(tensor_clip, torch.FloatTensor): tensor_clip = tensor_clip.float() if self.div_255: tensor_clip = torch.div(torch.sub(tensor_clip, 127.5), 127.5) return tensor_clip
class ToTensor(object): """Converts numpy array to tensor"""
def __call__(self, array): tensor = torch.from_numpy(array) return tensor123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import mathfrom typing import Iterator, Optional
import numpy as npimport torchfrom torch.utils.data import DistributedSampler, RandomSampler
from src.utils.logging import get_logger
logger = get_logger("WeightedSampler")
class DistributedWeightedSampler(DistributedSampler): """ This class implements a weighted sampler for distributed training. See https://pytorch.org/docs/stable/_modules/torch/utils/data/distributed.html#DistributedSampler for more details.
It shares the same interface as `torch.utils.data.DistributedSampler`. The effective change is replacing `DistributedSampler`'s `torch.randperm` for generating the sequence of indices with `numpy.random.Generator.choice`, with replacement. This allows weighted sampling and avoiding issue with `torch.randperm` when the number of samples is larger than 2^24 samples. """
def __init__( self, dataset, num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed: int = 0, drop_last: bool = False, ): logger.info(f"Using DistributedWeightedSampler with rank {rank} / {num_replicas}") assert hasattr( dataset, "sample_weights" ), "Dataset must have sample_weights property for using DistributedWeightedSampler" super().__init__( dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle, seed=seed, drop_last=drop_last, )
@property def sample_probabilities(self) -> np.ndarray: sample_weights = self.dataset.sample_weights if isinstance(sample_weights, torch.Tensor): sample_weights = sample_weights.cpu().numpy() elif isinstance(sample_weights, list): sample_weights = np.array(sample_weights) assert isinstance( sample_weights, np.ndarray ), f"sample_weights must be a numpy array, torch.Tensor, or python list; got {type(sample_weights)}" return sample_weights / np.sum(sample_weights)
def __iter__(self) -> Iterator: n = len(self.dataset)
# deterministically shuffle based on epoch and seed rng = np.random.default_rng(self.seed + self.epoch) indices = rng.choice( range(0, n), size=self.total_size, p=self.sample_probabilities, replace=True, ).tolist()
if not self.drop_last: # add extra samples to make it evenly divisible padding_size = self.total_size - len(indices) if padding_size <= len(indices): indices += indices[:padding_size] else: indices += (indices * math.ceil(padding_size / len(indices)))[:padding_size] else: # remove tail of data to make it evenly divisible indices = indices[: self.total_size] assert len(indices) == self.total_size
# subsample indices = indices[self.rank : self.total_size : self.num_replicas] assert len(indices) == self.num_samples
return iter(indices)
class MemoryEfficientDistributedWeightedSampler(DistributedSampler): """ This class implements a memory efficient version of `DistributedWeightedSampler`. It shares the same interface as `DistributedWeightedSampler`. The effective change is just-in-time sampling of the indices, instead of pre-computing them. """
def __init__( self, dataset, num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed: int = 0, ): logger.info(f"Using MemoryEfficientDistributedWeightedSampler with rank {rank} / {num_replicas}") assert hasattr( dataset, "dataset_weights" ), "Dataset must have dataset_weights property for using MemoryEfficientDistributedWeightedSampler" super().__init__( dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle, seed=seed, )
self.dataset_weights = dataset.dataset_weights self.dataset_sizes = [len(d) for d in dataset.datasets] if len(self.dataset_sizes) != len(self.dataset_weights): raise ValueError( f"Number of datasets ({len(self.dataset_sizes)}) " f"does not match number of dataset weights ({len(self.dataset_weights)})" )
if self.shuffle: self.rng = np.random.default_rng(self.seed + self.rank + self.epoch) total_weights = sum(self.dataset_weights) self.dataset_probablities = np.array([w / total_weights for w in self.dataset_weights]) else: if any([not isinstance(w, int) for w in self.dataset_weights]): raise ValueError("Dataset weights must be integers when shuffle is False")
self.dataset_orders = [] for i, w in enumerate(self.dataset_weights): self.dataset_orders.extend([i] * w)
self.drawn_samples = 0
def __iter__(self) -> Iterator: return self
def __next__(self) -> int: if self.shuffle: selected_dataset_idx = self.rng.choice(range(len(self.dataset_weights)), p=self.dataset_probablities)
# In order to avoid sampling the same example multiple times between the ranks, # we limit each rank to a subset of the total number of samples in the dataset. # For example if our dataet is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], and we have 2 ranks, # then rank 0 will ONLY sample from [0, 2, 4, 6, 8], and rank 1 from [1, 3, 5, 7, 9]. # In each iteration we first produce `in_rank_sample` which is the sample index in the rank, # based on the size of the subset which that rank can sample from. # Then we computer `sample_idx_in_dataset` for the indx of the sample in the whole dataset. # For the above example if we are sampling for rank 1, we have `self.rng.integers(5)`. # Let's assume the result is 2, then `in_rank_sample` is 2 (number "5" in the subset), # so the sample index in the whole dataset is # `in_rank_sample * self.num_replicas + self.rank`: 2 * 2 + 1 = 5.
selected_dataset_size = self.dataset_sizes[selected_dataset_idx] # 1) Getting sample index in the rank. # NOTE: this may effectively drops the last batch, # but given the sample sizes that we use this sampler with, it should not be an issue. num_samples_in_rank = selected_dataset_size // self.num_replicas in_rank_sample = self.rng.integers(num_samples_in_rank)
# 2) Getting sample index in the dataset. sample_idx_in_dataset = in_rank_sample * self.num_replicas + self.rank
else: # Iterate through the dataset orders in a round-robin fashion, offset by the rank dataset_orders_idx = (self.rank + self.drawn_samples) % len(self.dataset_orders) selected_dataset_idx = self.dataset_orders[dataset_orders_idx] # Get the sample index in the selected dataset by skipping with the num_replicas * drawn_samples sample_idx_in_dataset = (self.drawn_samples * self.num_replicas + self.rank) % self.dataset_sizes[ selected_dataset_idx ] self.drawn_samples += 1
# Getting the index of the sample in the whole dataset # For example if the total dataset has 4 datasets with sizes [10, 20, 30, 5]. # and our selected_dataset_idx=3 and sample_idx_in_dataset=5 # then the index of the sample in the whole dataset is # 10 (for dataset 1) + 20 (for dataset 1) + 5 (for sample_idx_in_dataset) = 35 # This is because the first 10 samples are from the first dataset, the next 20 are from the second dataset, # then we reach at the 3rd dataset which is the selected dataset, and the 5th sample in the 3rd dataset. sample_idx = 0 for i, d in enumerate(self.dataset_sizes): if selected_dataset_idx == i: break sample_idx += d sample_idx += sample_idx_in_dataset
return sample_idx
def safe_next(iterator): try: return next(iterator) except StopIteration: return None
class MemoryEfficientDistributedWeightedSamplerLessRepeat(DistributedSampler): """ This class implements a memory efficient version of `DistributedWeightedSampler`. It shares the same interface as `DistributedWeightedSampler`. The effective change is pre-computing the permutations of indices over a subset of total indices. This subset is the selected with picking the indices in a dataset with steps sizes equal to the world size. For example, if world size is 12 and rank is 2, for a dataset of size N, this sampler only permutes the indices in range(2, n, 12)
Compared with MemoryEfficientDistributedWeightedSampler, this will reduce the effective number of repeat. See discussions here: https://github.com/fairinternal/jepa-internal/pull/254 """
def __init__( self, dataset, num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed: int = 0, ): logger.info(f"Using MemoryEfficientDistributedWeightedSamplerLessRepeat with rank {rank} / {num_replicas}") assert hasattr( dataset, "dataset_weights" ), "Dataset must have dataset_weights property for using MemoryEfficientDistributedWeightedSamplerLessRepeat" super().__init__( dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle, seed=seed, )
self._generator = torch.Generator() self._generator.manual_seed(seed)
self.dataset_weights = dataset.dataset_weights self.dataset_sizes = [len(d) for d in dataset.datasets] if len(self.dataset_sizes) != len(self.dataset_weights): raise ValueError( f"Number of datasets ({len(self.dataset_sizes)}) " f"does not match number of dataset weights ({len(self.dataset_weights)})" )
if self.shuffle: self.rng = np.random.default_rng(self.seed + self.rank + self.epoch) total_weights = sum(self.dataset_weights) self.dataset_probablities = np.array([w / total_weights for w in self.dataset_weights])
# For each dataset we generate a permutation of the indices that will be processed by that rank. # This is going to be the subset of indices, selected by the steps sizes of the world size. logger.info(f"Generating dataset indices for rank {self.rank} / {self.num_replicas}")
# Getting a RandomSampler for indices assigned to each dataset. self.individual_dataset_sampler = [] for ids, ds in enumerate(self.dataset_sizes):
# NOTE: this may effectively drops the last batch, # but given the sample sizes that we use this sampler with, it should not be an issue. num_samples_in_rank = ds // self.num_replicas self.individual_dataset_sampler.append(self._new_sampler(num_samples_in_rank))
else: if any([not isinstance(w, int) for w in self.dataset_weights]): raise ValueError("Dataset weights must be integers when shuffle is False")
self.dataset_orders = [] for i, w in enumerate(self.dataset_weights): self.dataset_orders.extend([i] * w)
self.drawn_samples = 0
def __iter__(self) -> Iterator: return self
def _new_sampler(self, sample_size: int) -> RandomSampler: assert self.shuffle
return iter( RandomSampler( range(sample_size), generator=self._generator, ) )
def _in_rank_next_index_for_dataset(self, dataset_idx: int) -> int: assert self.shuffle
next_sampler_idx = safe_next(self.individual_dataset_sampler[dataset_idx]) if next_sampler_idx is None: # We have reached the end of the dataset, we need to reset the sampler. num_samples_in_rank = self.dataset_sizes[dataset_idx] // self.num_replicas self.individual_dataset_sampler[dataset_idx] = self._new_sampler(num_samples_in_rank) next_sampler_idx = safe_next(self.individual_dataset_sampler[dataset_idx]) assert next_sampler_idx is not None
return next_sampler_idx
def __next__(self) -> int: if self.shuffle: selected_dataset_idx = self.rng.choice(range(len(self.dataset_weights)), p=self.dataset_probablities) in_rank_sample = self._in_rank_next_index_for_dataset(selected_dataset_idx)
# 2) Getting sample index in the dataset. sample_idx_in_dataset = in_rank_sample * self.num_replicas + self.rank
else: # Iterate through the dataset orders in a round-robin fashion, offset by the rank dataset_orders_idx = (self.rank + self.drawn_samples) % len(self.dataset_orders) selected_dataset_idx = self.dataset_orders[dataset_orders_idx] # Get the sample index in the selected dataset by skipping with the num_replicas * drawn_samples sample_idx_in_dataset = (self.drawn_samples * self.num_replicas + self.rank) % self.dataset_sizes[ selected_dataset_idx ] self.drawn_samples += 1
# Getting the index of the sample in the whole dataset # For example if the total dataset has 4 datasets with sizes [10, 20, 30, 5]. # and our selected_dataset_idx=3 and sample_idx_in_dataset=5 # then the index of the sample in the whole dataset is # 10 (for dataset 1) + 20 (for dataset 1) + 5 (for sample_idx_in_dataset) = 35 # This is because the first 10 samples are from the first dataset, the next 20 are from the second dataset, # then we reach at the 3rd dataset which is the selected dataset, and the 5th sample in the 3rd dataset. sample_idx = 0 for i, d in enumerate(self.dataset_sizes): if selected_dataset_idx == i: break sample_idx += d sample_idx += sample_idx_in_dataset
return sample_idx12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# Copyright (c) Meta Platforms, Inc. and affiliates.
# Copyright The Lightning AI team.
# Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# This code originally comes from PyTorch Lighting with some light modificaitons:# https://github.com/Lightning-AI/pytorch-lightning/blob/a944e7744e57a5a2c13f3c73b9735edf2f71e329/src/lightning/fabric/utilities/seed.py
import osimport randomfrom typing import Optional
import numpy as npimport torch
from src.utils.logging import get_logger
logger = get_logger("worker_init_fn")
def _generate_seed_sequence(base_seed: int, worker_id: int, global_rank: int, count: int) -> list[int]: """Generates a sequence of seeds from a base seed, worker id and rank using the linear congruential generator (LCG) algorithm.""" # Combine base seed, worker id and rank into a unique 64-bit number combined_seed = (base_seed << 32) | (worker_id << 16) | global_rank seeds = [] for _ in range(count): # x_(n+1) = (a * x_n + c) mod m. With c=1, m=2^64 and a is D. Knuth's constant combined_seed = (combined_seed * 6364136223846793005 + 1) & ((1 << 64) - 1) seeds.append(combined_seed) return seeds
def pl_worker_init_function(worker_id: int, rank: Optional[int] = None) -> None: # pragma: no cover r"""The worker_init_fn that Lightning automatically adds to your dataloader if you previously set the seed with ``seed_everything(seed, workers=True)``.
See also the PyTorch documentation on `randomness in DataLoaders <https://pytorch.org/docs/stable/notes/randomness.html#dataloader>`_.
""" # implementation notes: https://github.com/pytorch/pytorch/issues/5059#issuecomment-817392562 if rank is None: procid = os.environ.get("SLURM_PROCID") if procid is None: logger.warning("SLURM_PROCID is not set, setting rank to 0") rank = 0 else: rank = int(procid)
process_seed = torch.initial_seed() # back out the base seed so we can use all the bits base_seed = process_seed - worker_id logger.debug( f"Initializing random number generators of process {rank} worker {worker_id} with base seed {base_seed}" ) seed_sequence = _generate_seed_sequence(base_seed, worker_id, rank, count=4) torch.manual_seed(seed_sequence[0]) # torch takes a 64-bit seed random.seed((seed_sequence[1] << 32) | seed_sequence[2]) # combine two 64-bit seeds
ss = np.random.SeedSequence([base_seed, worker_id, rank]) np_rng_seed = ss.generate_state(4)
np.random.seed(np_rng_seed)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import mathimport osimport pathlibimport warningsfrom logging import getLogger
import numpy as npimport pandas as pdimport torchimport torchvisionfrom decord import VideoReader, cpu
from src.datasets.utils.dataloader import ConcatIndices, MonitoredDataset, NondeterministicDataLoaderfrom src.datasets.utils.weighted_sampler import DistributedWeightedSamplerfrom datasets import load_datasetfrom torchvision import transforms
_GLOBAL_SEED = 0logger = getLogger()
def make_videodataset( data_paths, batch_size, frames_per_clip=8, dataset_fpcs=None, frame_step=4, duration=None, fps=None, num_clips=1, random_clip_sampling=True, allow_clip_overlap=False, filter_short_videos=False, filter_long_videos=int(10**9), transform=None, shared_transform=None, rank=0, world_size=1, datasets_weights=None, collator=None, drop_last=True, num_workers=10, pin_mem=True, persistent_workers=True, deterministic=True, log_dir=None,): dataset = VideoDataset( data_paths=data_paths, datasets_weights=datasets_weights, frames_per_clip=frames_per_clip, dataset_fpcs=dataset_fpcs, duration=duration, fps=fps, frame_step=frame_step, num_clips=num_clips, random_clip_sampling=random_clip_sampling, allow_clip_overlap=allow_clip_overlap, filter_short_videos=filter_short_videos, filter_long_videos=filter_long_videos, shared_transform=shared_transform, transform=transform, )
log_dir = pathlib.Path(log_dir) if log_dir else None if log_dir: log_dir.mkdir(parents=True, exist_ok=True) # Worker ID will replace '%w' resource_log_filename = log_dir / f"resource_file_{rank}_%w.csv" dataset = MonitoredDataset( dataset=dataset, log_filename=str(resource_log_filename), log_interval=10.0, monitor_interval=5.0, )
logger.info("VideoDataset dataset created") if datasets_weights is not None: dist_sampler = DistributedWeightedSampler(dataset, num_replicas=world_size, rank=rank, shuffle=True) else: dist_sampler = torch.utils.data.distributed.DistributedSampler( dataset, num_replicas=world_size, rank=rank, shuffle=True )
if deterministic: data_loader = torch.utils.data.DataLoader( dataset, collate_fn=collator, sampler=dist_sampler, batch_size=batch_size, drop_last=drop_last, pin_memory=pin_mem, num_workers=num_workers, persistent_workers=(num_workers > 0) and persistent_workers, ) else: data_loader = NondeterministicDataLoader( dataset, collate_fn=collator, sampler=dist_sampler, batch_size=batch_size, drop_last=drop_last, pin_memory=pin_mem, num_workers=num_workers, persistent_workers=(num_workers > 0) and persistent_workers, ) logger.info("VideoDataset unsupervised data loader created")
return dataset, data_loader, dist_sampler
class VideoDataset(torch.utils.data.Dataset): """Video classification dataset."""
def __init__( self, data_paths, datasets_weights=None, frames_per_clip=16, fps=None, dataset_fpcs=None, frame_step=4, num_clips=1, transform=None, shared_transform=None, random_clip_sampling=True, allow_clip_overlap=False, filter_short_videos=False, filter_long_videos=int(10**9), duration=None, # duration in seconds ): self.data_paths = data_paths self.datasets_weights = datasets_weights self.frame_step = frame_step self.num_clips = num_clips self.transform = transform self.shared_transform = shared_transform self.random_clip_sampling = random_clip_sampling self.allow_clip_overlap = allow_clip_overlap self.filter_short_videos = filter_short_videos self.filter_long_videos = filter_long_videos self.duration = duration self.fps = fps
if sum([v is not None for v in (fps, duration, frame_step)]) != 1: raise ValueError(f"Must specify exactly one of either {fps=}, {duration=}, or {frame_step=}.")
if isinstance(data_paths, str): data_paths = [data_paths]
if dataset_fpcs is None: self.dataset_fpcs = [frames_per_clip for _ in data_paths] else: if len(dataset_fpcs) != len(data_paths): raise ValueError("Frames per clip not properly specified for NFS data paths") self.dataset_fpcs = dataset_fpcs
if VideoReader is None: raise ImportError('Unable to import "decord" which is required to read videos.')
# Load video paths and labels samples, labels = [], [] self.num_samples_per_dataset = [] for data_path in self.data_paths:
if data_path[-4:] == ".csv": try: data = pd.read_csv(data_path, header=None, delimiter=" ") except pd.errors.ParserError: # In image captioning datasets where we have space, we use :: as delimiter. data = pd.read_csv(data_path, header=None, delimiter="::") samples += list(data.values[:, 0]) labels += list(data.values[:, 1]) num_samples = len(data) self.num_samples_per_dataset.append(num_samples)
elif data_path[-4:] == ".npy": data = np.load(data_path, allow_pickle=True) data = list(map(lambda x: repr(x)[1:-1], data)) samples += data labels += [0] * len(data) num_samples = len(data) self.num_samples_per_dataset.append(len(data))
self.per_dataset_indices = ConcatIndices(self.num_samples_per_dataset)
# [Optional] Weights for each sample to be used by downstream # weighted video sampler self.sample_weights = None if self.datasets_weights is not None: self.sample_weights = [] for dw, ns in zip(self.datasets_weights, self.num_samples_per_dataset): self.sample_weights += [dw / ns] * ns
self.samples = samples self.labels = labels
def __getitem__(self, index): sample = self.samples[index] loaded_sample = False # Keep trying to load videos until you find a valid sample while not loaded_sample: if not isinstance(sample, str): logger.warning("Invalid sample.") else: if sample.split(".")[-1].lower() in ("jpg", "png", "jpeg"): loaded_sample = self.get_item_image(index) else: loaded_sample = self.get_item_video(index)
if not loaded_sample: index = np.random.randint(self.__len__()) sample = self.samples[index]
return loaded_sample
def get_item_video(self, index): sample = self.samples[index] dataset_idx, _ = self.per_dataset_indices[index] frames_per_clip = self.dataset_fpcs[dataset_idx]
buffer, clip_indices = self.loadvideo_decord(sample, frames_per_clip) # [T H W 3] loaded_video = len(buffer) > 0 if not loaded_video: return
# Label/annotations for video label = self.labels[index]
def split_into_clips(video): """Split video into a list of clips""" fpc = frames_per_clip nc = self.num_clips return [video[i * fpc : (i + 1) * fpc] for i in range(nc)]
# Parse video into frames & apply data augmentations if self.shared_transform is not None: buffer = self.shared_transform(buffer) buffer = split_into_clips(buffer) if self.transform is not None: buffer = [self.transform(clip) for clip in buffer]
return buffer, label, clip_indices
def get_item_image(self, index): sample = self.samples[index] dataset_idx, _ = self.per_dataset_indices[index] fpc = self.dataset_fpcs[dataset_idx]
try: image_tensor = torchvision.io.read_image(path=sample, mode=torchvision.io.ImageReadMode.RGB) except Exception: return label = self.labels[index] clip_indices = [np.arange(start=0, stop=fpc, dtype=np.int32)]
# Expanding the input image [3, H, W] ==> [T, 3, H, W] buffer = image_tensor.unsqueeze(dim=0).repeat((fpc, 1, 1, 1)) buffer = buffer.permute((0, 2, 3, 1)) # [T, 3, H, W] ==> [T H W 3]
if self.shared_transform is not None: # Technically we can have only transform, doing this just for the sake of consistency with videos. buffer = self.shared_transform(buffer)
if self.transform is not None: buffer = [self.transform(buffer)]
return buffer, label, clip_indices
def loadvideo_decord(self, sample, fpc): """Load video content using Decord"""
fname = sample if not os.path.exists(fname): warnings.warn(f"video path not found {fname=}") return [], None
_fsize = os.path.getsize(fname) if _fsize > self.filter_long_videos: warnings.warn(f"skipping long video of size {_fsize=} (bytes)") return [], None
try: vr = VideoReader(fname, num_threads=-1, ctx=cpu(0)) except Exception: return [], None
fstp = self.frame_step if self.duration is not None or self.fps is not None: try: video_fps = math.ceil(vr.get_avg_fps()) except Exception as e: logger.warning(e)
if self.duration is not None: assert self.fps is None fstp = int(self.duration * video_fps / fpc) else: assert self.duration is None fstp = video_fps // self.fps
assert fstp is not None and fstp > 0 clip_len = int(fpc * fstp)
if self.filter_short_videos and len(vr) < clip_len: warnings.warn(f"skipping video of length {len(vr)}") return [], None
vr.seek(0) # Go to start of video before sampling frames
# Partition video into equal sized segments and sample each clip # from a different segment partition_len = len(vr) // self.num_clips
all_indices, clip_indices = [], [] for i in range(self.num_clips):
if partition_len > clip_len: # If partition_len > clip len, then sample a random window of # clip_len frames within the segment end_indx = clip_len if self.random_clip_sampling: end_indx = np.random.randint(clip_len, partition_len) start_indx = end_indx - clip_len indices = np.linspace(start_indx, end_indx, num=fpc) indices = np.clip(indices, start_indx, end_indx - 1).astype(np.int64) # -- indices = indices + i * partition_len else: # If partition overlap not allowed and partition_len < clip_len # then repeatedly append the last frame in the segment until # we reach the desired clip length if not self.allow_clip_overlap: indices = np.linspace(0, partition_len, num=partition_len // fstp) indices = np.concatenate( ( indices, np.ones(fpc - partition_len // fstp) * partition_len, ) ) indices = np.clip(indices, 0, partition_len - 1).astype(np.int64) # -- indices = indices + i * partition_len
# If partition overlap is allowed and partition_len < clip_len # then start_indx of segment i+1 will lie within segment i else: sample_len = min(clip_len, len(vr)) - 1 indices = np.linspace(0, sample_len, num=sample_len // fstp) indices = np.concatenate( ( indices, np.ones(fpc - sample_len // fstp) * sample_len, ) ) indices = np.clip(indices, 0, sample_len - 1).astype(np.int64) # -- clip_step = 0 if len(vr) > clip_len: clip_step = (len(vr) - clip_len) // (self.num_clips - 1) indices = indices + i * clip_step
clip_indices.append(indices) all_indices.extend(list(indices))
buffer = vr.get_batch(all_indices).asnumpy() return buffer, clip_indices
def __len__(self): return len(self.samples)
class MiniImagenetDataset: def __init__(self, path, transform=None): self.dataset = load_dataset(path, split="train") self.transform = transform self.num_classes = self.dataset.features['label'].num_classes # Create one-hot encoded labels for the number of classes self.one_hot_labels = torch.nn.functional.one_hot(torch.arange(self.num_classes), num_classes=self.num_classes)
if transform is None: # Define the transformations self.transform = transforms.Compose([ transforms.ToTensor(), transforms.Resize((256, 256)), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ])
def __len__(self): return len(self.dataset)
def __getitem__(self, idx): item = self.dataset[idx] image = item['image'] label = item['label']
# Convert the image to RGB format if it's not already if image.mode != 'RGB': image = image.convert('RGB')
if self.transform: image = self.transform(image) # Get the one-hot encoded label one_hot_label = self.one_hot_labels[label]
return torch.tensor(image).detach().clone(), torch.tensor(one_hot_label).detach().clone()
def make_miniimagenet( path_miniimagenet, batch_size, transform=None, shared_transform=None, data="ImageNet", collator=None, pin_mem=True, num_workers=8, world_size=1, rank=0, root_path=None, image_folder=None, training=True, drop_last=True, subset_file=None, clip_len=None, dataset_fpcs=None, frame_sample_rate=None, duration=None, fps=None, num_clips=1, random_clip_sampling=True, allow_clip_overlap=False, filter_short_videos=False, filter_long_videos=int(1e9), datasets_weights=None, persistent_workers=False, deterministic=True, log_dir=None): dataset = MiniImagenetDataset( path=path_miniimagenet, transform=transform )
logger.info("MiniImagenetDataset dataset created")
if datasets_weights is not None: dist_sampler = DistributedWeightedSampler(dataset, num_replicas=world_size, rank=rank, shuffle=True) else: dist_sampler = torch.utils.data.distributed.DistributedSampler( dataset, num_replicas=world_size, rank=rank, shuffle=True )
if deterministic: data_loader = torch.utils.data.DataLoader( dataset, collate_fn=collator, sampler=dist_sampler, batch_size=batch_size, drop_last=drop_last, pin_memory=pin_mem, num_workers=num_workers, persistent_workers=(num_workers > 0) and persistent_workers, ) else: data_loader = NondeterministicDataLoader( dataset, collate_fn=collator, sampler=dist_sampler, batch_size=batch_size, drop_last=drop_last, pin_memory=pin_mem, num_workers=num_workers, persistent_workers=(num_workers > 0) and persistent_workers, ) logger.info("MiniImagenetDataset unsupervised data loader created")
return dataset, data_loader, dist_sampler123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import mathfrom logging import getLoggerfrom multiprocessing import Valueimport torch
import torch
_GLOBAL_SEED = 0logger = getLogger()
class MaskCollator(object):
def __init__( self, cfgs_mask, dataset_fpcs, crop_size=(224, 224), patch_size=(16, 16), tubelet_size=2, ): super(MaskCollator, self).__init__()
self.mask_generators = dict() for fpc in dataset_fpcs: self.mask_generators[fpc] = [] for m in cfgs_mask: mask_generator = _MaskGenerator( crop_size=crop_size, num_frames=fpc, spatial_patch_size=patch_size, temporal_patch_size=tubelet_size, spatial_pred_mask_scale=m.get("spatial_scale"), temporal_pred_mask_scale=m.get("temporal_scale"), aspect_ratio=m.get("aspect_ratio"), npred=m.get("num_blocks"), max_context_frames_ratio=m.get("max_temporal_keep", 1.0), max_keep=m.get("max_keep", None), full_complement=m.get("full_complement", False), pred_full_complement=m.get("pred_full_complement", False), inv_block=m.get("inv_block", False), ) self.mask_generators[fpc].append(mask_generator)
def step(self): for fpc in self.mask_generators: for mask_generator in self.mask_generators[fpc]: mask_generator.step()
def __call__(self, batch):
# Batch: [buffer, label, clip_indices] filtered_batches = {fpc: [] for fpc in self.mask_generators} for sample in batch: fpc = len(sample[-1][-1]) filtered_batches[fpc] += [sample]
fpc_collations = [] for fpc in filtered_batches: fpc_batch = filtered_batches[fpc] batch_size = len(fpc_batch) if batch_size == 0: continue collated_batch = torch.utils.data.default_collate(fpc_batch) collated_masks_pred, collated_masks_enc = [], [] for i, mask_generator in enumerate(self.mask_generators[fpc]): masks_enc, masks_pred = mask_generator(batch_size) collated_masks_enc.append(masks_enc) collated_masks_pred.append(masks_pred) fpc_collations += [(collated_batch, collated_masks_enc, collated_masks_pred)]
return fpc_collations
class _MaskGenerator(object):
def __init__( self, crop_size=(224, 224), num_frames=16, spatial_patch_size=(16, 16), temporal_patch_size=2, spatial_pred_mask_scale=(0.2, 0.8), temporal_pred_mask_scale=(1.0, 1.0), aspect_ratio=(0.3, 3.0), npred=1, max_context_frames_ratio=1.0, max_keep=None, inv_block=False, full_complement=False, pred_full_complement=False, ): super(_MaskGenerator, self).__init__() if not isinstance(crop_size, tuple): crop_size = (crop_size,) * 2 if not isinstance(spatial_patch_size, tuple): spatial_patch_size = (spatial_patch_size,) * 2 self.crop_size = crop_size self.height, self.width = [crop_size[i] // spatial_patch_size[i] for i in (0, 1)] self.duration = num_frames // temporal_patch_size self.full_complement = full_complement self.pred_full_complement = pred_full_complement
self.spatial_patch_size = spatial_patch_size self.temporal_patch_size = temporal_patch_size
self.aspect_ratio = aspect_ratio self.spatial_pred_mask_scale = spatial_pred_mask_scale self.temporal_pred_mask_scale = temporal_pred_mask_scale self.npred = npred self.max_context_duration = max( 1, int(self.duration * max_context_frames_ratio) ) # maximum number of time-steps (frames) spanned by context mask self.max_keep = max_keep # maximum number of patches to keep in context self._itr_counter = Value("i", -1) # collator is shared across worker processes self.inv_block = inv_block
def step(self): i = self._itr_counter with i.get_lock(): i.value += 1 v = i.value return v
def _sample_block_size(self, generator, temporal_scale, spatial_scale, aspect_ratio_scale): # -- Sample temporal block mask scale _rand = torch.rand(1, generator=generator).item() min_t, max_t = temporal_scale temporal_mask_scale = min_t + _rand * (max_t - min_t) t = max(1, int(self.duration * temporal_mask_scale))
# -- Sample spatial block mask scale _rand = torch.rand(1, generator=generator).item() min_s, max_s = spatial_scale spatial_mask_scale = min_s + _rand * (max_s - min_s) spatial_num_keep = int(self.height * self.width * spatial_mask_scale)
# -- Sample block aspect-ratio _rand = torch.rand(1, generator=generator).item() min_ar, max_ar = aspect_ratio_scale aspect_ratio = min_ar + _rand * (max_ar - min_ar)
# -- Compute block height and width (given scale and aspect-ratio) h = int(round(math.sqrt(spatial_num_keep * aspect_ratio))) w = int(round(math.sqrt(spatial_num_keep / aspect_ratio))) h = min(h, self.height) w = min(w, self.width)
return (t, h, w)
def _sample_block_mask(self, b_size): t, h, w = b_size top = torch.randint(0, self.height - h + 1, (1,)) left = torch.randint(0, self.width - w + 1, (1,)) start = torch.randint(0, self.duration - t + 1, (1,))
mask = torch.ones((self.duration, self.height, self.width), dtype=torch.int32) mask[start : start + t, top : top + h, left : left + w] = 0
# Context mask will only span the first X frames # (X=self.max_context_frames) if self.max_context_duration < self.duration: mask[self.max_context_duration :, :, :] = 0
# -- return mask
def __call__(self, batch_size): """ Create encoder and predictor masks when collating imgs into a batch # 1. sample pred block size using seed # 2. sample several pred block locations for each image (w/o seed) # 3. return pred masks and complement (enc mask) """ seed = self.step() g = torch.Generator() g.manual_seed(seed) p_size = self._sample_block_size( generator=g, temporal_scale=self.temporal_pred_mask_scale, spatial_scale=self.spatial_pred_mask_scale, aspect_ratio_scale=self.aspect_ratio, )
collated_masks_pred, collated_masks_enc = [], [] min_keep_enc = min_keep_pred = self.duration * self.height * self.width for _ in range(batch_size):
empty_context = True while empty_context:
mask_e = torch.ones((self.duration, self.height, self.width), dtype=torch.int32) for _ in range(self.npred): mask_e *= self._sample_block_mask(p_size) mask_e = mask_e.flatten()
mask_p = torch.argwhere(mask_e == 0).squeeze() mask_e = torch.nonzero(mask_e).squeeze()
empty_context = len(mask_e) == 0 if not empty_context: min_keep_pred = min(min_keep_pred, len(mask_p)) min_keep_enc = min(min_keep_enc, len(mask_e)) collated_masks_pred.append(mask_p) collated_masks_enc.append(mask_e)
if self.max_keep is not None: min_keep_enc = min(min_keep_enc, self.max_keep)
collated_masks_enc = [cm[:min_keep_enc] for cm in collated_masks_enc] collated_masks_pred = [cm[:min_keep_pred] for cm in collated_masks_pred] if self.full_complement: # predictor mask is just complement of encoder mask collated_masks_pred = [ torch.tensor( sorted(list(set(range(int(self.duration * self.height * self.width))) - set(cm.tolist()))), dtype=cm.dtype, ) for cm in collated_masks_enc ] elif self.pred_full_complement: collated_masks_enc = [ torch.tensor( sorted(list(set(range(int(self.duration * self.height * self.width))) - set(cm.tolist()))), dtype=cm.dtype, ) for cm in collated_masks_pred ]
collated_masks_enc = torch.utils.data.default_collate(collated_masks_enc) collated_masks_pred = torch.utils.data.default_collate(collated_masks_pred)
if self.inv_block: return collated_masks_pred, collated_masks_enc # predict context from block else: return collated_masks_enc, collated_masks_pred
class MiniImagenetCollator(object): def __init__( self, cfgs_mask, num_frames, crop_size=(224, 224), patch_size=(16, 16), tubelet_size=2, ): super(MiniImagenetCollator, self).__init__() self.mask_generator = [] for m in cfgs_mask: self.mask_generator.append(_MaskGenerator( crop_size=crop_size, num_frames=num_frames, spatial_patch_size=patch_size, temporal_patch_size=tubelet_size, spatial_pred_mask_scale=m.get("spatial_scale"), temporal_pred_mask_scale=m.get("temporal_scale"), aspect_ratio=m.get("aspect_ratio"), npred=m.get("num_blocks"), max_context_frames_ratio=m.get("max_temporal_keep", 1.0), max_keep=m.get("max_keep", None), full_complement=m.get("full_complement", False), pred_full_complement=m.get("pred_full_complement", False), inv_block=m.get("inv_block", False), ))
def __call__(self, batch): fpc_collations = [] images, labels = zip(*batch) for i in range(len(images)): masks_enc, masks_pred = [], [] for mask_generator in self.mask_generator: mask_enc, mask_pred = mask_generator(1) masks_enc.append(mask_enc) masks_pred.append(mask_pred) fpc_collations += [(images[i], labels[i], masks_enc, masks_pred)]
return fpc_collations123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import math
import torchimport torch.nn as nn
from src.models.utils.modules import Block, CrossAttention, CrossAttentionBlockfrom src.utils.tensors import trunc_normal_
class AttentivePooler(nn.Module): """Attentive Pooler"""
def __init__( self, num_queries=1, embed_dim=768, num_heads=12, mlp_ratio=4.0, depth=1, norm_layer=nn.LayerNorm, init_std=0.02, qkv_bias=True, complete_block=True, use_activation_checkpointing=False, ): super().__init__() self.use_activation_checkpointing = use_activation_checkpointing self.query_tokens = nn.Parameter(torch.zeros(1, num_queries, embed_dim))
self.complete_block = complete_block if complete_block: self.cross_attention_block = CrossAttentionBlock( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, norm_layer=norm_layer ) else: self.cross_attention_block = CrossAttention(dim=embed_dim, num_heads=num_heads, qkv_bias=qkv_bias)
self.blocks = None if depth > 1: self.blocks = nn.ModuleList( [ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=False, norm_layer=norm_layer, ) for i in range(depth - 1) ] )
self.init_std = init_std trunc_normal_(self.query_tokens, std=self.init_std) self.apply(self._init_weights) self._rescale_blocks()
def _rescale_blocks(self): def rescale(param, layer_id): param.div_(math.sqrt(2.0 * layer_id))
layer_id = 0 if self.blocks is not None: for layer_id, layer in enumerate(self.blocks): rescale(layer.attn.proj.weight.data, layer_id + 1) rescale(layer.mlp.fc2.weight.data, layer_id + 1)
if self.complete_block: rescale(self.cross_attention_block.mlp.fc2.weight.data, layer_id + 1)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=self.init_std) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): trunc_normal_(m.weight, std=self.init_std) if m.bias is not None: nn.init.constant_(m.bias, 0)
def forward(self, x): if self.blocks is not None: for blk in self.blocks: if self.use_activation_checkpointing: x = torch.utils.checkpoint.checkpoint(blk, x, False, None, use_reentrant=False) else: x = blk(x) q = self.query_tokens.repeat(len(x), 1, 1) q = self.cross_attention_block(q, x) return q
class AttentiveClassifier(nn.Module): """Attentive Classifier"""
def __init__( self, embed_dim=768, num_heads=12, mlp_ratio=4.0, depth=1, norm_layer=nn.LayerNorm, init_std=0.02, qkv_bias=True, num_classes=1000, complete_block=True, use_activation_checkpointing=False, ): super().__init__() self.pooler = AttentivePooler( num_queries=1, embed_dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, depth=depth, norm_layer=norm_layer, init_std=init_std, qkv_bias=qkv_bias, complete_block=complete_block, use_activation_checkpointing=use_activation_checkpointing, ) self.linear = nn.Linear(embed_dim, num_classes, bias=True)
def forward(self, x): x = self.pooler(x).squeeze(1) x = self.linear(x) return x12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import torch.nn as nnfrom einops import rearrange
class PatchEmbed(nn.Module): """ Image to Patch Embedding """
def __init__(self, patch_size=16, in_chans=3, embed_dim=768): super().__init__() self.patch_size = patch_size self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
def forward(self, x): B, C, H, W = x.shape x = self.proj(x).flatten(2).transpose(1, 2) return x
class PatchEmbed3D(nn.Module): """ Image to Patch Embedding """
def __init__( self, patch_size=16, tubelet_size=2, in_chans=3, embed_dim=768, ): super().__init__() self.patch_size = patch_size self.tubelet_size = tubelet_size
self.proj = nn.Conv3d( in_channels=in_chans, out_channels=embed_dim, kernel_size=(tubelet_size, patch_size, patch_size), stride=(tubelet_size, patch_size, patch_size), )
def forward(self, x, **kwargs): B, C, T, H, W = x.shape x = self.proj(x).flatten(2).transpose(1, 2) return xevals/action_anticipation_frozen/dataloader.pyAdded+236
evals/action_anticipation_frozen/epickitchens.pyAdded+323
evals/action_anticipation_frozen/eval.pyAdded+749
evals/action_anticipation_frozen/losses.pyAdded+49
evals/action_anticipation_frozen/metrics.pyAdded+58
evals/action_anticipation_frozen/modelcustom/vit_encoder_predictor_concat_ar.pyAdded+188
evals/action_anticipation_frozen/models.pyAdded+136
evals/action_anticipation_frozen/utils.pyAdded+85
evals/hub/__init__.pyAdded
evals/hub/preprocessor.pyAdded+15
evals/image_classification_frozen/eval.pyAdded+476
evals/image_classification_frozen/modelcustom/vit_encoder.pyAdded+83
evals/image_classification_frozen/models.pyAdded+44
evals/main.pyAdded+112
evals/main_distributed.pyAdded+230
evals/scaffold.pyAdded+19
evals/video_classification_frozen/eval.pyAdded+537
evals/video_classification_frozen/modelcustom/vit_encoder_multiclip.pyAdded+149
evals/video_classification_frozen/modelcustom/vit_encoder_multiclip_multilevel.pyAdded+155
evals/video_classification_frozen/models.pyAdded+46
evals/video_classification_frozen/utils.pyAdded+198
make_module_static.ipynbAdded
src/datasets/__pycache__/data_manager.cpython-310.pycAdded
src/datasets/__pycache__/video_dataset.cpython-310.pycAdded
src/datasets/imagenet1k.pyAdded+152
src/datasets/utils/__pycache__/dataloader.cpython-310.pycAdded
src/datasets/utils/__pycache__/weighted_sampler.cpython-310.pycAdded
src/datasets/utils/dataloader.pyAdded+234
src/datasets/utils/video/__pycache__/functional.cpython-310.pycAdded
src/datasets/utils/video/__pycache__/randaugment.cpython-310.pycAdded
src/datasets/utils/video/__pycache__/transforms.cpython-310.pycAdded
src/datasets/utils/video/functional.pyAdded+110
src/datasets/utils/video/randerase.pyAdded+170
src/datasets/utils/video/transforms.pyAdded+1161
src/datasets/utils/video/volume_transforms.pyAdded+159
src/datasets/utils/weighted_sampler.pyAdded+336
src/datasets/utils/worker_init_fn.pyAdded+76
src/datasets/video_dataset.pyAdded+485
src/masks/__pycache__/multiseq_multiblock3d.cpython-310.pycAdded
src/masks/__pycache__/utils.cpython-310.pycAdded
src/masks/multiseq_multiblock3d.pyAdded+282
src/models/__pycache__/vision_transformer.cpython-310.pycAdded
src/models/attentive_pooler.pyAdded+137
src/models/utils/__pycache__/modules.cpython-310.pycAdded
src/models/utils/patch_embed.pyAdded+52
src/utils/__pycache__/distributed.cpython-310.pycAdded
src/utils/__pycache__/monitoring.cpython-310.pycAdded
src/utils/__pycache__/schedulers.cpython-310.pycAdded
src/utils/__pycache__/tensors.cpython-310.pycAdded
src/utils/__pycache__/wrappers.cpython-310.pycAdded