code
stringlengths
17
6.64M
def basic_clean(text): text = ftfy.fix_text(text) text = html.unescape(html.unescape(text)) return text.strip()
def whitespace_clean(text): text = re.sub('\\s+', ' ', text) text = text.strip() return text
class SimpleTokenizer(object): def __init__(self, bpe_path: str=default_bpe()): self.byte_encoder = bytes_to_unicode() self.byte_decoder = {v: k for (k, v) in self.byte_encoder.items()} merges = gzip.open(bpe_path).read().decode('utf-8').split('\n') merges = merges[1:(((49152 - 25...
@DATASET_REGISTRY.register() class Bamboo(DatasetBase): dataset_dir = 'bamboo' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.image_dir = (root + '/images') self.dataset_dir = root self.preprocessed = os.path.join(self.dataset_dir, '...
@DATASET_REGISTRY.register() class Caltech101(DatasetBase): dataset_dir = 'caltech-101' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.image_dir = os.path.join(self.dataset_dir, '101_Ob...
@DATASET_REGISTRY.register() class DescribableTextures(DatasetBase): dataset_dir = 'dtd' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.image_dir = os.path.join(self.dataset_dir, 'image...
@DATASET_REGISTRY.register() class EuroSAT(DatasetBase): dataset_dir = 'eurosat' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.image_dir = os.path.join(self.dataset_dir, '2750') ...
@DATASET_REGISTRY.register() class FGVCAircraft(DatasetBase): dataset_dir = 'fgvc_aircraft' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.image_dir = os.path.join(self.dataset_dir, 'im...
@DATASET_REGISTRY.register() class Food101(DatasetBase): dataset_dir = 'food-101' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.image_dir = os.path.join(self.dataset_dir, 'images') ...
@DATASET_REGISTRY.register() class ImageNet(DatasetBase): dataset_dir = 'imagenet' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.image_dir = self.dataset_dir self.preprocessed ...
@DATASET_REGISTRY.register() class ImageNet21k(DatasetBase): dataset_dir = 'imagenet21k' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.image_dir = root self.dataset_dir = root self.preprocessed = os.path.join(self.dataset_dir.replac...
@DATASET_REGISTRY.register() class ImageNetA(DatasetBase): 'ImageNet-A(dversarial).\n\n This dataset is used for testing only.\n ' dataset_dir = 'imagenet-adversarial' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.jo...
@DATASET_REGISTRY.register() class ImageNetR(DatasetBase): 'ImageNet-R(endition).\n\n This dataset is used for testing only.\n ' dataset_dir = 'imagenet-rendition' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(r...
@DATASET_REGISTRY.register() class ImageNetSketch(DatasetBase): 'ImageNet-Sketch.\n\n This dataset is used for testing only.\n ' dataset_dir = 'imagenet-sketch' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root...
@DATASET_REGISTRY.register() class ImageNetV2(DatasetBase): 'ImageNetV2.\n\n This dataset is used for testing only.\n ' dataset_dir = 'imagenetv2' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset...
@DATASET_REGISTRY.register() class OxfordFlowers(DatasetBase): dataset_dir = 'oxford_flowers' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.image_dir = os.path.join(self.dataset_dir, '...
@DATASET_REGISTRY.register() class OxfordPets(DatasetBase): dataset_dir = 'oxford_pets' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.image_dir = os.path.join(self.dataset_dir, 'images...
@DATASET_REGISTRY.register() class StanfordCars(DatasetBase): dataset_dir = 'stanford_cars' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.split_path = os.path.join(self.dataset_dir, 's...
@DATASET_REGISTRY.register() class SUN397(DatasetBase): dataset_dir = 'sun397' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.image_dir = os.path.join(self.dataset_dir, 'SUN397') ...
@DATASET_REGISTRY.register() class UCF101(DatasetBase): dataset_dir = 'ucf101' def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.image_dir = os.path.join(self.dataset_dir, 'UCF-101-midfram...
def print_args(args, cfg): print('***************') print('** Arguments **') print('***************') optkeys = list(args.__dict__.keys()) optkeys.sort() for key in optkeys: print('{}: {}'.format(key, args.__dict__[key])) print('************') print('** Config **') print('*...
def reset_cfg(cfg, args): if args.root: cfg.DATASET.ROOT = args.root if args.output_dir: cfg.OUTPUT_DIR = args.output_dir if args.trainer: cfg.TRAINER.NAME = args.trainer if args.backbone: cfg.MODEL.BACKBONE.NAME = args.backbone if args.head: cfg.MODEL.HEAD....
def extend_cfg(cfg): '\n Add new config variables.\n\n E.g.\n from yacs.config import CfgNode as CN\n cfg.TRAINER.MY_MODEL = CN()\n cfg.TRAINER.MY_MODEL.PARAM_A = 1.\n cfg.TRAINER.MY_MODEL.PARAM_B = 0.5\n cfg.TRAINER.MY_MODEL.PARAM_C = False\n ' from yacs.config imp...
def setup_cfg(args): cfg = get_cfg_default() extend_cfg(cfg) if args.dataset_config_file: cfg.merge_from_file(args.dataset_config_file) if args.config_file: cfg.merge_from_file(args.config_file) reset_cfg(cfg, args) cfg.freeze() return cfg
def main(args): cfg = setup_cfg(args) if (cfg.SEED >= 0): print('Setting fixed seed: {}'.format(cfg.SEED)) set_random_seed(cfg.SEED) setup_logger(cfg.OUTPUT_DIR) if (torch.cuda.is_available() and cfg.USE_CUDA): torch.backends.cudnn.benchmark = True print_args(args, cfg) ...
def average_ckpt(state_dict, ignore=['optimizer', 'scheduler']): new_dict = dict() print(state_dict['val_result'], state_dict['epoch']) for key in state_dict: if (key in ignore): continue if isinstance(state_dict[key][0], int): new_dict[key] = int(np.average(state_d...
def compute_ci95(res): return ((1.96 * np.std(res)) / np.sqrt(len(res)))
def parse_function(*metrics, directory='', args=None, end_signal=None): print(f'Parsing files in {directory}') subdirs = listdir_nohidden(directory, sort=True) outputs = [] for subdir in subdirs: fpath = osp.join(directory, subdir, 'log.txt') assert check_isfile(fpath) good_to_...
def main(args, end_signal): metric = {'name': args.keyword, 'regex': re.compile(f'\* {args.keyword}: ([\.\deE+-]+)%')} if args.multi_exp: final_results = defaultdict(list) for directory in listdir_nohidden(args.directory, sort=True): directory = osp.join(args.directory, directory) ...
def main(): with open(f'./scripts/{out_name}.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) dataset = COOP_ELEVATER_DATASET writer.writerow(([' '] + dataset)) missed = 0 for seed in seeds: temp_row = [] temp_row.append(f'seed {seed}') ...
def print_args(args, cfg): print('***************') print('** Arguments **') print('***************') optkeys = list(args.__dict__.keys()) optkeys.sort() for key in optkeys: print('{}: {}'.format(key, args.__dict__[key])) print('************') print('** Config **') print('*...
def reset_cfg(cfg, args): if args.root: cfg.DATASET.ROOT = args.root if args.output_dir: cfg.OUTPUT_DIR = args.output_dir if args.resume: cfg.RESUME = args.resume if args.seed: cfg.SEED = args.seed cfg.DATASET.RANDOM_SEED_SAMPLING = args.seed if args.source_...
def extend_cfg(cfg): '\n Add new config variables.\n\n E.g.\n from yacs.config import CfgNode as CN\n cfg.TRAINER.MY_MODEL = CN()\n cfg.TRAINER.MY_MODEL.PARAM_A = 1.\n cfg.TRAINER.MY_MODEL.PARAM_B = 0.5\n cfg.TRAINER.MY_MODEL.PARAM_C = False\n ' from yacs.config imp...
def setup_cfg(args): cfg = get_cfg_default() extend_cfg(cfg) if args.dataset_config_file: cfg.merge_from_file(args.dataset_config_file) if args.config_file: cfg.merge_from_file(args.config_file) reset_cfg(cfg, args) cfg.merge_from_list(args.opts) cfg.freeze() return cfg...
def main(args): cfg = setup_cfg(args) if (cfg.SEED >= 0): print('Setting fixed seed: {}'.format(cfg.SEED)) set_random_seed(cfg.SEED) setup_logger(cfg.OUTPUT_DIR) if (torch.cuda.is_available() and cfg.USE_CUDA): torch.backends.cudnn.benchmark = True print_args(args, cfg) ...
def add_finetuning_args(parser): parser.add_argument('--ds', required=False, help='Evaluation dataset configure file name.', type=str) parser.add_argument('--model', required=True, help='Evaluation model configure file name', type=str) parser.add_argument('--submit-predictions', help='submit predictions a...
def main(): parser = argparse.ArgumentParser(description='Test a classification model, with finetuning.') add_finetuning_args(parser) args = parser.parse_args() args.cfg = args.ds update_config(config, args) args.cfg = args.model update_config(config, args) config.defrost() config....
def add_linear_probing_args(parser): parser.add_argument('--ds', required=False, help='Evaluation dataset configure file name.', type=str) parser.add_argument('--model', required=True, help='Evaluation model configure file name', type=str) parser.add_argument('--submit-predictions', help='submit predictio...
def main(): parser = argparse.ArgumentParser(description='Test a classification model, with linear probing.') add_linear_probing_args(parser) args = parser.parse_args() args.cfg = args.ds update_config(config, args) args.cfg = args.model update_config(config, args) config.defrost() ...
def parse_args(): parser = argparse.ArgumentParser(description='Submit predictions to leaderboard service.') parser.add_argument('--combine_path', required=True, help='Prediction json file path.', type=pathlib.Path) parser.add_argument('--combine_name', default='all_predictions', required=False, help='Out...
def json_prec_dump(data, prec=6): return json.dumps(json.loads(json.dumps(data), parse_float=(lambda x: round(float(x), prec))))
def main(): logging.basicConfig(level=logging.INFO) args = parse_args() all_predictions = defaultdict(list) for prediction_file in args.combine_path.iterdir(): if (prediction_file.suffix != '.json'): print(f'Ignoring file {prediction_file.name} by suffix.') continue ...
def add_zero_shot_args(parser): parser.add_argument('--ds', required=False, help='Evaluation dataset configure file name.', type=str) parser.add_argument('--model', required=True, help='Clip model configure file name', type=str) parser.add_argument('--text_feature_only', help='consider text feature or not...
def load_or_extract_features(args, cfg): if (cfg.MODEL.SPEC.TEXT.TOKENIZER == 'clip'): tokenizer = SimpleTokenizer() elif ('hf_' in cfg.MODEL.SPEC.TEXT.TOKENIZER): tokenizer = HFPTTokenizer(pt_name=cfg.MODEL.SPEC.TEXT.TOKENIZER[3:]) else: tokenizer = None feature_file = os.path...
def load_or_extract_text_features(args, cfg): if (cfg.MODEL.SPEC.TEXT.TOKENIZER == 'clip'): tokenizer = SimpleTokenizer() elif ('hf_' in cfg.MODEL.SPEC.TEXT.TOKENIZER): tokenizer = HFPTTokenizer(pt_name=cfg.MODEL.SPEC.TEXT.TOKENIZER[3:]) else: tokenizer = None feature_file = os...
def main(): parser = argparse.ArgumentParser(description='Zero-shot evaluation script.') add_zero_shot_args(parser) args = parser.parse_args() args.cfg = args.ds update_config(config, args) args.cfg = args.model update_config(config, args) config.defrost() config.NAME = '' conf...
def get_dataset_hub(): vision_dataset_json = (((pathlib.Path(__file__).resolve().parents[1] / 'resources') / 'datasets') / 'vision_datasets.json').read_text() hub = DatasetHub(vision_dataset_json) return hub
class DataClassBase(): def __post_init__(self): self.validate() @classmethod def from_dict(cls, data_content): c = {} for field in dataclasses.fields(cls): d_type = DataClassBase._get_dataclass_type(field.type) if (field.name in data_content): ...
class Tasks(): IC_MULTILABEL = DatasetTypes.IC_MULTILABEL IC_MULTICLASS = DatasetTypes.IC_MULTICLASS OBJECT_DETECTION = DatasetTypes.OD VALID_TYPES = [IC_MULTILABEL, IC_MULTICLASS, OBJECT_DETECTION] @staticmethod def is_valid(task): return (task in Tasks.VALID_TYPES)
class Tracks(): LINEAR_PROBING = 'linear_probing' TRANSFER_LEARNING = 'transfer_learning' ZERO_SHOT = 'zero_shot' VALID_TYPES = [LINEAR_PROBING, TRANSFER_LEARNING, ZERO_SHOT] @staticmethod def is_valid(task, track): if (track not in Tracks.VALID_TYPES): return False ...
@dataclasses.dataclass(frozen=True) class PredictionSubmission(DataClassBase): dataset_name: str model_name: str created_by: str task: str track: str predictions: List def validate(self): vision_dataset_json = (((pathlib.Path(__file__).resolve().parents[1] / 'resources') / 'datase...
@dataclasses.dataclass(frozen=True) class ModelInfoSubmission(DataClassBase): name: str author: str num_params_in_millions: int pretrained_data: str creation_time: str def validate(self): self._check_value('name', (lambda x: x)) self._check_value('author', (lambda x: x)) ...
def log_arg_env_config(args, config, output_dir): logging.info('=> collecting env info (might take some time)') logging.info(('\n' + get_pretty_env_info())) logging.info(pprint.pformat(args)) logging.info(config) logging.info(f'=> saving logging info into: {output_dir}')
def submit_predictions(prediction_list, submit_by, config, track, task): from vision_benchmark.commands.submit_predictions import submit_predictions_to_leaderboard, submit_model_to_leaderboard submission = {'dataset_name': config.DATASET.DATASET, 'model_name': config.MODEL.NAME, 'track': track, 'task': task, ...
def _update_config_from_file(config, cfg_file): config.defrost() with open(cfg_file, 'r') as f: yaml_cfg = yaml.load(f, Loader=yaml.FullLoader) for cfg in yaml_cfg.setdefault('BASE', ['']): if cfg: _update_config_from_file(config, op.join(op.dirname(cfg_file), cfg)) print('...
def update_config(config, args): _update_config_from_file(config, args.cfg) config.defrost() config.merge_from_list(args.opts) config.TRAIN.LR *= comm.world_size (file_name, _) = op.splitext(op.basename(args.cfg)) config.NAME = (file_name + config.NAME) config.RANK = comm.rank if hasat...
class HFPTTokenizer(object): def __init__(self, pt_name=None): self.pt_name = pt_name self.added_sep_token = 0 self.added_cls_token = 0 self.enable_add_tokens = False self.gpt_special_case = ((not self.enable_add_tokens) and ('gpt' in self.pt_name)) if (pt_name is ...
def build_tokenizer(tokenizer_name): tokenizer = None if (tokenizer_name == 'clip'): tokenizer = SimpleTokenizer() elif ('hf_' in tokenizer_name): tokenizer = HFPTTokenizer(pt_name=tokenizer_name[3:]) elif ('hfc_' in tokenizer_name): tokenizer = HFPTTokenizer(pt_name=tokenizer_...
class HFPTTokenizer(object): def __init__(self, pt_name=None): self.pt_name = pt_name self.added_sep_token = 0 self.added_cls_token = 0 self.enable_add_tokens = False self.gpt_special_case = ((not self.enable_add_tokens) and ('gpt' in self.pt_name)) if (pt_name is ...
def get_prompt_templates(): prompt_templates = ['{}.', 'a photo of a {}.', 'a bad photo of a {}.', 'a photo of many {}.', 'a sculpture of a {}.', 'a photo of the hard to see {}.', 'a low resolution photo of the {}.', 'a rendering of a {}.', 'graffiti of a {}.', 'a bad photo of the {}.', 'a cropped photo of the {}...
def prompt_engineering(classnames): prompt_templates = get_prompt_templates() temp_idx = np.random.randint(len(prompt_templates)) if isinstance(classnames, list): classname = random.choice(classnames) else: classname = classnames return prompt_templates[temp_idx].replace('{}', clas...
class Voc2007Classification(torch.utils.data.Dataset): def __init__(self, data_root, image_set='train', transform=None): '\n Pascal voc2007 training/validation data: http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtrainval_06-Nov-2007.tar\n test data: http://host.robots.ox.ac.uk/pascal/VO...
def _is_depthwise(m): return (isinstance(m, nn.Conv2d) and (m.groups == m.in_channels) and (m.groups == m.out_channels))
def _set_wd(cfg, model): without_decay_list = cfg.TRAIN.WITHOUT_WD_LIST without_decay_depthwise = [] without_decay_norm = [] for m in model.modules(): if (_is_depthwise(m) and ('depthwise' in without_decay_list)): without_decay_depthwise.append(m.weight) elif (isinstance(m,...
def build_optimizer(cfg, model): if (cfg.TRAIN.OPTIMIZER == 'timm'): args = cfg.TRAIN.OPTIMIZER_ARGS print(f'=> usage timm optimizer args: {cfg.TRAIN.OPTIMIZER_ARGS}') optimizer = create_optimizer(args, model) return optimizer optimizer = None params = _set_wd(cfg, model) ...
class Comm(object): def __init__(self): self.local_rank = 0 @property def world_size(self): if (not dist.is_available()): return 1 if (not dist.is_initialized()): return 1 return dist.get_world_size() @property def rank(self): if (...
def all_gather(data): '\n Run all_gather on arbitrary picklable data (not necessarily tensors)\n Args:\n data: any picklable object\n Returns:\n list[data]: list of data gathered from each rank\n ' world_size = comm.world_size if (world_size == 1): return [data] buffe...
def reduce_dict(input_dict, average=True): '\n Args:\n input_dict (dict): all the values will be reduced\n average (bool): whether to do average or sum\n Reduce the values in the dictionary from all processes so that process with rank\n 0 has the averaged results. Returns a dict with the sa...
def gather_tensors(tensor): '\n Performs all_gather operation on the provided tensors.\n *** Warning ***: torch.distributed.all_gather has no gradient.\n ' tensors_gather = [torch.ones_like(tensor) for _ in range(comm.world_size)] dist.all_gather(tensors_gather, tensor, async_op=False) tensor...
def setup_logger(final_output_dir, rank, phase): time_str = time.strftime('%Y-%m-%d-%H-%M') log_file = f'{phase}_{time_str}_rank{rank}.txt' final_log_file = os.path.join(final_output_dir, log_file) head = (('%(asctime)-15s:[P:%(process)d]:' + comm.head) + ' %(message)s') logging.basicConfig(filena...
def create_logger(cfg, phase='train'): root_output_dir = Path(cfg.OUTPUT_DIR) dataset = cfg.DATASET.DATASET cfg_name = cfg.NAME final_output_dir = ((root_output_dir / dataset) / cfg_name) print('=> creating {} ...'.format(root_output_dir)) root_output_dir.mkdir(parents=True, exist_ok=True) ...
@TRAINER_REGISTRY.register() class ZeroshotCLIP(TrainerX): def build_model(self): cfg = self.cfg classnames = self.dm.dataset.classnames print(f'Loading CLIP (backbone: {cfg.MODEL.BACKBONE.NAME})') clip_model = load_clip_to_cpu(cfg) clip_model.to(self.device) temp ...
@TRAINER_REGISTRY.register() class ZeroshotCLIP2(ZeroshotCLIP): 'Prompt ensembling.' templates = IMAGENET_TEMPLATES_SELECT def build_model(self): cfg = self.cfg classnames = self.dm.dataset.classnames print(f'Loading CLIP (backbone: {cfg.MODEL.BACKBONE.NAME})') clip_model ...
def create_config(model_name='u256', timestep_rp=50): if (model_name == 'c64'): config = {'model_path': 'symlink/pretrained/64x64_diffusion.pt', 'classifier_path': 'symlink/pretrained/64x64_classifier.pt', 'image_size': 64, 'batch_size': 64, 'use_ddim': False, 'clip_denoised': True, 'classifier_scale': 0....
def setup_dist(): '\n Setup a distributed process group.\n ' if dist.is_initialized(): return os.environ['CUDA_VISIBLE_DEVICES'] = f'{(MPI.COMM_WORLD.Get_rank() % GPUS_PER_NODE)}' comm = MPI.COMM_WORLD backend = 'gloo' if (backend == 'gloo'): hostname = 'localhost' el...
def dev(): '\n Get the device to use for torch.distributed.\n ' if th.cuda.is_available(): return th.device(f'cuda') return th.device('cpu')
def load_state_dict(path, **kwargs): '\n Load a PyTorch file without redundant fetches across MPI ranks.\n ' chunk_size = (2 ** 30) if (MPI.COMM_WORLD.Get_rank() == 0): with bf.BlobFile(path, 'rb') as f: data = f.read() num_chunks = (len(data) // chunk_size) if (l...
def sync_params(params): '\n Synchronize a sequence of Tensors across ranks from rank 0.\n ' for p in params: with th.no_grad(): dist.broadcast(p, 0)
def _find_free_port(): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 0)) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return s.getsockname()[1] finally: s.close()
def convert_module_to_f16(l): '\n Convert primitive modules to float16.\n ' if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): l.weight.data = l.weight.data.half() if (l.bias is not None): l.bias.data = l.bias.data.half()
def convert_module_to_f32(l): '\n Convert primitive modules to float32, undoing convert_module_to_f16().\n ' if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): l.weight.data = l.weight.data.float() if (l.bias is not None): l.bias.data = l.bias.data.float()
def make_master_params(param_groups_and_shapes): '\n Copy model parameters into a (differently-shaped) list of full-precision\n parameters.\n ' master_params = [] for (param_group, shape) in param_groups_and_shapes: master_param = nn.Parameter(_flatten_dense_tensors([param.detach().float(...
def model_grads_to_master_grads(param_groups_and_shapes, master_params): '\n Copy the gradients from the model parameters into the master parameters\n from make_master_params().\n ' for (master_param, (param_group, shape)) in zip(master_params, param_groups_and_shapes): master_param.grad = _f...
def master_params_to_model_params(param_groups_and_shapes, master_params): '\n Copy the master parameter data back into the model parameters.\n ' for (master_param, (param_group, _)) in zip(master_params, param_groups_and_shapes): for ((_, param), unflat_master_param) in zip(param_group, unflatt...
def unflatten_master_params(param_group, master_param): return _unflatten_dense_tensors(master_param, [param for (_, param) in param_group])
def get_param_groups_and_shapes(named_model_params): named_model_params = list(named_model_params) scalar_vector_named_params = ([(n, p) for (n, p) in named_model_params if (p.ndim <= 1)], (- 1)) matrix_named_params = ([(n, p) for (n, p) in named_model_params if (p.ndim > 1)], (1, (- 1))) return [scal...
def master_params_to_state_dict(model, param_groups_and_shapes, master_params, use_fp16): if use_fp16: state_dict = model.state_dict() for (master_param, (param_group, _)) in zip(master_params, param_groups_and_shapes): for ((name, _), unflat_master_param) in zip(param_group, unflatten...
def state_dict_to_master_params(model, state_dict, use_fp16): if use_fp16: named_model_params = [(name, state_dict[name]) for (name, _) in model.named_parameters()] param_groups_and_shapes = get_param_groups_and_shapes(named_model_params) master_params = make_master_params(param_groups_and...
def zero_master_grads(master_params): for param in master_params: param.grad = None
def zero_grad(model_params): for param in model_params: if (param.grad is not None): param.grad.detach_() param.grad.zero_()
def param_grad_or_zeros(param): if (param.grad is not None): return param.grad.data.detach() else: return th.zeros_like(param)
class MixedPrecisionTrainer(): def __init__(self, *, model, use_fp16=False, fp16_scale_growth=0.001, initial_lg_loss_scale=INITIAL_LOG_LOSS_SCALE): self.model = model self.use_fp16 = use_fp16 self.fp16_scale_growth = fp16_scale_growth self.model_params = list(self.model.parameters...
def check_overflow(value): return ((value == float('inf')) or (value == (- float('inf'))) or (value != value))
def get_named_beta_schedule(schedule_name, num_diffusion_timesteps): '\n Get a pre-defined beta schedule for the given name.\n\n The beta schedule library consists of beta schedules which remain similar\n in the limit of num_diffusion_timesteps.\n Beta schedules may be added, but should not be removed...
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): '\n Create a beta schedule that discretizes the given alpha_t_bar function,\n which defines the cumulative product of (1-beta) over time from t = [0,1].\n\n :param num_diffusion_timesteps: the number of betas to produce.\n :p...
class ModelMeanType(enum.Enum): '\n Which type of output the model predicts.\n ' PREVIOUS_X = enum.auto() START_X = enum.auto() EPSILON = enum.auto()
class ModelVarType(enum.Enum): "\n What is used as the model's output variance.\n\n The LEARNED_RANGE option has been added to allow the model to predict\n values between FIXED_SMALL and FIXED_LARGE, making its job easier.\n " LEARNED = enum.auto() FIXED_SMALL = enum.auto() FIXED_LARGE = e...
class LossType(enum.Enum): MSE = enum.auto() RESCALED_MSE = enum.auto() KL = enum.auto() RESCALED_KL = enum.auto() def is_vb(self): return ((self == LossType.KL) or (self == LossType.RESCALED_KL))
class GaussianDiffusion(): '\n Utilities for training and sampling diffusion models.\n\n Ported directly from here, and then adapted over time to further experimentation.\n https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42\n\n ...
def _extract_into_tensor(arr, timesteps, broadcast_shape): '\n Extract values from a 1-D numpy array for a batch of indices.\n\n :param arr: the 1-D numpy array.\n :param timesteps: a tensor of indices into the array to extract.\n :param broadcast_shape: a larger shape of K dimensions with the batch\n...