-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHDA.py
More file actions
177 lines (157 loc) · 5.36 KB
/
HDA.py
File metadata and controls
177 lines (157 loc) · 5.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import numpy as np
import torchvision
import torchvision.transforms as transforms
import torch
from torchvision.datasets import ImageFolder
from models import get_cell_based_tiny_net
from nats_bench import create
import time
import pandas as pd
import random
from DownsampledImageNet import ImageNet16
# ==============================================
# GLOBAL VARIABLE:
# Batch size for RBFleX-NAS
# N_GAMMA: Number of network to detect hyperparameter for RBF kernel
# ==============================================
batch_size_NE = 3
N_GAMMA = 10
# ==============================================
# GLOBAL VARIABLE: Experiment for RBFleX-NAS
# - cifar10
# - cifar100
# - ImageNet16-120
# ==============================================
dataset = 'cifar10'
# ==============================================
# GLOBAL VARIABLE: create a searchspace
# This example is NATS-Bench-SSS
# ==============================================
benchmark_root = "./designspace/NATS-Bench-SSS/NATS-sss-v1_0-50262-simple"
# NAS Benchmark
print('Loading...NAT Bench '+"sss")
searchspace = create(benchmark_root, "sss", fast_mode=True, verbose=False)
# ==============================================
# GLOBAL VARIABLE: create a dataloader
# This example is cifar-10
# ==============================================
img_root = "./dataset"
print('==> Preparing data..')
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
imgset = torchvision.datasets.CIFAR10(
root=img_root+'/cifar10', train=True, download=True, transform=transform_train)
img_loader = torch.utils.data.DataLoader(
imgset, batch_size=batch_size_NE, shuffle=True, num_workers=1, pin_memory=True)
#######################################
# Normalization
# - Column-wise normalization
#######################################
def normalize(x, axis=None):
x_min = x.min(axis=axis, keepdims=True)
x_max = x.max(axis=axis, keepdims=True)
x_max[x_max == x_min] = 1
x_min[x_max == x_min] = 0
return (x - x_min) / (x_max - x_min)
def main():
# Reproducibility
print('==> Reproducibility..')
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.set_printoptions(precision=8)
np.random.seed(1)
torch.manual_seed(1)
# GPU
# Check that CUDA is available
# device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Check that MPS is available
if torch.cuda.is_available():
device = 'cuda:0'
else:
device = 'cpu'
print('device GPU: ', device)
tkwargs = {
"dtype": torch.float64,
"device": device,
"requires_grad":False
}
# Hyperparameter
print('==> Preparing hyperparameters..')
batch_space = random.sample(range(len(searchspace)), N_GAMMA)
########################
# Compute Distance and Kernel Matrix
########################
def counting_forward_hook(module, inp, out):
with torch.no_grad():
arr = out.view(batch_size_NE, -1)
network.K = torch.cat((network.K, arr),1)
def counting_forward_hook_FC(module, inp, out):
with torch.no_grad():
if isinstance(inp, tuple):
inp = inp[0]
network.Q = inp
#######################################
# Self-detecting Hyperparameter
#######################################
GAMMA_K_list = []
GAMMA_Q_list = []
for id in range(N_GAMMA):
uid = batch_space[id]
config = searchspace.get_net_config(uid, dataset)
network = get_cell_based_tiny_net(config)
network = network.to(device)
net_counter = list(network.named_modules())
net_counter = len(net_counter)
NC = 0
for name, module in network.named_modules():
NC += 1
if 'ReLU' in str(type(module)):
module.register_forward_hook(counting_forward_hook)
if NC == net_counter:
module.register_forward_hook(counting_forward_hook_FC)
with torch.no_grad():
network.K = torch.empty(0, device=device)
network.Q = torch.empty(0, device=device)
network(x[0:batch_size_NE,:,:,:].to(device))
Output_matrix = network.K
Last_matrix = network.Q
with torch.no_grad():
Output_matrix = Output_matrix.cpu().numpy()
Last_matrix = Last_matrix.cpu().numpy()
for i in range(batch_size_NE-1):
for j in range(i+1,batch_size_NE):
z1 = Output_matrix[i,:]
z2 = Output_matrix[j,:]
m1 = np.mean(z1)
m2 = np.mean(z2)
M = (m1-m2)**2
z1 = z1-m1
z2 = z2-m2
s1 = np.mean(z1**2)
s2 = np.mean(z2**2)
if s1+s2 != 0:
candi_gamma_K = M/((s1+s2)*2)
GAMMA_K_list.append(candi_gamma_K)
for i in range(batch_size_NE-1):
for j in range(i+1,batch_size_NE):
z1 = Last_matrix[i,:]
z2 = Last_matrix[j,:]
m1 = np.mean(z1)
m2 = np.mean(z2)
M = (m1-m2)**2
z1 = z1-m1
z2 = z2-m2
s1 = np.mean(z1**2)
s2 = np.mean(z2**2)
if s1+s2 != 0:
candi_gamma_Q = M/((s1+s2)*2)
GAMMA_Q_list.append(candi_gamma_Q)
GAMMA_K = np.min(np.array(GAMMA_K_list))
GAMMA_Q = np.min(np.array(GAMMA_Q_list))
print('==> Detected Hyperparameter Gamma ..')
print('gamma_k:',GAMMA_K)
print('gamma_q:',GAMMA_Q)