Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Download model if not exists (New Feature) #29

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions models/vgg_.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
"""
Mostly copy-paste from torchvision references.
"""
from posixpath import split
import torch
import torch.nn as nn
import os
from tqdm import tqdm
import urllib.request


__all__ = [
Expand All @@ -23,14 +27,13 @@
'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth',
}

checkpoints_dir = os.path.join(os.path.dirname(__file__), "../checkpoints/")

model_paths = {
'vgg16_bn': '/apdcephfs/private_changanwang/checkpoints/vgg16_bn-6c64b313.pth',
'vgg16': '/apdcephfs/private_changanwang/checkpoints/vgg16-397923af.pth',

'vgg16_bn': os.path.join(checkpoints_dir,'vgg16_bn-6c64b313.pth'),
'vgg16': os.path.join(checkpoints_dir,'vgg16-397923af.pth'),
}


class VGG(nn.Module):

def __init__(self, features, num_classes=1000, init_weights=True):
Expand Down Expand Up @@ -98,11 +101,30 @@ def make_layers(cfg, batch_norm=False, sync=False):
}


class DownloadProgressBar(tqdm):
def update_to(self, b=1, bsize=1, tsize=None):
if tsize is not None:
self.total = tsize
self.update(b * bsize - self.n)

def download_arch_if_not_exists(arch):
if not os.path.exists(model_paths[arch]):
print(f"{arch} model not found.")
chunk_size = 1024
os.makedirs(checkpoints_dir, exist_ok=True)

url = model_urls[arch]
filename = os.path.basename(url)
output_path = os.path.join(checkpoints_dir, filename)
with DownloadProgressBar(unit='B', unit_scale=True, miniters=1, desc=url.split('/')[-1]) as t:
urllib.request.urlretrieve(url, filename=output_path, reporthook=t.update_to)

def _vgg(arch, cfg, batch_norm, pretrained, progress, sync=False, **kwargs):
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm, sync=sync), **kwargs)
if pretrained:
download_arch_if_not_exists(arch)
state_dict = torch.load(model_paths[arch])
model.load_state_dict(state_dict)
return model
Expand Down