code
stringlengths
17
6.64M
class MultiCropTransform(): "Define multi crop transform that apply several sets of transform to the inputs.\n\n Args:\n set_transforms: List of Dictionary of sets of transforms specifying transforms and number of views per set.\n\n Example::\n\n set_transforms = [\n {'transform': [...
class OnlyInputListTransform(Compose): "Apply Transform to only the key ``'input'`` in a list of sample dictionary.\n\n Args:\n transform: The transform to apply.\n " def __init__(self, transform: Callable) -> None: transforms = [ApplyTransformInputKeyOnList(transform), DictKeepInputLabe...
class OnlyInputTransform(Compose): "Apply Transform to only the key ``'input'`` in a sample dictionary.\n\n Args:\n transform: The transform to apply.\n " def __init__(self, transform: Callable) -> None: transforms = [ApplyTransformInputKey(transform), DictKeepInputLabelIdx()] su...
class OnlyInputListSameTransform(Compose): "Apply the same transform to only the key ``'input'`` in a list of sample dictionary.\n\n Args:\n transform: The transform to apply.\n " def __init__(self, transform: Callable) -> None: transforms = [ApplySameTransformInputKeyOnList(transform), ...
class OnlyInputTransformWithDictTransform(Compose): "Apply Transform to only the key ``'input'`` in a sample dictionary with a transformation on the dictionary\n afterwards.\n\n Args:\n transform: The transform to apply to the input.\n dict_transform: The transform to apply to the dictionary.\...
class OnlyInputListTransformWithDictTransform(): "Apply Transform to only the key ``'input'`` in a list of sample dictionary with a transformation on the\n dictionary afterwards.\n\n Args:\n transform: The transform to apply to the input.\n dict_transform: The transform to apply to the diction...
class RandomResizedCrop(transforms.RandomResizedCrop): def __init__(self, size: Union[(int, Iterable[int])], scale: Iterable[float]=[0.08, 1.0], ratio: Iterable[float]=[(3 / 4), (4 / 3)], interpolation: Union[(str, InterpolationMode)]='bilinear', antialias: bool=True, **kwargs) -> None: if (type(interpol...
class RemoveKey(Module): "Removes the given key from the input dict. Useful for removing modalities from a video clip that aren't\n needed.\n\n Args:\n key: The dictionary key to remove.\n " def __init__(self, key: str): super().__init__() self._key = key def __call__(sel...
class RemoveInputKey(RemoveKey): 'Remove video key from sample dictionary.' def __init__(self): super().__init__('input')
class RemoveAudioKey(RemoveKey): 'Remove audio key from sample dictionary.' def __init__(self): super().__init__('audio')
class RemoveTimeDim(nn.Module): 'Remove time dimension from tensor.\n\n Suppose the tensor shape is [C,T,H,W].\n ' def __init__(self) -> None: super().__init__() def forward(self, tensor: Tensor): (c, t, h, w) = tensor.shape return tensor.view((c * t), h, w) def __repr...
def mix_spotting(x: Tensor, mix_value: Tensor, permutation: Tensor, labels: Tensor, has_label: Tensor, ignore_class: Tensor): 'Make mixup of the batch for action spotting.\n\n Args:\n x: The batch values to mix.\n mix_value: Value coefficients for mixing.\n permutation: Permutation to perf...
class SpottingMixup(Module): 'Make mixup for spotting for labels.\n\n Args:\n alpha: Alpha value for the beta distribution of mixup.\n ' def __init__(self, alpha: float=0.5) -> None: super().__init__() self.alpha = alpha self.mix_sampler = torch.distributions.Beta(alpha, ...
def get_matching_files_in_dir(dir: str, file_pattern: str) -> List[Path]: 'Retrieve files in directory matching a pattern.\n\n Args:\n dir: Directory path.\n file_pattern: Pattern for the files.\n\n Raises:\n NotADirectoryError: If `dir` does not exist or is not a directory.\n\n Retu...
def get_ckpts_in_dir(dir: str, ckpt_pattern: str='*.ckpt') -> List[Path]: 'Get all checkpoints in a directory.\n\n Args:\n dir: Directory path containing the checkpoints.\n ckpt_pattern: Checkpoint glob pattern.\n\n Returns:\n List of checkpoints paths in directory.\n ' try: ...
def get_last_ckpt_in_dir(dir: str, ckpt_pattern: str='*.ckpt', key_sort: Callable=(lambda x: x.stat().st_mtime)) -> Optional[Path]: 'Get last ckpt in directory following a sorting function.\n\n Args:\n dir: Directory path containing the checkpoints.\n ckpt_pattern: Checkpoint glob pattern.\n ...
def get_last_ckpt_in_path_or_dir(checkpoint_file: Optional[str]=None, checkpoint_dir: Optional[str]=None, ckpt_pattern: str='*.ckpt', key_sort: Callable=(lambda x: x.stat().st_mtime)) -> Optional[Path]: 'Get checkpoint from file or from last checkpoint in directory following a sorting function.\n\n Args:\n ...
def get_ckpt_by_callback_mode(checkpoint_path: str, checkpoint_mode: str) -> List[Path]: "Get checkpoint from ModelCheckpoint callback based on the mode: ``'best'``, ``'last'``, or ``'both'``.\n\n Args:\n checkpoint_path: Checkpoint file path containing the callback checkpoint.\n checkpoint_mode:...
def get_sub_state_dict_from_pl_ckpt(checkpoint_path: str, pattern: str='^(trunk\\.)') -> Dict[(Any, Any)]: 'Retrieve sub state dict from a pytorch lightning checkpoint.\n\n Args:\n checkpoint_path: Pytorch lightning checkpoint path.\n pattern: Pattern to filter the keys for the sub state dictiona...
def remove_pattern_in_keys_from_dict(d: Dict[(Any, Any)], pattern: str) -> Dict[(Any, Any)]: 'Remove the pattern from keys in a dictionary.\n\n Args:\n d: The dictionary.\n pattern: Pattern to remove from the keys.\n If value is ``""`` keep all keys.\n\n Returns:\n Input dict...
def mask_tube_in_sequence(mask_ratio: float, tube_size: int, len_sequence: int, device: (str | torch.device)='cpu'): 'Generate indices to mask tubes from a sequence.\n\n Args:\n mask_ratio: Ratio for the masking.\n tube_size: Tube size for the masking.\n len_sequence (int): Length of the s...
def batch_mask_tube_in_sequence(mask_ratio: float, tube_size: int, len_sequence: int, batch_size: int, device: (str | torch.device)='cpu'): 'Generate indices to mask tubes from a batch of sequences.\n\n Args:\n mask_ratio: Ratio for the masking.\n tube_size: Tube size for the masking.\n le...
def get_global_batch_size_in_trainer(local_batch_size: int, trainer: Trainer) -> int: 'Get global batch size used by a trainer based on the local batch size.\n\n Args:\n local_batch_size: The local batch size used by the trainer.\n trainer: The trainer used.\n\n Raises:\n AttributeError...
def get_local_batch_size_in_trainer(global_batch_size: int, trainer: Trainer) -> int: 'Get local batch size used by a trainer based on the global batch size.\n\n Args:\n global_batch_size: The global batch size used by the trainer.\n strategy: The trainer used.\n\n Raises:\n AttributeEr...
def get_num_devices_in_trainer(trainer: Trainer) -> int: 'Get the number of devices used by the trainer.\n\n Args:\n trainer: The trainer.\n\n Raises:\n AttributeError: The strategy used by trainer is not supported\n\n Returns:\n The number of devices used by trainer.\n ' stra...
def get_trainer_strategy(trainer: Trainer) -> Any: 'Retrieve the strategy from a trainer.\n\n Args:\n trainer: The trainer.\n\n Returns:\n The strategy.\n ' if (pl.__version__ < '1.6.0'): return trainer.training_type_plugin else: return trainer.strategy
def is_strategy_ddp(strategy: Any) -> bool: 'Test if strategy is ddp.\n\n Args:\n strategy: The strategy.\n\n Returns:\n ``True`` if strategy is ddp.\n ' return any([isinstance(strategy, process_strategy) for process_strategy in process_independent_strategies])
def is_strategy_tpu(strategy: Any) -> bool: 'Test if strategy is tpu.\n\n Args:\n strategy: The strategy.\n\n Returns:\n ``True`` if strategy is tpu.\n ' return any([isinstance(strategy, tpu_strategy) for tpu_strategy in tpu_strategies])
def compile_model(model: LightningModule, do_compile: bool=False, fullgraph: bool=False, dynamic: bool=False, backend: Union[(str, Callable)]='inductor', mode: Union[(str, None)]=None, options: Optional[Dict[(str, Union[(str, int, bool)])]]=None, disable: bool=False): "If torch version is greater than `'2.0.0'` a...
def get_default_seed(default_seed: int=0) -> int: 'Get the default seed if pytorch lightning did not initialize one.\n\n Args:\n default_seed: The default seed.\n\n Returns:\n Pytorch lightning seed or the default one.\n ' return int(os.getenv('PL_GLOBAL_SEED', default_seed))
def get_global_rank() -> int: 'Get global rank of the process.' if (dist.is_available() and dist.is_initialized()): return dist.get_rank() if (('RANK' in os.environ) and ('WORLD_SIZE' in os.environ)): rank = int(os.environ['RANK']) elif (int(os.environ.get('SLURM_NPROCS', 1)) > 1): ...
def get_local_rank() -> int: 'Get local rank of the process.' if (('RANK' in os.environ) and ('WORLD_SIZE' in os.environ)): local_rank = int(os.environ['LOCAL_RANK']) elif (int(os.environ.get('SLURM_NPROCS', 1)) > 1): local_rank = int(os.environ['SLURM_LOCALID']) else: local_ra...
def get_world_size() -> int: 'Get world size or number of the processes.' if (dist.is_available() and dist.is_initialized()): return dist.get_world_size() if (('RANK' in os.environ) and ('WORLD_SIZE' in os.environ)): world_size = int(os.environ['WORLD_SIZE']) elif (int(os.environ.get('...
def get_local_world_size() -> int: 'Get local world size or number of processes on the node.' if (dist.is_available() and dist.is_initialized()): return torch.cuda.device_count() else: return 1
def is_only_one_condition_true(*conditions: List[bool]) -> bool: 'Test if only one of the conditions is True.' a = conditions[0] b = conditions[0] for condition in conditions[1:]: a = (a ^ condition) b = (b & condition) return (a & (~ b))
def all_false(*conditions: List[bool]) -> bool: 'Test that all conditions are False.' return all([(~ condition) for condition in conditions])
def warmup_value(initial_value: float, final_value: float, step: int=0, max_step: int=0) -> float: 'Apply warmup to a value.\n\n Args:\n initial_value: Initial value.\n final_value: Final value.\n step: Current step.\n max_step: Max step for warming up.\n\n Returns:\n The ...
def scheduler_value(scheduler: Optional[str], initial_value: float, final_value: float, step: int=0, max_step: int=0) -> float: 'Apply scheduler to a value.\n\n Args:\n scheduler: The type of the scheduler.\n initial_value: The initial value.\n final_value: The final value.\n step: ...
def apply_several_transforms(images: Iterable[Tensor], transforms: Iterable[Module]) -> List[List[Tensor]]: 'Apply several transformations to a list of images.\n\n Args:\n images: The images.\n transforms: The transformations to apply to the images.\n\n Returns:\n List of list of transf...
def apply_several_video_transforms(videos: Iterable[Dict[(str, Any)]], transforms: Iterable[Module]) -> List[List[Tensor]]: 'Apply several transformations to a list of videos.\n\n Args:\n videos: The videos.\n transforms: The transformations to apply to the videos.\n\n Returns:\n List o...
def make_grid_from_several_transforms(sets_images: Iterable[Iterable[Tensor]], n_images_per_row: int=8) -> Tensor: 'Make a grid of images by aligning images from several transformations vertically.\n\n Args:\n sets_images: Sets of transformed images aligned, base_image(sets_images[0][?]) == ... == base_...
def make_several_transforms_from_config(cfg_transforms: Mapping[(Any, Any)]) -> List[Module]: "Make several transformations from a configuration dictionary.\n\n Args:\n cfg_transforms: Configuration of transformations in the form {'transform1': {...}, 'transform2': {...}}.\n\n Returns:\n List ...
def show_images(imgs: Union[(Iterable[Tensor], Tensor)], figsize: Iterable[float]=[6.4, 4.8]): 'Show images from a tensor or a list of tensor.\n\n Args:\n imgs: Images to display.\n figsize: Figure size for the images.\n ' if (not isinstance(imgs, list)): imgs = [imgs] (_, axs)...
def show_video(video: Tensor) -> animation.ArtistAnimation: 'Show a video thanks to animation from matplotlib.\n\n Args:\n video: The raw video to display.\n\n Returns:\n The animation to show.\n ' video = video.long() video = np.asarray(video.permute(1, 2, 3, 0)) (fig, ax) = pl...
def main(): args = parser.parse_args() soccernet_dataset(data_path=args.data_path, transform=None, video_path_prefix=args.path_prefix, decoder_args={'fps': args.fps}, features_args=None, label_args={'radius_label': args.radius_label, 'cache_dir': args.cache_dir}, task=SoccerNetTask(args.task))
def get_video_duration(video_file): cmd = ['ffmpeg', '-i', str(video_file), '-f', 'null', '-'] try: output = subprocess.check_output(cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: print(video_file, err.output) return (- 1) try: output_decode...
def has_video_stream(video_file): cmd = ['ffprobe', '-i', str(video_file), '-show_streams', '-select_streams', 'v', '-loglevel', 'error'] try: output = subprocess.check_output(cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: print(video_file, err.output) ...
def is_video_empty(video_file): return ((get_video_duration(video_file) <= 0) or (not has_video_stream(video_file)))
def process(row, folder_path, output_path, args): classname = row[0] videoname = row[1] videostem = row[2] inname = ((folder_path / classname) / videoname) if is_video_empty(inname): print(f'{inname} is empty.') return (False, f'{inname} is empty.') output_folder = (output_path...
@hydra.main(config_path='../eztorch/configs/run/evaluation/feature_extractor/resnet3d50', config_name='resnet3d50_ucf101') def main(config: DictConfig) -> None: rundir = Path(to_absolute_path(config.dir.run)) rundir.mkdir(parents=True, exist_ok=True) os.chdir(rundir) rank_zero_info(f'Run directory: {r...
@hydra.main(config_path='../eztorch/configs/run/evaluation/linear_classifier/sce/resnet50', config_name='resnet50_imagenet_mocov3') def main(config: DictConfig) -> None: rundir = Path(to_absolute_path(config.dir.run)) rundir.mkdir(parents=True, exist_ok=True) os.chdir(rundir) rank_zero_info(f'Run dire...
@hydra.main(config_path='../eztorch/configs/run/pretrain/sce/resnet50', config_name='resnet50_imagenet') def main(config: DictConfig) -> None: rundir = Path(to_absolute_path(config.dir.run)) rundir.mkdir(parents=True, exist_ok=True) os.chdir(rundir) rank_zero_info(f'Run directory: {rundir}') hydra...
@hydra.main(config_path='../eztorch/configs/run/pretrain/moco', config_name='resnet18_cifar10') def main(config: DictConfig) -> None: rundir = Path(to_absolute_path(config.dir.run)) rundir.mkdir(parents=True, exist_ok=True) os.chdir(rundir) rank_zero_info(f'Run directory: {rundir}') hydradir = (ru...
@hydra.main(config_path='../eztorch/configs/run/evaluation/retrieval_from_bank', config_name='default') def main(config: DictConfig) -> None: rundir = Path(to_absolute_path(config.dir.run)) rundir.mkdir(parents=True, exist_ok=True) os.chdir(rundir) rank_zero_info(f'Run directory: {rundir}') hydrad...
@hydra.main(config_path='../eztorch/configs/run/supervised/resnet3d18', config_name='kinetics200') def main(config: DictConfig) -> None: rundir = Path(to_absolute_path(config.dir.run)) rundir.mkdir(parents=True, exist_ok=True) os.chdir(rundir) rank_zero_info(f'Run directory: {rundir}') hydradir = ...
@hydra.main(config_path='../eztorch/configs/run/supervised/resnet3d18', config_name='kinetics200') def main(config: DictConfig) -> None: rundir = Path(to_absolute_path(config.dir.run)) rundir.mkdir(parents=True, exist_ok=True) os.chdir(rundir) rank_zero_info(f'Run directory: {rundir}') hydradir = ...
@hydra.main(config_path='../eztorch/configs/run/supervised/resnet3d50', config_name='ucf101') def main(config: DictConfig) -> None: rundir = Path(to_absolute_path(config.dir.run)) rundir.mkdir(parents=True, exist_ok=True) os.chdir(rundir) rank_zero_info(f'Run directory: {rundir}') hydradir = (rund...
class TestFrameSoccerNetVideo(unittest.TestCase): def setUp(self) -> None: self.default_args = {'video_path': Path('/video/'), 'half_path': Path('/video/half1'), 'transform': None, 'video_frame_to_path_fn': get_video_to_frame_path_fn(zeros=8), 'num_threads_io': 0} def test_same_fps_get_timestamps_in...
class TestSoccerNetDataset(unittest.TestCase): def test_soccernet_dataset(self): dataset = soccernet_dataset((Path(os.path.realpath(__file__)).parent / 'small_annotations.json'), None, (Path(os.path.realpath(__file__)).parent / 'images'), label_args={'radius_label': 2, 'cache_dir': (Path(os.path.realpath...
class TestSoccerNetPredictions(unittest.TestCase): def test_aggregate_predictions(self): predictions = torch.tensor([[0.5, 0.6], [0.4, 0.7], [0.7, 0.3], [0.3, 0.5], [0.8, 0.2], [0.9, 0.9]]) timestamps = torch.tensor([[0.0, 0.0], [1.0, 1.0], [1.0, 1.0], [2.0, 2.0], [8.0, 2.0], [8.0, 8.0]]) ...
class TestSCETokenMasks(unittest.TestCase): def test_perform_hard_NMS(self): values = torch.tensor([0.5, 1.0, 0.2, 0.3, 0.1, 0.2, 0.6]) window = 3 threshold = 0.49 keep_indexes = perform_hard_NMS(values, window, threshold) expected_keep_indexes = torch.tensor([False, True,...
class BoringDataModule(LightningDataModule): def __init__(self, data_dir: str='./', dataset=RandomDataset((32, (64 * 4))), val_dataset=RandomDataset((32, (64 * 4))), batch_size: int=1): super().__init__() self.data_dir = data_dir self.non_picklable = None self.checkpoint_state: Op...
class RandomDataset(Dataset): def __init__(self, size: Iterable[int]): self.length = size[0] self.data = torch.randn(size) def __getitem__(self, index): return {'input': self.data[index], 'idx': index} def __len__(self): return self.length
class RandomLabeledDataset(Dataset): def __init__(self, size: Iterable[int], num_classes: int=10): self.length = size[0] self.data = torch.randn(size) self.labels = torch.randint(num_classes, size=(size[0], 1)) def __getitem__(self, index): return {'input': self.data[index], ...
class RandomVisionLabeledDataset(VisionDataset): def __init__(self, size: Iterable[int], num_classes: int=10, transform: Optional[Module]=None): super().__init__('data/', transform=transform) self.length = size[0] self.data = torch.randn(size) self.labels = torch.randint(num_class...
class BoringModel(LightningModule): def __init__(self): 'Testing PL Module. Use as follows:\n\n - subclass\n - modify the behavior for what you want\n class TestModel(BaseTestModel):\n def training_step(...):\n # do your own thing\n or:\n model...
class LargeBoringModel(LightningModule): def __init__(self): 'Testing PL Module. Use as follows:\n\n - subclass\n - modify the behavior for what you want\n class TestModel(BaseTestModel):\n def training_step(...):\n # do your own thing\n or:\n ...
class ManualOptimBoringModel(BoringModel): def __init__(self): super().__init__() self.automatic_optimization = False def training_step(self, batch, batch_idx): opt = self.optimizers() output = self(batch) loss = self.loss(batch, output) opt.zero_grad() ...
class TestSCELoss(unittest.TestCase): def setUp(self) -> None: self.coeff = 0.5 self.temp = 0.1 self.temp_m = 0.07 def test_sce_loss_without_key(self): q = torch.arange(1.0, 9.0, 1.0).view((4, 2)) k = torch.tensor([[0, 0], [1, 1], [0, 0], [1.0, 1.0]]) queue = ...
class TestSCETokenMasks(unittest.TestCase): def setUp(self) -> None: self.batch_size = 2 self.num_tokens = 8 self.num_negatives = 2 def test_one_device_zero_pos_radius_no_keys_init(self): (mask_sim_q, mask_sim_k, mask_prob_q, mask_log_q, num_positives_per_token) = compute_sce...
class TestSCETokenLoss(unittest.TestCase): def setUp(self) -> None: self.batch_size = 2 self.num_tokens = 8 self.num_negatives = 2 self.dim = 4 self.query = torch.randn(((self.batch_size * self.num_tokens), self.dim)) self.key = torch.randn(((self.batch_size * self...
class TestMoCoModel(unittest.TestCase): def setUp(self) -> None: self.trunk_cfg = DictConfig({'_target_': 'eztorch.models.trunks.create_resnet', 'name': 'resnet18', 'num_classes': 0, 'small_input': True}) self.projector_cfg = DictConfig({'_target_': 'eztorch.models.heads.MLPHead', 'input_dim': 51...
class TestReSSLModel(unittest.TestCase): def setUp(self) -> None: self.trunk_cfg = DictConfig({'_target_': 'eztorch.models.trunks.create_resnet', 'name': 'resnet18', 'num_classes': 0, 'small_input': True}) self.projector_cfg = DictConfig({'_target_': 'eztorch.models.heads.MLPHead', 'input_dim': 5...
class TestSCEModel(unittest.TestCase): def setUp(self) -> None: self.trunk_cfg = DictConfig({'_target_': 'eztorch.models.trunks.create_resnet', 'name': 'resnet18', 'num_classes': 0, 'small_input': True}) self.projector_cfg = DictConfig({'_target_': 'eztorch.models.heads.MLPHead', 'input_dim': 512...
class TestSimCLRModel(unittest.TestCase): def setUp(self) -> None: self.trunk_cfg = DictConfig({'_target_': 'eztorch.models.trunks.create_resnet', 'name': 'resnet18', 'num_classes': 0, 'small_input': True}) self.projector_cfg = DictConfig({'_target_': 'eztorch.models.heads.MLPHead', 'input_dim': ...
class TestResnet(unittest.TestCase): def test_all_resnets(self): for resnet in _ResNets: create_resnet(resnet) def test_resnet_small_input_with_fc(self): resnet = create_resnet('resnet18', small_input=True) assert isinstance(resnet.fc, nn.Linear) assert (resnet.co...
class TestOptimizerFactory(unittest.TestCase): def test_init_lars(self): model = BoringModel() LARS(model.parameters(), lr=0.1)
class TestOptimizerFactory(unittest.TestCase): def setUp(self): self.base_model = BoringModel() self.large_model = LargeBoringModel() self.sgd_config = DictConfig({'name': 'sgd', 'initial_lr': 2.0, 'batch_size': None, 'num_steps_per_epoch': None, 'exclude_wd_norm': False, 'exclude_wd_bias...
class TestFilterLearnableParmams(unittest.TestCase): def test_filter_learnable_params(self) -> None: boring_model = BoringModel() large_boring_model = LargeBoringModel() boring_model_params = list(boring_model.parameters()) filtered_boring_model_params = filter_learnable_params(bo...
class TestLrScaler(unittest.TestCase): def setUp(self) -> None: self.initial_lr = 2.0 self.batch_size = 16 def test_none_scaler(self) -> None: lr = scale_learning_rate(self.initial_lr, None, self.batch_size) assert (lr == self.initial_lr) lr = scale_learning_rate(self...
class TestRetrieveModelParams(unittest.TestCase): def setUp(self) -> None: self.linear1 = nn.Linear(5, 5) self.bn1 = nn.BatchNorm1d(5) self.linear2 = nn.Linear(5, 5, bias=True) self.model = nn.Sequential(self.linear1, self.bn1, self.linear2) self.module_list = list(self.mo...
class TestReducedTimestamps(unittest.TestCase): def test_batch_reduced_timestamps(self): x = torch.tensor([[[0.5, 0.8], [0.4, 0.6]], [[0.5, 0.8], [0.4, 0.6]], [[0.2, 0.8], [0.4, 0.6]], [[0.2, 0.8], [0.4, 0.6]], [[0.2, 0.8], [0.4, 0.6]], [[0.2, 0.8], [0.4, 0.6]]]) labels = torch.tensor([[[1.0, 0.0...
class TestActionSpottingMixup(unittest.TestCase): def test_mix_action_spotting(self): x = torch.tensor([[[0.5, 0.8], [0.4, 0.6]], [[0.2, 0.8], [0.4, 0.6]], [[0.5, 0.8], [0.4, 0.5]], [[0.4, 0.2], [0.2, 0.5]]]) mix_value = torch.tensor([[[0.5]], [[0.3]], [[0.7]], [[0.2]]]) permutation = tor...
class RSSMPrior(nn.Module): c: Config @nn.compact def __call__(self, prev_state, context): inputs = jnp.concatenate([prev_state['sample'], context], (- 1)) hl = nn.relu(nn.Dense(self.c.cell_embed_size)(inputs)) (det_state, det_out) = GRUCell()(prev_state['det_state'], hl) ...
class RSSMPosterior(nn.Module): c: Config @nn.compact def __call__(self, prior, obs_inputs): inputs = jnp.concatenate([prior['det_out'], obs_inputs], (- 1)) hl = nn.relu(nn.Dense(self.c.cell_embed_size)(inputs)) hl = nn.relu(nn.Dense(self.c.cell_embed_size)(hl)) mean = nn....
class RSSMCell(nn.Module): c: Config @property def state_size(self): return dict(mean=self.c.cell_stoch_size, stddev=self.c.cell_stoch_size, sample=self.c.cell_stoch_size, det_out=self.c.cell_deter_size, det_state=self.c.cell_deter_size, output=(self.c.cell_stoch_size + self.c.cell_deter_size)) ...
class Encoder(nn.Module): '\n Multi-level Video Encoder.\n 1. Extracts hierarchical features from a sequence of observations.\n 2. Encodes observations using Conv layers, uses them directly for the bottom-most level.\n 3. Uses dense features for each level of the hierarchy above the bottom-most level....
class Decoder(nn.Module): ' States to Images Decoder.' c: Config @nn.compact def __call__(self, bottom_layer_output): '\n Arguments:\n bottom_layer_output : Tensor\n State tensor of shape (batch_size, timesteps, feature_dim)\n\n Returns:\n Ou...
def must_be(value): return field(default=value, metadata=dict(choices=[value]))
@dataclass class Config(): config: str datadir: str logdir: str levels: int = 3 tmp_abs_factor: int = 6 dec_stddev: float = 1.0 enc_dense_layers: int = 3 enc_dense_embed_size: int = 1000 cell_stoch_size: int = 20 cell_deter_size: int = 200 cell_embed_size: int = 200 cel...
def parse_config(eval=False): p = ArgumentParser() for f in fields(Config): kwargs = (dict(action='store_true') if ((f.type is bool) and (not f.default)) else dict(default=f.default, type=f.type)) p.add_argument(f'--{f.name}', **kwargs, **f.metadata) c = Config(**vars(p.parse_args())) ...
class GqnMazes(tfds.core.GeneratorBasedBuilder): 'DatasetBuilder for GQN Mazes dataset.' VERSION = tfds.core.Version('1.0.0') RELEASE_NOTES = {'1.0.0': 'Initial release.'} def _info(self) -> tfds.core.DatasetInfo: 'Returns the dataset metadata.' return tfds.core.DatasetInfo(builder=se...
class MovingMnist_2digit(tfds.core.GeneratorBasedBuilder): 'DatasetBuilder for Moving MNIST dataset.' VERSION = tfds.core.Version('1.0.0') RELEASE_NOTES = {'1.0.0': 'Initial release.'} def _info(self) -> tfds.core.DatasetInfo: 'Returns the dataset metadata.' return tfds.core.DatasetIn...
class SSFetcher(threading.Thread): def __init__(self, parent, init_offset=0, init_reshuffle_count=1, eos_sym=(- 1), skip_utterance=False, skip_utterance_predict_both=False): threading.Thread.__init__(self) self.parent = parent self.rng = numpy.random.RandomState(self.parent.seed) ...
class SSIterator(object): def __init__(self, dialogue_file, batch_size, seed, max_len=(- 1), use_infinite_loop=True, init_offset=0, init_reshuffle_count=1, eos_sym=(- 1), skip_utterance=False, skip_utterance_predict_both=False): self.dialogue_file = dialogue_file self.batch_size = batch_size ...
def sharedX(value, name=None, borrow=False, dtype=None): if (dtype is None): dtype = theano.config.floatX return theano.shared(theano._asarray(value, dtype=dtype), name=name, borrow=borrow)
def Adam(grads, lr=0.0002, b1=0.1, b2=0.001, e=1e-08): updates = [] varlist = [] i = sharedX(0.0) i_t = (i + 1.0) fix1 = (1.0 - ((1.0 - b1) ** i_t)) fix2 = (1.0 - ((1.0 - b2) ** i_t)) lr_t = (lr * (T.sqrt(fix2) / fix1)) for (p, g) in grads.items(): m = sharedX((p.get_value() * ...
def safe_pickle(obj, filename): if os.path.isfile(filename): logger.info(('Overwriting %s.' % filename)) else: logger.info(('Saving to %s.' % filename)) with open(filename, 'wb') as f: cPickle.dump(obj, f, protocol=cPickle.HIGHEST_PROTOCOL)
class Model(object): def __init__(self): self.floatX = theano.config.floatX self.params = [] def save(self, filename): '\n Save the model to file `filename`\n ' vals = dict([(x.name, x.get_value()) for x in self.params]) numpy.savez(filename, **vals) ...
class Timer(object): def __init__(self): self.total = 0 def start(self): self.start_time = time.time() def finish(self): self.total += (time.time() - self.start_time)