GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — cGAN_tutorial/main.py at main · snath-xoc/cGAN_tutorial Expand file tree/ Copy pathmain.pyMore file actions executable file ·339 lines (294 loc) · 12.2 KB / Copy pathmain.pyFile metadata and controlsexecutable file ·339 lines (294 loc) · 12.2 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 import wandb import argparse import gc import json import os #os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" # suppress TF debug message spam in v2.12 os.environ["TF_USE_LEGACY_KERAS"] = "1" import yaml from pathlib import Path import matplotlib matplotlib.use("Agg") # noqa: E702 import numpy as np import pandas as pd from data import all_fcst_fields from evaluation import evaluate_multiple_checkpoints, plot_histograms from config import set_gpu_mode, read_downscaling_factor import setupdata import setupmodel from tensorflow import config as tf_config gpu_devices = tf_config.list_physical_devices('GPU') print(gpu_devices) if len(gpu_devices) == 0: print('GPU devices are not being seen') if __name__ == "__main__": set_gpu_mode() # set up whether to use GPU, and mem alloc mode df_dict = read_downscaling_factor() # read downscaling params parser = argparse.ArgumentParser() parser.add_argument("--config", help="Path to configuration file") parser.add_argument("--tune", dest="tune", action="store_true",) parser.add_argument("--log_wandb", dest="log_wandb", action="store_true", default=False) parser.set_defaults(do_training=True) parser.add_argument( "--no_train", dest="do_training", action="store_false", help="Do NOT carry out training, only perform eval", ) parser.add_argument( "--restart", dest="restart", action="store_true", help="Restart training from latest checkpoint", ) group = parser.add_mutually_exclusive_group() group.add_argument( "--eval_full", dest="evalnum", action="store_const", const="full" ) group.add_argument( "--eval_short", dest="evalnum", action="store_const", const="short" ) group.add_argument( "--eval_blitz", dest="evalnum", action="store_const", const="blitz" ) parser.set_defaults(evalnum=None) parser.set_defaults(evaluate=False) parser.set_defaults(plot_ranks=False) parser.add_argument( "--evaluate", dest="evaluate", action="store_true", help="Include evaluation on full-size images", ) parser.add_argument( "--plot_ranks", dest="plot_ranks", action="store_true", help="Plot rank histograms", ) args = parser.parse_args() if args.evaluate and args.evalnum is None: raise RuntimeError( "You asked for evaluation to occur, but did not pass in '--eval_full', '--eval_short', or '--eval_blitz' to specify length of evaluation" ) # Read in the configurations if args.config is not None: config_path = args.config else: raise Exception("Please specify configuration!") with open(config_path, "r") as f: try: setup_params = yaml.safe_load(f) # print(setup_params) except yaml.YAMLError as exc: print(exc) mode = setup_params["GENERAL"]["mode"] arch = setup_params["MODEL"]["architecture"] padding = setup_params["MODEL"]["padding"] log_folder = setup_params["SETUP"]["log_folder"] problem_type = setup_params["GENERAL"]["problem_type"] filters_gen = setup_params["GENERATOR"]["filters_gen"] lr_gen = setup_params["GENERATOR"]["learning_rate_gen"] noise_channels = setup_params["GENERATOR"]["noise_channels"] latent_variables = setup_params["GENERATOR"]["latent_variables"] filters_disc = setup_params["DISCRIMINATOR"]["filters_disc"] lr_disc = setup_params["DISCRIMINATOR"]["learning_rate_disc"] train_years = setup_params["TRAIN"]["train_years"] training_weights = setup_params["TRAIN"]["training_weights"] num_samples = setup_params["TRAIN"]["num_samples"] steps_per_checkpoint = setup_params["TRAIN"]["steps_per_checkpoint"] batch_size = setup_params["TRAIN"]["batch_size"] kl_weight = setup_params["TRAIN"]["kl_weight"] ensemble_size = setup_params["TRAIN"]["ensemble_size"] CLtype = setup_params["TRAIN"]["CL_type"] content_loss_weight = setup_params["TRAIN"]["content_loss_weight"] val_years = setup_params["VAL"]["val_years"] val_size = setup_params["VAL"]["val_size"] num_images = setup_params["EVAL"]["num_batches"] add_noise = setup_params["EVAL"]["add_postprocessing_noise"] noise_factor = setup_params["EVAL"]["postprocessing_noise_factor"] max_pooling = setup_params["EVAL"]["max_pooling"] avg_pooling = setup_params["EVAL"]["avg_pooling"] constant_fields = 2 # future todo: have dataset config file? # otherwise these are of type string, e.g. '1e-5' lr_gen = float(lr_gen) lr_disc = float(lr_disc) kl_weight = float(kl_weight) noise_factor = float(noise_factor) content_loss_weight = float(content_loss_weight) if mode not in ["GAN", "VAEGAN", "det"]: raise ValueError("Mode type is restricted to 'GAN' 'VAEGAN' 'det'") if problem_type not in ["normal", "autocoarsen"]: raise ValueError("Problem type is restricted to 'normal' 'autocoarsen'") if ensemble_size is not None: if CLtype not in ["CRPS", "CRPS_phys", "ensmeanMSE", "ensmeanMSE_phys"]: raise ValueError( "Content loss type is restricted to 'CRPS', 'CRPS_phys', 'ensmeanMSE', 'ensmeanMSE_phys'" ) num_checkpoints = int(num_samples / (steps_per_checkpoint * batch_size)) checkpoint = 1 # create log folder and model save/load subfolder if they don't exist Path(log_folder).mkdir(parents=True, exist_ok=True) model_weights_root = os.path.join(log_folder, "models") Path(model_weights_root).mkdir(parents=True, exist_ok=True) # save setup parameters save_config = os.path.join(log_folder, "setup_params.yaml") with open(save_config, "w") as outfile: yaml.dump(setup_params, outfile, default_flow_style=False) if problem_type == "normal": autocoarsen = False input_channels = 5 * len(all_fcst_fields) elif problem_type == "autocoarsen": autocoarsen = True input_channels = 1 else: raise ValueError("no such problem type, try again!") if args.do_training: # initialize GAN # future todo: all these arguments should be wrapped inside # a nice dictionary, or similar, with sensible default values model = setupmodel.setup_model( mode=mode, arch=arch, downscaling_steps=df_dict["steps"], input_channels=input_channels, constant_fields=constant_fields, latent_variables=latent_variables, filters_gen=filters_gen, filters_disc=filters_disc, noise_channels=noise_channels, padding=padding, lr_disc=lr_disc, lr_gen=lr_gen, kl_weight=kl_weight, ensemble_size=ensemble_size, CLtype=CLtype, content_loss_weight=content_loss_weight, ) # print(train_years, val_years) batch_gen_train, data_gen_valid = setupdata.setup_data( train_years=train_years, val_years=val_years, autocoarsen=autocoarsen, weights=training_weights, batch_size=batch_size) if args.tune: print("Tuning cGAN") model.load(model.filenames_from_root(model_weights_root)) training_samples = 0 log_file = os.path.join(log_folder, "log_tune.txt") log_list = [] elif args.restart: # load weights and run status model.load(model.filenames_from_root(model_weights_root)) with open(os.path.join(log_folder, "run_status.json"), "r") as f: run_status = json.load(f) training_samples = run_status["training_samples"] checkpoint = int(training_samples / (steps_per_checkpoint * batch_size)) + 1 log_file = os.path.join(log_folder, "log.txt") log = pd.read_csv(log_file) log_list = [log] else: # initialize run status print("Training cGAN") training_samples = 0 log_file = os.path.join(log_folder, "log.txt") log_list = [] plot_fname = os.path.join(log_folder, "progress") if args.log_wandb: run = wandb.init(project='cGAN-gefs-tf216-run') while training_samples < num_samples: # main training loop gc.collect() print(f"Checkpoint {checkpoint}/{num_checkpoints}") # train for some number of batches loss_log = train.train_model( model=model, mode=mode, batch_gen_train=batch_gen_train, data_gen_valid=data_gen_valid, noise_channels=noise_channels, latent_variables=latent_variables, checkpoint=checkpoint, steps_per_checkpoint=steps_per_checkpoint, num_cases=val_size, plot_fn=plot_fname, log_wandb=args.log_wandb, ) training_samples += steps_per_checkpoint * batch_size checkpoint += 1 # save results model.save(model_weights_root) run_status = { "training_samples": training_samples, } if args.tune: with open(os.path.join(log_folder, "run_status_tune.json"), "w") as f: json.dump(run_status, f) else: with open(os.path.join(log_folder, "run_status_tune.json"), "w") as f: json.dump(run_status, f) data = {"training_samples": [training_samples]} for foo in loss_log: data[foo] = loss_log[foo] log_list.append(pd.DataFrame(data=data)) log = pd.concat(log_list) log.to_csv(log_file, index=False, float_format="%.6f") # Save model weights each checkpoint gen_weights_file = os.path.join( model_weights_root, f"gen_weights-{training_samples:07d}.h5" ) model.gen.save_weights(gen_weights_file) else: print("Training skipped...") if args.log_wandb: run.finish() if args.tune: eval_fname = os.path.join(log_folder, "eval_validation_tune.txt") else: eval_fname = os.path.join(log_folder, "eval_validation.txt") # model iterations to save full rank data to disk for during evaluations; # necessary for plot rank histograms. these are large files, so small # selection used to avoid storing gigabytes of data interval = steps_per_checkpoint * batch_size finalchkpt = num_samples // interval # last 4 checkpoints, or all checkpoints if < 4 ranks_to_save = ( [(finalchkpt - ii) * interval for ii in range(3, -1, -1)] if finalchkpt >= 4 else [ii * interval for ii in range(1, finalchkpt + 1)] ) if args.evalnum == "blitz": model_numbers = ( ranks_to_save.copy() ) # should not be modifying list in-place, but just in case! elif args.evalnum == "short": # last 1/3rd of checkpoints Neval = max(finalchkpt // 3, 1) model_numbers = [ (finalchkpt - ii) * interval for ii in range((Neval - 1), -1, -1) ] elif args.evalnum == "full": model_numbers = np.arange(0, num_samples + 1, interval)[1:].tolist() # evaluate model performance if args.evaluate: evaluate_multiple_checkpoints( mode=mode, arch=arch, val_years=val_years, log_fname=eval_fname, weights_dir=model_weights_root, autocoarsen=autocoarsen, add_noise=add_noise, noise_factor=noise_factor, model_numbers=model_numbers, ranks_to_save=ranks_to_save, num_images=num_images, filters_gen=filters_gen, filters_disc=filters_disc, input_channels=input_channels, constant_fields=constant_fields, latent_variables=latent_variables, noise_channels=noise_channels, padding=padding, ensemble_size=10, ) if args.plot_ranks: plot_histograms(log_folder, val_years, ranks=ranks_to_save, N_ranks=11) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |