JustAGeek commited on
Commit
8fb0f90
·
verified ·
1 Parent(s): 08306d3

Delete duplicate/old file: \/modelADT.py

Browse files
Files changed (1) hide show
  1. ///modelADT.py +0 -289
///modelADT.py DELETED
@@ -1,289 +0,0 @@
1
- #!/usr/bin/python
2
- '''
3
- Defines a generic wrapper class for all the network models
4
- Utilizes params.py to create, initiate, load and train the network.
5
- '''
6
- import torch
7
- import numpy as np
8
- from collections import OrderedDict
9
- import scipy.io
10
- from torch.autograd import Variable
11
- import os
12
- from Generators import *
13
- from utils import *
14
-
15
- class ModelADT():
16
- def name(self):
17
- return 'Pix2PixModel'
18
-
19
- def initialize(self, opt):
20
-
21
- self.opt = opt
22
- # self.gpu_ids = opt.gpu_ids
23
- gpu_ids = []
24
- for i in range(torch.cuda.device_count()):
25
- gpu_ids.append(str(i))
26
- print(gpu_ids)
27
- self.gpu_ids = gpu_ids
28
- self.isTrain = opt.isTrain
29
- self.loss_weight = opt.lambda_L
30
- self.reg_loss_weight = opt.lambda_reg
31
- self.cross_loss_weight = opt.lambda_cross
32
- self.device = torch.device('cuda:{}'.format(self.gpu_ids[0])) # if self.gpu_ids else torch.device('cpu')
33
-
34
- print(self.device)
35
- self.model_name = self.opt.name
36
- self.save_dir = os.path.join(self.opt.checkpoints_save_dir, self.model_name)
37
- self.load_dir = os.path.join(self.opt.checkpoints_load_dir, self.model_name)
38
- self.results_save_dir = opt.results_dir
39
-
40
- self.loss_names = []
41
- self.visual_names = []
42
- self.image_paths = []
43
-
44
- self.loss_names = ['loss_criterion']
45
- self.visual_names = ['output']
46
-
47
-
48
- self.net = get_model_funct(self.opt.net)(self.opt, self.gpu_ids)
49
- self.net = self.net.to(self.device)
50
-
51
- if self.isTrain:
52
- if self.opt.loss_type == "L2":
53
- self.loss_criterion = torch.nn.MSELoss()
54
- elif self.opt.loss_type == "L1":
55
- self.loss_criterion = torch.nn.L1Loss()
56
- elif self.opt.loss_type == "L1_sumL2":
57
- self.loss_criterion = torch.nn.L1Loss()
58
- elif self.opt.loss_type == "L2_sumL2":
59
- self.loss_criterion = torch.nn.MSELoss()
60
- elif self.opt.loss_type == "L2_sumL1":
61
- self.loss_criterion = torch.nn.MSELoss()
62
- elif self.opt.loss_type == "L2_offset_loss":
63
- self.loss_criterion = torch.nn.MSELoss()
64
- elif self.opt.loss_type == "L1_offset_loss":
65
- self.loss_criterion = torch.nn.L1Loss()
66
- elif self.opt.loss_type == "L1_sumL2_cross":
67
- self.loss_criterion = torch.nn.MSELoss()
68
- elif self.opt.loss_type == "L2_sumL2_cross":
69
- self.loss_criterion = torch.nn.MSELoss()
70
- self.cross_loss_criterion = torch.nn.NLLLoss()
71
-
72
- # initialize optimizers
73
- self.optimizers = []
74
- self.optimizer = torch.optim.Adam(self.net.parameters(),lr=opt.lr, betas=(opt.beta1, 0.999), weight_decay=opt.weight_decay)
75
- self.optimizers.append(self.optimizer)
76
-
77
- # load and print networks; create schedulers
78
- def setup(self, opt, parser=None):
79
- if self.isTrain:
80
- self.schedulers = [get_scheduler(optimizer, opt) for optimizer in self.optimizers]
81
-
82
- if not self.isTrain or opt.continue_train:
83
- self.load_networks(opt.starting_epoch_count)
84
- if self.isTrain and opt.continue_train:
85
- self.load_training_state(opt.starting_epoch_count)
86
- self.print_networks(opt.verbose)
87
-
88
- # make models eval mode during test time
89
- def eval(self):
90
- self.net.eval()
91
-
92
- # used in test time, wrapping `forward` in no_grad() so we don't save
93
- # intermediate steps for backprop
94
- def test(self):
95
- with torch.no_grad():
96
- self.forward()
97
-
98
- def save_outputs(self):
99
- if not os.path.exists(self.results_save_dir):
100
- os.makedirs(self.results_save_dir, exist_ok=True)
101
- to_save_dict = {}
102
- for tensor in self.visual_names:
103
- tensor_val = getattr(self, tensor).data.cpu().numpy()
104
- to_save_dict[tensor] = tensor_val
105
- scipy.io.savemat(self.results_save_dir+".mat", mdict=to_save_dict)
106
-
107
-
108
- # update learning rate (called once every epoch)
109
- def update_learning_rate(self):
110
- for scheduler in self.schedulers:
111
- scheduler.step()
112
- lr = self.optimizers[0].param_groups[0]['lr']
113
- print('learning rate = %.7f' % lr)
114
-
115
- # return visualization images. train.py will display these images, and save the images to a html
116
- def get_current_visuals(self):
117
- visual_ret = OrderedDict()
118
- for name in self.visual_names:
119
- if isinstance(name, str):
120
- visual_ret[name] = getattr(self, name)
121
- return visual_ret
122
-
123
- # return traning losses/errors. train.py will print out these errors as debugging information
124
- def get_current_losses(self):
125
- errors_ret = OrderedDict()
126
- for name in self.loss_names:
127
- if isinstance(name, str):
128
- # float(...) works for both scalar tensor and float number
129
- errors_ret[name] = float(getattr(self, 'loss_' + name))
130
- return errors_ret
131
-
132
- # save models to the disk
133
- def save_networks(self, epoch):
134
- name = self.model_name
135
- save_filename = '%s_net_%s.pth' % (epoch, name)
136
- if not os.path.exists(self.save_dir):
137
- os.makedirs(self.save_dir)
138
- save_path = os.path.join(self.save_dir, save_filename)
139
- net = self.net
140
- print(save_path)
141
- print('net'+name)
142
- if len(self.gpu_ids) > 0 and torch.cuda.is_available() and hasattr(net, 'module'):
143
- torch.save(net.module.cpu().state_dict(), save_path)
144
- else:
145
- torch.save(net.cpu().state_dict(), save_path)
146
- net.to(self.device)
147
-
148
- # save optimizer, scheduler, and RNG state
149
- if self.isTrain:
150
- optim_filename = '%s_optim_%s.pth' % (epoch, self.model_name)
151
- optim_path = os.path.join(self.save_dir, optim_filename)
152
- save_dict = {
153
- 'optimizer': self.optimizer.state_dict(),
154
- 'scheduler': self.schedulers[0].state_dict() if self.schedulers else None,
155
- 'rng_torch': torch.random.get_rng_state(),
156
- 'rng_numpy': np.random.get_state(),
157
- }
158
- if torch.cuda.is_available():
159
- save_dict['rng_cuda'] = torch.cuda.get_rng_state_all()
160
- torch.save(save_dict, optim_path)
161
-
162
- def __patch_instance_norm_state_dict(self, state_dict, module, keys, i=0):
163
- key = keys[i]
164
- if i + 1 == len(keys): # at the end, pointing to a parameter/buffer
165
- if module.__class__.__name__.startswith('InstanceNorm') and (key == 'running_mean' or key == 'running_var'):
166
- if getattr(module, key) is None:
167
- state_dict.pop('.'.join(keys))
168
- if module.__class__.__name__.startswith('InstanceNorm') and (key == 'num_batches_tracked'):
169
- state_dict.pop('.'.join(keys))
170
- else:
171
- self.__patch_instance_norm_state_dict(state_dict, getattr(module, key), keys, i + 1)
172
-
173
- # load models from the disk
174
- def load_networks(self, epoch, load_dir=""):
175
- """
176
- epoch (int/str): epoch index / "best" / "latest"
177
- """
178
- assert isinstance(epoch,int) or epoch=="best" or epoch=="latest"
179
- load_filename = f'{epoch}_net_{self.model_name}.pth'
180
-
181
- if load_dir:
182
- # use given load dir
183
- load_path = os.path.join(load_dir, self.model_name, load_filename)
184
- else:
185
- # use default load dir
186
- load_path = os.path.join(self.load_dir, load_filename)
187
-
188
- net = self.net
189
- if isinstance(net, torch.nn.DataParallel):
190
- net = net.module
191
- print('loading the model from %s' % load_path)
192
- # if you are using PyTorch newer than 0.4 (e.g., built from
193
- # GitHub source), you can remove str() on self.device
194
- state_dict = torch.load(load_path, weights_only=False)
195
- if hasattr(state_dict, '_metadata'):
196
- del state_dict._metadata
197
-
198
- # patch InstanceNorm checkpoints prior to 0.4
199
- print(state_dict.keys())
200
- for key in list(state_dict.keys()): # need to copy keys here because we mutate in loop
201
- self.__patch_instance_norm_state_dict(state_dict, net, key.split('.'))
202
- net.load_state_dict(state_dict)
203
- net = net.to(self.device)
204
-
205
- # load optimizer and scheduler state from disk
206
- def load_training_state(self, epoch):
207
- optim_filename = f'{epoch}_optim_{self.model_name}.pth'
208
- load_path = os.path.join(self.load_dir, optim_filename)
209
- if os.path.exists(load_path):
210
- print(f'loading optimizer/scheduler from {load_path}')
211
- state = torch.load(load_path, weights_only=False)
212
- self.optimizer.load_state_dict(state['optimizer'])
213
- if state.get('scheduler') and self.schedulers:
214
- self.schedulers[0].load_state_dict(state['scheduler'])
215
- # Restore RNG states for session continuity
216
- if 'rng_torch' in state:
217
- torch.random.set_rng_state(state['rng_torch'])
218
- if 'rng_numpy' in state:
219
- np.random.set_state(state['rng_numpy'])
220
- if 'rng_cuda' in state and torch.cuda.is_available():
221
- torch.cuda.set_rng_state_all(state['rng_cuda'])
222
- else:
223
- print(f'No optimizer state found at {load_path}, starting fresh')
224
-
225
- # print network information
226
- def print_networks(self, verbose):
227
- print('---------- Networks initialized -------------')
228
- net = self.net
229
- name = self.model_name
230
- num_params = 0
231
- for param in net.parameters():
232
- num_params += param.numel()
233
- if verbose:
234
- print(net)
235
- print('[Network %s] Total number of parameters : %.3f M' % (name, num_params / 1e6))
236
- print('-----------------------------------------------')
237
-
238
- # set requies_grad=Fasle to avoid computation
239
- def set_requires_grad(self, nets, requires_grad=False):
240
- if not isinstance(nets, list):
241
- nets = [nets]
242
- for net in nets:
243
- if net is not None:
244
- for param in net.parameters():
245
- param.requires_grad = requires_grad
246
-
247
- # Set the input and target data for the network to train on/evaluate against
248
- def set_data(self, input, target, convert=False, shuffle_channel=False):
249
- shape_in = input.shape
250
- if shuffle_channel:
251
- self.input = input[:,torch.randperm(shape_in[1]),:,:]
252
- else:
253
- self.input = input
254
- self.target = target
255
- if convert:
256
- self.input, self.target = Variable(self.input), Variable(self.target)
257
-
258
- self.input = self.input.to(self.device)
259
- self.target = self.target.to(self.device)
260
-
261
- # Define the forward pass to compute loss
262
- def forward(self):
263
- self.output = self.net(self.input)
264
- if self.opt.loss_type != "NoLoss":
265
- self.loss = self.loss_weight*self.loss_criterion(self.output, self.target)
266
-
267
- if self.opt.loss_type == "L1_sumL2" or self.opt.loss_type == "L2_sumL2":
268
- self.loss += self.reg_loss_weight*torch.norm(self.output).div(self.output.numel())
269
- self.reg_loss = self.reg_loss_weight*torch.norm(self.output).div(self.output.numel())
270
-
271
- if self.opt.loss_type == "L2_sumL1":
272
- self.loss += self.reg_loss_weight*torch.norm(self.output,p=1).div(self.output.numel())
273
- self.reg_loss = self.reg_loss_weight*torch.norm(self.output,p=1).div(self.output.numel())
274
-
275
- if self.opt.loss_type == "L1_sumL2_cross" or self.opt.loss_type == "L2_sumL2_cross":
276
- self.loss += self.reg_loss_weight*torch.norm(self.output).div(self.output.numel())
277
- self.loss += self.cross_loss_weight*self.cross_loss_criterion(self.output.flatten(start_dim=1),self.target.flatten(start_dim=1))
278
-
279
- if self.opt.loss_type == "L1_offset_loss" or self.opt.loss_type == "L2_offset_loss":
280
- self.loss += self.reg_loss_weight*torch.norm(self.output).div(self.output.numel())
281
-
282
- def backward(self):
283
- self.loss.backward(retain_graph=True)
284
-
285
- def optimize_parameters(self):
286
- self.forward()
287
- self.backward()
288
- self.optimizer.step()
289
- self.optimizer.zero_grad()