if isinstance(self.pretrained, str): self.apply(_init_weights) logger = get_root_logger() logger.info(f'load model from: {self.pretrained}') checkpoint = torch.load(self.pretrained, map_location='cpu') state_dict = checkpoint['model'] state_dict['patch_embed.proj.weight'] = state_dict['patch_embed.proj.weight'].unsqueeze(2).repeat(1,1,self.patch_size[0],1,1) / self.patch_size[0] ## Duplicate weights for temporal attention and temporal norm # new_state_dict = state_dict.copy() # for key in state_dict: # if 'blocks' in key and 'attn' in key and 'relative' not in key and 'mask' not in key: # new_key = key.replace('attn','temporal_attn') # if not new_key in state_dict: # new_state_dict[new_key] = state_dict[key] # else: # new_state_dict[new_key] = state_dict[new_key] # if 'blocks' in key and 'norm1' in key and 'relative' not in key and 'mask' not in key: # new_key = key.replace('norm1','temporal_norm') # if not new_key in state_dict: # new_state_dict[new_key] = state_dict[key] # else: # new_state_dict[new_key] = state_dict[new_key] # state_dict = new_state_dict msg = self.load_state_dict(state_dict, strict=False) logger.info('Missing keys: {}'.format(msg.missing_keys)) logger.info('Unexpected keys: {}'.format(msg.unexpected_keys)) logger.info(f"=> loaded successfully '{self.pretrained}'") del checkpoint torch.cuda.empty_cache() elif self.pretrained is None: self.apply(_init_weights) else: raise TypeError('pretrained must be a str or None')
时间: 2023-06-19 07:06:42 浏览: 187
python中 _、__、__xx__()区别及使用场景
这段代码是初始化模型的代码。首先判断是否需要加载预训练模型,如果需要,则从指定的路径加载预训练模型的参数,并将模型的 patch_embed.proj.weight 层的权重进行重新计算,以适应输入的 patch 大小。然后将加载的参数应用到当前模型中。如果没有指定预训练模型,则直接进行权重初始化。如果预训练参数既不是字符串也不是 None,则会报错。
阅读全文