smart_augmentation/higher/smart_aug/test_dataug.py

176 lines
6.5 KiB
Python
Raw Normal View History

2020-01-24 14:32:37 -05:00
""" Script to run experiment on smart augmentation.
"""
2020-01-31 16:43:10 -05:00
import sys
2020-01-31 10:34:44 -05:00
from LeNet import *
2019-11-08 11:28:06 -05:00
from dataug import *
2019-11-13 11:44:29 -05:00
#from utils import *
from train_utils import *
2020-02-19 11:54:54 -05:00
from transformations import TF_loader
2019-11-08 11:28:06 -05:00
postfix=''
2020-02-19 11:54:54 -05:00
TF_loader=TF_loader()
2020-01-24 14:32:37 -05:00
device = torch.device('cuda') #Select device to use
2019-11-08 11:28:06 -05:00
if device == torch.device('cpu'):
device_name = 'CPU'
else:
device_name = torch.cuda.get_device_name(device)
2020-01-30 11:21:25 -05:00
torch.backends.cudnn.benchmark = True #Faster if same input size #Not recommended for reproductibility
#Increase reproductibility
torch.manual_seed(0)
np.random.seed(0)
2019-11-08 11:28:06 -05:00
##########################################
if __name__ == "__main__":
2020-01-24 14:32:37 -05:00
#Task to perform
2019-12-04 12:28:32 -05:00
tasks={
2020-02-14 13:57:17 -05:00
#'classic',
'aug_model'
2019-12-04 12:28:32 -05:00
}
2020-01-24 14:32:37 -05:00
#Parameters
2020-01-13 18:02:36 -05:00
n_inner_iter = 1
epochs = 200
2020-01-21 13:53:07 -05:00
dataug_epoch_start=0
Nb_TF_seq=3
optim_param={
'Meta':{
'optim':'Adam',
'lr':1e-2, #1e-2
2020-02-19 11:54:54 -05:00
'epoch_start': 2, #0 / 2 (Resnet?)
'reg_factor': 0.001,
},
'Inner':{
'optim': 'SGD',
2020-02-14 13:57:17 -05:00
'lr':1e-1, #1e-2/1e-1 (ResNet)
'momentum':0.9, #0.9
'decay':0.0005, #0.0005
'nesterov':False, #False (True: Bad behavior w/ Data_aug)
2020-02-14 13:57:17 -05:00
'scheduler':'cosine', #None, 'cosine', 'multiStep', 'exponential'
}
}
2019-11-08 11:28:06 -05:00
2020-01-24 14:32:37 -05:00
#Models
#model = LeNet(3,10)
#model = ResNet(num_classes=10)
import torchvision.models as models
2020-01-30 11:21:25 -05:00
#model=models.resnet18()
model_name = 'resnet18' #'wide_resnet50_2' #'resnet18' #str(model)
model = getattr(models.resnet, model_name)(pretrained=False, num_classes=len(dl_train.dataset.classes))
2019-12-04 12:28:32 -05:00
2019-11-08 11:28:06 -05:00
#### Classic ####
2019-12-04 12:28:32 -05:00
if 'classic' in tasks:
torch.cuda.reset_max_memory_allocated() #reset_peak_stats
torch.cuda.reset_max_memory_cached() #reset_peak_stats
2020-02-03 12:55:54 -05:00
t0 = time.perf_counter()
model = model.to(device)
2019-12-04 12:28:32 -05:00
2020-01-31 16:43:10 -05:00
2020-02-21 15:29:34 -05:00
print("{} on {} for {} epochs{}".format(model_name, device_name, epochs, postfix))
#print("RandAugment(N{}-M{:.2f})-{} on {} for {} epochs{}".format(rand_aug['N'],rand_aug['M'],model_name, device_name, epochs, postfix))
log= train_classic(model=model, opt_param=optim_param, epochs=epochs, print_freq=10)
#log= train_classic_higher(model=model, epochs=epochs)
2019-12-04 12:28:32 -05:00
2020-02-03 12:55:54 -05:00
exec_time=time.perf_counter() - t0
max_allocated = torch.cuda.max_memory_allocated()/(1024.0 * 1024.0)
max_cached = torch.cuda.max_memory_cached()/(1024.0 * 1024.0) #torch.cuda.max_memory_reserved() #MB
2019-12-04 12:28:32 -05:00
####
print('-'*9)
times = [x["time"] for x in log]
2020-02-03 12:06:32 -05:00
out = {"Accuracy": max([x["acc"] for x in log]),
"Time": (np.mean(times),np.std(times), exec_time),
'Optimizer': optim_param['Inner'],
"Device": device_name,
"Memory": [max_allocated, max_cached],
#"Rand_Aug": rand_aug,
2020-02-03 12:06:32 -05:00
"Log": log}
2020-02-03 11:21:54 -05:00
print(model_name,": acc", out["Accuracy"], "in:", out["Time"][0], "+/-", out["Time"][1])
2020-02-21 15:29:34 -05:00
filename = "{}-{} epochs".format(model_name,epochs)+postfix
#print("RandAugment-",model_name,": acc", out["Accuracy"], "in:", out["Time"][0], "+/-", out["Time"][1])
2020-02-21 15:29:34 -05:00
#filename = "RandAugment(N{}-M{:.2f})-{}-{} epochs".format(rand_aug['N'],rand_aug['M'],model_name,epochs)+postfix
2020-01-24 14:32:37 -05:00
with open("../res/log/%s.json" % filename, "w+") as f:
2020-02-03 11:21:54 -05:00
try:
json.dump(out, f, indent=True)
print('Log :\"',f.name, '\" saved !')
except:
print("Failed to save logs :",f.name)
print(sys.exc_info()[1])
2019-12-04 12:28:32 -05:00
2020-02-03 11:21:54 -05:00
try:
plot_resV2(log, fig_name="../res/"+filename)
except:
print("Failed to plot res")
print(sys.exc_info()[1])
2019-12-04 12:28:32 -05:00
2020-02-03 12:55:54 -05:00
print('Execution Time (s): %.00f '%(exec_time))
2019-12-04 12:28:32 -05:00
print('-'*9)
2020-01-29 06:36:12 -05:00
#### Augmented Model ####
if 'aug_model' in tasks:
tf_config='../config/invScale_wide_tf_config.json'#'../config/base_tf_config.json'
2020-02-14 13:57:17 -05:00
tf_dict, tf_ignore_mag =TF_loader.load_TF_dict(tf_config)
torch.cuda.reset_max_memory_allocated() #reset_peak_stats
2020-02-10 14:50:45 -05:00
torch.cuda.reset_max_memory_cached() #reset_peak_stats
2020-02-03 12:55:54 -05:00
t0 = time.perf_counter()
2020-01-29 06:36:12 -05:00
2020-01-31 16:43:10 -05:00
model = Higher_model(model, model_name) #run_dist_dataugV3
if n_inner_iter !=0:
aug_model = Augmented_model(
Data_augV5(TF_dict=tf_dict,
N_TF=Nb_TF_seq,
mix_dist=0.5,
fixed_prob=False,
fixed_mag=False,
shared_mag=False,
TF_ignore_mag=tf_ignore_mag), model).to(device)
else:
aug_model = Augmented_model(RandAug(TF_dict=tf_dict, N_TF=Nb_TF_seq), model).to(device)
2020-01-29 06:36:12 -05:00
2020-02-21 15:29:34 -05:00
print("{} on {} for {} epochs - {} inner_it{}".format(str(aug_model), device_name, epochs, n_inner_iter, postfix))
2020-01-29 06:36:12 -05:00
log= run_dist_dataugV3(model=aug_model,
epochs=epochs,
inner_it=n_inner_iter,
dataug_epoch_start=dataug_epoch_start,
opt_param=optim_param,
print_freq=10,
2020-01-29 06:36:12 -05:00
unsup_loss=1,
2020-01-30 11:21:25 -05:00
hp_opt=False,
save_sample_freq=None)
2020-01-29 06:36:12 -05:00
2020-02-03 12:55:54 -05:00
exec_time=time.perf_counter() - t0
2020-02-10 14:50:45 -05:00
max_allocated = torch.cuda.max_memory_allocated()/(1024.0 * 1024.0)
max_cached = torch.cuda.max_memory_cached()/(1024.0 * 1024.0) #torch.cuda.max_memory_reserved() #MB
2020-01-29 06:36:12 -05:00
####
print('-'*9)
times = [x["time"] for x in log]
2020-02-03 12:06:32 -05:00
out = {"Accuracy": max([x["acc"] for x in log]),
"Time": (np.mean(times),np.std(times), exec_time),
'Optimizer': optim_param,
"Device": device_name,
2020-02-10 14:50:45 -05:00
"Memory": [max_allocated, max_cached],
2020-02-14 13:57:17 -05:00
"TF_config": tf_config,
2020-02-03 12:06:32 -05:00
"Param_names": aug_model.TF_names(),
"Log": log}
2020-01-29 06:36:12 -05:00
print(str(aug_model),": acc", out["Accuracy"], "in:", out["Time"][0], "+/-", out["Time"][1])
filename = "{}-{} epochs (dataug:{})- {} in_it".format(str(aug_model),epochs,dataug_epoch_start,n_inner_iter)+postfix
2020-01-29 06:36:12 -05:00
with open("../res/log/%s.json" % filename, "w+") as f:
try:
json.dump(out, f, indent=True)
print('Log :\"',f.name, '\" saved !')
except:
print("Failed to save logs :",f.name)
2020-02-03 11:21:54 -05:00
print(sys.exc_info()[1])
2020-01-29 06:36:12 -05:00
try:
plot_resV2(log, fig_name="../res/"+filename, param_names=aug_model.TF_names())
except:
print("Failed to plot res")
2020-02-03 11:21:54 -05:00
print(sys.exc_info()[1])
2020-01-29 06:36:12 -05:00
2020-02-03 12:55:54 -05:00
print('Execution Time (s): %.00f '%(exec_time))
2020-01-31 10:34:44 -05:00
print('-'*9)