Merge branch 'master' into amp_updates

This commit is contained in:
JanFschr 2021-12-06 20:50:29 +01:00 committed by GitHub
commit 592ebfa0e0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 656 additions and 168 deletions

View file

@ -131,6 +131,8 @@ if __name__ == "__main__":
'start_tensorboard' : arguments.start_tensorboard, 'start_tensorboard' : arguments.start_tensorboard,
'dump_ckpt' : arguments.dump_ckpt, 'dump_ckpt' : arguments.dump_ckpt,
'flask_preview' : arguments.flask_preview, 'flask_preview' : arguments.flask_preview,
'config_training_file' : arguments.config_training_file,
'auto_gen_config' : arguments.auto_gen_config
} }
from mainscripts import Trainer from mainscripts import Trainer
Trainer.main(**kwargs) Trainer.main(**kwargs)
@ -150,6 +152,8 @@ if __name__ == "__main__":
p.add_argument('--silent-start', action="store_true", dest="silent_start", default=False, help="Silent start. Automatically chooses Best GPU and last used model.") p.add_argument('--silent-start', action="store_true", dest="silent_start", default=False, help="Silent start. Automatically chooses Best GPU and last used model.")
p.add_argument('--tensorboard-logdir', action=fixPathAction, dest="tensorboard_dir", help="Directory of the tensorboard output files") p.add_argument('--tensorboard-logdir', action=fixPathAction, dest="tensorboard_dir", help="Directory of the tensorboard output files")
p.add_argument('--start-tensorboard', action="store_true", dest="start_tensorboard", default=False, help="Automatically start the tensorboard server preconfigured to the tensorboard-logdir") p.add_argument('--start-tensorboard', action="store_true", dest="start_tensorboard", default=False, help="Automatically start the tensorboard server preconfigured to the tensorboard-logdir")
p.add_argument('--config-training-file', action=fixPathAction, dest="config_training_file", help="Path to custom yaml configuration file")
p.add_argument('--auto-gen-config', action="store_true", dest="auto_gen_config", default=False, help="Saves a configuration file for each model used in the trainer. It'll have the same model name")
p.add_argument('--dump-ckpt', action="store_true", dest="dump_ckpt", default=False, help="Dump the model to ckpt format.") p.add_argument('--dump-ckpt', action="store_true", dest="dump_ckpt", default=False, help="Dump the model to ckpt format.")

View file

@ -71,6 +71,7 @@ def trainerThread (s2c, c2s, e,
debug=False, debug=False,
tensorboard_dir=None, tensorboard_dir=None,
start_tensorboard=False, start_tensorboard=False,
config_training_file=None,
dump_ckpt=False, dump_ckpt=False,
**kwargs): **kwargs):
while True: while True:
@ -101,6 +102,8 @@ def trainerThread (s2c, c2s, e,
force_gpu_idxs=force_gpu_idxs, force_gpu_idxs=force_gpu_idxs,
cpu_only=cpu_only, cpu_only=cpu_only,
silent_start=silent_start, silent_start=silent_start,
config_training_file=config_training_file,
auto_gen_config=kwargs.get("auto_gen_config", False),
debug=debug) debug=debug)
is_reached_goal = model.is_reached_iter_goal() is_reached_goal = model.is_reached_iter_goal()

View file

@ -1,5 +1,6 @@
import colorsys import colorsys
import inspect import inspect
from io import FileIO
import json import json
import multiprocessing import multiprocessing
import operator import operator
@ -10,6 +11,9 @@ import tempfile
import time import time
import datetime import datetime
from pathlib import Path from pathlib import Path
import yaml
from jsonschema import validate, ValidationError
import models
import cv2 import cv2
import numpy as np import numpy as np
@ -35,6 +39,8 @@ class ModelBase(object):
cpu_only=False, cpu_only=False,
debug=False, debug=False,
force_model_class_name=None, force_model_class_name=None,
config_training_file=None,
auto_gen_config=False,
silent_start=False, silent_start=False,
**kwargs): **kwargs):
self.is_training = is_training self.is_training = is_training
@ -44,6 +50,8 @@ class ModelBase(object):
self.training_data_dst_path = training_data_dst_path self.training_data_dst_path = training_data_dst_path
self.pretraining_data_path = pretraining_data_path self.pretraining_data_path = pretraining_data_path
self.pretrained_model_path = pretrained_model_path self.pretrained_model_path = pretrained_model_path
self.config_training_file = config_training_file
self.auto_gen_config = auto_gen_config
self.no_preview = no_preview self.no_preview = no_preview
self.debug = debug self.debug = debug
@ -141,12 +149,50 @@ class ModelBase(object):
self.choosed_gpu_indexes = None self.choosed_gpu_indexes = None
model_data = {} model_data = {}
# True if yaml conf file exists
self.config_file_exists = False
# True if user chooses to read options external or internal conf file
self.read_from_conf = False
config_error = False
#check if config_training_file mode is enabled
if config_training_file is not None:
self.config_file_path = Path(config_training_file)
# Creates folder if folder doesn't exist
if not self.config_file_path.exists():
os.makedirs(self.config_file_path, exist_ok=True)
# Ask if user wants to read options from external or internal conf file only if external conf file exists
# or auto_gen_config is true
if Path(self.get_strpath_configuration_path()).exists() or self.auto_gen_config:
self.read_from_conf = io.input_bool(
f'Do you want to read training options from {"external" if self.auto_gen_config else "internal"} file?',
True,
'Read options from configuration file instead of asking one by one each option'
)
# If user decides to read from external or internal conf file
if self.read_from_conf:
# Try to read dictionary from external of internal yaml file according
# to the value of auto_gen_config
self.options = self.read_from_config_file(auto_gen=self.auto_gen_config)
# If options dict is empty options will be loaded from dat file
if self.options is None:
io.log_info(f"Config file validation error, check your config")
config_error = True
elif not self.options.keys():
io.log_info(f"Configuration file doesn't exist. A standard configuration file will be created.")
else:
self.config_file_exists = True
else:
io.log_info(f"Configuration file doesn't exist. A standard configuration file will be created.")
self.model_data_path = Path( self.get_strpath_storage_for_file('data.dat') ) self.model_data_path = Path( self.get_strpath_storage_for_file('data.dat') )
if self.model_data_path.exists(): if self.model_data_path.exists():
io.log_info (f"Loading {self.model_name} model...") io.log_info (f"Loading {self.model_name} model...")
model_data = pickle.loads ( self.model_data_path.read_bytes() ) model_data = pickle.loads ( self.model_data_path.read_bytes() )
self.iter = model_data.get('iter',0) self.iter = model_data.get('iter',0)
if self.iter != 0: if self.iter != 0:
# read options from the .dat file only if the user chooses not to read options from the yaml file
if not self.config_file_exists:
self.options = model_data['options'] self.options = model_data['options']
self.loss_history = model_data.get('loss_history', []) self.loss_history = model_data.get('loss_history', [])
self.sample_for_preview = model_data.get('sample_for_preview', None) self.sample_for_preview = model_data.get('sample_for_preview', None)
@ -183,6 +229,11 @@ class ModelBase(object):
if self.is_first_run(): if self.is_first_run():
# save as default options only for first run model initialize # save as default options only for first run model initialize
self.default_options_path.write_bytes( pickle.dumps (self.options) ) self.default_options_path.write_bytes( pickle.dumps (self.options) )
# save config file
if self.config_training_file is not None and not self.config_file_exists and not config_error:
self.save_config_file(self.auto_gen_config)
self.session_name = self.options.get('session_name', "") self.session_name = self.options.get('session_name', "")
self.autobackup_hour = self.options.get('autobackup_hour', 0) self.autobackup_hour = self.options.get('autobackup_hour', 0)
self.maximum_n_backups = self.options.get('maximum_n_backups', 24) self.maximum_n_backups = self.options.get('maximum_n_backups', 24)
@ -382,6 +433,10 @@ class ModelBase(object):
#return predictor_func, predictor_input_shape, MergerConfig() for the model #return predictor_func, predictor_input_shape, MergerConfig() for the model
raise NotImplementedError raise NotImplementedError
#overridable
def get_config_schema_path(self):
raise NotImplementedError
def get_pretraining_data_path(self): def get_pretraining_data_path(self):
return self.pretraining_data_path return self.pretraining_data_path
@ -429,6 +484,60 @@ class ModelBase(object):
self.autobackup_start_time += self.autobackup_hour*3600 self.autobackup_start_time += self.autobackup_hour*3600
self.create_backup() self.create_backup()
def read_from_config_file(self, auto_gen=False):
"""
Read yaml config file and saves it into a dictionary
Args:
auto_gen (bool, optional): True if you want that a yaml file is readed from model folder. Defaults to False.
Returns:
[dict]: Returns the options dictionary if everything is alright otherwise an empty dictionary.
"""
fun = self.get_strpath_configuration_path if not auto_gen else self.get_model_conf_path
try:
with open(fun(), 'r') as file, open(self.get_config_schema_path(), 'r') as schema:
data = yaml.safe_load(file)
validate(data, yaml.safe_load(schema))
except FileNotFoundError:
return {}
except ValidationError as ve:
io.log_err(f"{ve}")
return None
for key, value in data.items():
if isinstance(value, bool):
continue
if isinstance(value, int):
data[key] = np.int32(value)
elif isinstance(value, float):
data[key] = np.float64(value)
return data
def save_config_file(self, auto_gen=False):
"""
Saves options dictionary in a yaml file.
Args:
auto_gen ([bool], optional): True if you want that a yaml file is generated inside model folder for each model. Defaults to None.
"""
saving_dict = {}
for key, value in self.options.items():
if isinstance(value, np.int32) or isinstance(value, np.float64):
saving_dict[key] = value.item()
else:
saving_dict[key] = value
fun = self.get_strpath_configuration_path if not auto_gen else self.get_model_conf_path
try:
with open(fun(), 'w') as file:
yaml.dump(saving_dict, file, sort_keys=False)
except OSError as exception:
io.log_info('Impossible to write YAML configuration file -> ', exception)
def create_backup(self): def create_backup(self):
io.log_info ("Creating backup...", end='\r') io.log_info ("Creating backup...", end='\r')
@ -561,9 +670,15 @@ class ModelBase(object):
def get_strpath_storage_for_file(self, filename): def get_strpath_storage_for_file(self, filename):
return str( self.saved_models_path / ( self.get_model_name() + '_' + filename) ) return str( self.saved_models_path / ( self.get_model_name() + '_' + filename) )
def get_strpath_configuration_path(self):
return str(self.config_file_path / 'configuration_file.yaml')
def get_summary_path(self): def get_summary_path(self):
return self.get_strpath_storage_for_file('summary.txt') return self.get_strpath_storage_for_file('summary.txt')
def get_model_conf_path(self):
return self.get_strpath_storage_for_file('configuration_file.yaml')
def get_summary_text(self): def get_summary_text(self):
visible_options = self.options.copy() visible_options = self.options.copy()
visible_options.update(self.options_show_override) visible_options.update(self.options_show_override)

View file

@ -11,12 +11,13 @@ from models import ModelBase
from samplelib import * from samplelib import *
from core.cv2ex import * from core.cv2ex import *
from pathlib import Path
class AMPModel(ModelBase): class AMPModel(ModelBase):
#override #override
def on_initialize_options(self): def on_initialize_options(self):
default_retraining_samples = self.options['retraining_samples'] = self.load_or_def_option('retraining_samples', False) default_retraining_samples = self.options['retraining_samples'] = self.load_or_def_option('retraining_samples', False)
# default_usefp16 = self.options['use_fp16'] = self.load_or_def_option('use_fp16', False)
default_resolution = self.options['resolution'] = self.load_or_def_option('resolution', 224) default_resolution = self.options['resolution'] = self.load_or_def_option('resolution', 224)
default_face_type = self.options['face_type'] = self.load_or_def_option('face_type', 'f') default_face_type = self.options['face_type'] = self.load_or_def_option('face_type', 'f')
default_models_opt_on_gpu = self.options['models_opt_on_gpu'] = self.load_or_def_option('models_opt_on_gpu', True) default_models_opt_on_gpu = self.options['models_opt_on_gpu'] = self.load_or_def_option('models_opt_on_gpu', True)
@ -54,10 +55,11 @@ class AMPModel(ModelBase):
default_ct_mode = self.options['ct_mode'] = self.load_or_def_option('ct_mode', 'none') default_ct_mode = self.options['ct_mode'] = self.load_or_def_option('ct_mode', 'none')
default_random_color = self.options['random_color'] = self.load_or_def_option('random_color', False) default_random_color = self.options['random_color'] = self.load_or_def_option('random_color', False)
default_clipgrad = self.options['clipgrad'] = self.load_or_def_option('clipgrad', False) default_clipgrad = self.options['clipgrad'] = self.load_or_def_option('clipgrad', False)
default_use_fp16 = self.options['use_fp16'] = self.load_or_def_option('use_fp16', False) default_usefp16 = self.options['use_fp16'] = self.load_or_def_option('use_fp16', False)
ask_override = self.ask_override() ask_override = False if self.read_from_conf else self.ask_override()
if self.is_first_run() or ask_override: if self.is_first_run() or ask_override:
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
self.ask_autobackup_hour() self.ask_autobackup_hour()
self.ask_session_name() self.ask_session_name()
self.ask_maximum_n_backups() self.ask_maximum_n_backups()
@ -67,16 +69,19 @@ class AMPModel(ModelBase):
self.ask_random_src_flip() self.ask_random_src_flip()
self.ask_random_dst_flip() self.ask_random_dst_flip()
self.ask_batch_size(8) self.ask_batch_size(8)
# self.options['use_fp16'] = io.input_bool ("Use fp16", default_usefp16, help_message='Increases training/inference speed, reduces model size. Model may crash. Enable it after 1-5k iters.') self.options['use_fp16'] = io.input_bool ("Use fp16", default_usefp16, help_message='Increases training/inference speed, reduces model size. Model may crash. Enable it after 1-5k iters.')
if self.is_first_run(): if self.is_first_run():
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
resolution = io.input_int("Resolution", default_resolution, add_info="64-640", help_message="More resolution requires more VRAM and time to train. Value will be adjusted to multiple of 32 .") resolution = io.input_int("Resolution", default_resolution, add_info="64-640", help_message="More resolution requires more VRAM and time to train. Value will be adjusted to multiple of 32 .")
resolution = np.clip ( (resolution // 32) * 32, 64, 640) resolution = np.clip ( (resolution // 32) * 32, 64, 640)
self.options['resolution'] = resolution self.options['resolution'] = resolution
self.options['face_type'] = io.input_str ("Face type", default_face_type, ['h','mf','f','wf','head', 'custom'], help_message="Half / mid face / full face / whole face / head / custom. Half face has better resolution, but covers less area of cheeks. Mid face is 30% wider than half face. 'Whole face' covers full area of face include forehead. 'head' covers full head, but requires XSeg for src and dst faceset.").lower() self.options['face_type'] = io.input_str ("Face type", default_face_type, ['h','mf','f','wf','head', 'custom'], help_message="Half / mid face / full face / whole face / head / custom. Half face has better resolution, but covers less area of cheeks. Mid face is 30% wider than half face. 'Whole face' covers full area of face include forehead. 'head' covers full head, but requires XSeg for src and dst faceset.").lower()
default_d_dims = self.options['d_dims'] = self.load_or_def_option('d_dims', 64) default_d_dims = self.options['d_dims'] = self.load_or_def_option('d_dims', 64)
default_d_mask_dims = default_d_dims // 3 default_d_mask_dims = default_d_dims // 3
@ -84,6 +89,7 @@ class AMPModel(ModelBase):
default_d_mask_dims = self.options['d_mask_dims'] = self.load_or_def_option('d_mask_dims', default_d_mask_dims) default_d_mask_dims = self.options['d_mask_dims'] = self.load_or_def_option('d_mask_dims', default_d_mask_dims)
if self.is_first_run(): if self.is_first_run():
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
self.options['ae_dims'] = np.clip ( io.input_int("AutoEncoder dimensions", default_ae_dims, add_info="32-1024", help_message="All face information will packed to AE dims. If amount of AE dims are not enough, then for example closed eyes will not be recognized. More dims are better, but require more VRAM. You can fine-tune model size to fit your GPU." ), 32, 1024 ) self.options['ae_dims'] = np.clip ( io.input_int("AutoEncoder dimensions", default_ae_dims, add_info="32-1024", help_message="All face information will packed to AE dims. If amount of AE dims are not enough, then for example closed eyes will not be recognized. More dims are better, but require more VRAM. You can fine-tune model size to fit your GPU." ), 32, 1024 )
self.options['inter_dims'] = np.clip ( io.input_int("Inter dimensions", default_inter_dims, add_info="32-2048", help_message="Should be equal or more than AutoEncoder dimensions. More dims are better, but require more VRAM. You can fine-tune model size to fit your GPU." ), 32, 2048 ) self.options['inter_dims'] = np.clip ( io.input_int("Inter dimensions", default_inter_dims, add_info="32-2048", help_message="Should be equal or more than AutoEncoder dimensions. More dims are better, but require more VRAM. You can fine-tune model size to fit your GPU." ), 32, 2048 )
@ -97,6 +103,7 @@ class AMPModel(ModelBase):
self.options['d_mask_dims'] = d_mask_dims + d_mask_dims % 2 self.options['d_mask_dims'] = d_mask_dims + d_mask_dims % 2
if self.is_first_run() or ask_override: if self.is_first_run() or ask_override:
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
morph_factor = np.clip ( io.input_number ("Morph factor.", default_morph_factor, add_info="0.1 .. 0.5", help_message="Typical fine value is 0.5"), 0.1, 0.5 ) morph_factor = np.clip ( io.input_number ("Morph factor.", default_morph_factor, add_info="0.1 .. 0.5", help_message="Typical fine value is 0.5"), 0.1, 0.5 )
self.options['morph_factor'] = morph_factor self.options['morph_factor'] = morph_factor
@ -122,6 +129,7 @@ class AMPModel(ModelBase):
default_gan_noise = self.options['gan_noise'] = self.load_or_def_option('gan_noise', 0.0) default_gan_noise = self.options['gan_noise'] = self.load_or_def_option('gan_noise', 0.0)
if self.is_first_run() or ask_override: if self.is_first_run() or ask_override:
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
self.options['models_opt_on_gpu'] = io.input_bool ("Place models and optimizer on GPU", default_models_opt_on_gpu, help_message="When you train on one GPU, by default model and optimizer weights are placed on GPU to accelerate the process. You can place they on CPU to free up extra VRAM, thus set bigger dimensions.") self.options['models_opt_on_gpu'] = io.input_bool ("Place models and optimizer on GPU", default_models_opt_on_gpu, help_message="When you train on one GPU, by default model and optimizer weights are placed on GPU to accelerate the process. You can place they on CPU to free up extra VRAM, thus set bigger dimensions.")
self.options['adabelief'] = io.input_bool ("Use AdaBelief optimizer?", default_adabelief, help_message="Use AdaBelief optimizer. It requires more VRAM, but the accuracy and the generalization of the model is higher.") self.options['adabelief'] = io.input_bool ("Use AdaBelief optimizer?", default_adabelief, help_message="Use AdaBelief optimizer. It requires more VRAM, but the accuracy and the generalization of the model is higher.")
@ -134,9 +142,9 @@ class AMPModel(ModelBase):
self.options['random_hsv_power'] = np.clip ( io.input_number ("Random hue/saturation/light intensity", default_random_hsv_power, add_info="0.0 .. 0.3", help_message="Random hue/saturation/light intensity applied to the src face set only at the input of the neural network. Stabilizes color perturbations during face swapping. Reduces the quality of the color transfer by selecting the closest one in the src faceset. Thus the src faceset must be diverse enough. Typical fine value is 0.05"), 0.0, 0.3 ) self.options['random_hsv_power'] = np.clip ( io.input_number ("Random hue/saturation/light intensity", default_random_hsv_power, add_info="0.0 .. 0.3", help_message="Random hue/saturation/light intensity applied to the src face set only at the input of the neural network. Stabilizes color perturbations during face swapping. Reduces the quality of the color transfer by selecting the closest one in the src faceset. Thus the src faceset must be diverse enough. Typical fine value is 0.05"), 0.0, 0.3 )
self.options['gan_power'] = np.clip ( io.input_number ("GAN power", default_gan_power, add_info="0.0 .. 5.0", help_message="Forces the neural network to learn small details of the face. Enable it only when the face is trained enough with random_warp(off), and don't disable. The higher the value, the higher the chances of artifacts. Typical fine value is 0.1"), 0.0, 5.0 ) self.options['gan_power'] = np.clip ( io.input_number ("GAN power", default_gan_power, add_info="0.0 .. 5.0", help_message="Forces the neural network to learn small details of the face. Enable it only when the face is trained enough with random_warp(off), and don't disable. The higher the value, the higher the chances of artifacts. Typical fine value is 0.1"), 0.0, 5.0 )
if self.options['gan_power'] != 0.0: if self.options['gan_power'] != 0.0:
self.options['gan_version'] = np.clip (io.input_int("GAN version", default_gan_version, add_info="2 or 3", help_message="Choose GAN version (v2: 7/16/2020, v3: 1/3/2021):"), 2, 3) self.options['gan_version'] = np.clip (io.input_int("GAN version", default_gan_version, add_info="2 or 3", help_message="Choose GAN version (v2: 7/16/2020, v3: 1/3/2021):"), 2, 3)
@ -153,6 +161,7 @@ class AMPModel(ModelBase):
self.options['background_power'] = np.clip ( io.input_number("Background power", default_background_power, add_info="0.0..1.0", help_message="Learn the area outside of the mask. Helps smooth out area near the mask boundaries. Can be used at any time"), 0.0, 1.0 ) self.options['background_power'] = np.clip ( io.input_number("Background power", default_background_power, add_info="0.0..1.0", help_message="Learn the area outside of the mask. Helps smooth out area near the mask boundaries. Can be used at any time"), 0.0, 1.0 )
self.options['ct_mode'] = io.input_str (f"Color transfer for src faceset", default_ct_mode, ['none','rct','lct','mkl','idt','sot', 'fs-aug'], help_message="Change color distribution of src samples close to dst samples. Try all modes to find the best.") self.options['ct_mode'] = io.input_str (f"Color transfer for src faceset", default_ct_mode, ['none','rct','lct','mkl','idt','sot', 'fs-aug'], help_message="Change color distribution of src samples close to dst samples. Try all modes to find the best.")
self.options['random_color'] = io.input_bool ("Random color", default_random_color, help_message="Samples are randomly rotated around the L axis in LAB colorspace, helps generalize training") self.options['random_color'] = io.input_bool ("Random color", default_random_color, help_message="Samples are randomly rotated around the L axis in LAB colorspace, helps generalize training")
@ -944,4 +953,10 @@ class AMPModel(ModelBase):
import merger import merger
return predictor_morph, (self.options['resolution'], self.options['resolution'], 3), merger.MergerConfigMasked(face_type=self.face_type, default_mode = 'overlay') return predictor_morph, (self.options['resolution'], self.options['resolution'], 3), merger.MergerConfigMasked(face_type=self.face_type, default_mode = 'overlay')
#override
def get_config_schema_path(self):
config_path = Path(__file__).parent.absolute() / Path("config_schema.json")
return config_path
Model = AMPModel Model = AMPModel

View file

@ -0,0 +1,256 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "#/definitions/dfl_config",
"definitions": {
"dfl_config": {
"type": "object",
"additionalProperties": false,
"properties": {
"use_fp16": {
"type": "boolean"
},
"morph_factor": {
"type": "number",
"minimum":0.0,
"maximum":0.5
},
"resolution": {
"type": "integer",
"minimum": 64,
"maximum": 640,
"multipleOf": 16
},
"face_type": {
"type": "string",
"enum": [
"h",
"mf",
"f",
"wf",
"head",
"custom"
]
},
"models_opt_on_gpu": {
"type": "boolean"
},
"ae_dims": {
"type": "integer",
"minimum": 32,
"maximum": 1024
},
"e_dims": {
"type": "integer",
"minimum": 16,
"maximum": 256,
"multipleOf": 2
},
"inter_dims": {
"type": "integer",
"minimum": 32,
"maximum": 2048,
"multipleOf": 2
},
"d_dims": {
"type": "integer",
"minimum": 16,
"maximum": 256,
"multipleOf": 2
},
"d_mask_dims": {
"type": "integer",
"minimum": 16,
"maximum": 256,
"multipleOf": 2
},
"masked_training": {
"type": "boolean"
},
"eyes_prio": {
"type": "boolean"
},
"mouth_prio": {
"type": "boolean"
},
"uniform_yaw": {
"type": "boolean"
},
"blur_out_mask": {
"type": "boolean"
},
"adabelief": {
"type": "boolean"
},
"lr_dropout": {
"type": "string",
"enum": [
"y",
"n",
"cpu"
]
},
"loss_function": {
"type": "string",
"enum": [
"SSIM",
"MS-SSIM",
"MS-SSIM+L1"
]
},
"random_warp": {
"type": "boolean"
},
"random_hsv_power": {
"type": "number",
"minimum": 0.0,
"maximum": 0.3
},
"random_downsample": {
"type": "boolean"
},
"random_noise": {
"type": "boolean"
},
"random_blur": {
"type": "boolean"
},
"random_jpeg": {
"type": "boolean"
},
"background_power": {
"type": "number",
"minimum": 0.0,
"maximum": 1.0
},
"ct_mode": {
"type": "string",
"enum": [
"none",
"rct",
"lct",
"mkl",
"idt",
"sot"
]
},
"random_color": {
"type": "boolean"
},
"clipgrad": {
"type": "boolean"
},
"pretrain": {
"type": "boolean"
},
"session_name": {
"type": "string"
},
"autobackup_hour": {
"type": "integer",
"minimum": 0,
"maximum": 24
},
"maximum_n_backups": {
"type": "integer"
},
"write_preview_history": {
"type": "boolean"
},
"target_iter": {
"type": "integer",
"minimum": 0
},
"retraining_samples": {
"type": "boolean"
},
"random_src_flip": {
"type": "boolean"
},
"random_dst_flip": {
"type": "boolean"
},
"batch_size": {
"type": "integer",
"minimum": 1
},
"gan_power": {
"type": "number",
"minimum": 0.0,
"maximum": 5.0
},
"gan_version": {
"type": "integer",
"minimum": 2,
"maximum": 3
},
"gan_patch_size": {
"type": "integer",
"minimum": 3,
"maximum": 640
},
"gan_dims": {
"type": "integer",
"minimum": 4,
"maximum": 512
},
"gan_smoothing": {
"type": "number",
"minimum": 0.0,
"maximum": 0.5
},
"gan_noise": {
"type": "number",
"minimum": 0.0,
"maximum": 0.5
}
},
"required": [
"adabelief",
"ae_dims",
"autobackup_hour",
"background_power",
"batch_size",
"blur_out_mask",
"clipgrad",
"ct_mode",
"d_dims",
"d_mask_dims",
"e_dims",
"inter_dims",
"morph_factor",
"eyes_prio",
"face_type",
"gan_dims",
"gan_noise",
"gan_patch_size",
"gan_power",
"gan_smoothing",
"gan_version",
"loss_function",
"lr_dropout",
"masked_training",
"maximum_n_backups",
"models_opt_on_gpu",
"mouth_prio",
"pretrain",
"random_blur",
"random_color",
"random_downsample",
"random_dst_flip",
"random_hsv_power",
"random_jpeg",
"random_noise",
"random_src_flip",
"random_warp",
"resolution",
"retraining_samples",
"session_name",
"target_iter",
"uniform_yaw",
"use_fp16",
"write_preview_history"
],
"title": "dfl_config"
}
}
}

View file

@ -10,7 +10,16 @@ from facelib import FaceType
from models import ModelBase from models import ModelBase
from samplelib import * from samplelib import *
from pathlib import Path
class QModel(ModelBase): class QModel(ModelBase):
#override
def on_initialize_options(self):
ask_override = False if self.read_from_conf else self.ask_override()
if self.is_first_run() or ask_override:
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
self.ask_batch_size()
#override #override
def on_initialize(self): def on_initialize(self):
device_config = nn.getCurrentDeviceConfig() device_config = nn.getCurrentDeviceConfig()
@ -80,7 +89,7 @@ class QModel(ModelBase):
if self.is_training: if self.is_training:
# Adjust batch size for multiple GPU # Adjust batch size for multiple GPU
gpu_count = max(1, len(devices) ) gpu_count = max(1, len(devices) )
bs_per_gpu = max(1, 4 // gpu_count) bs_per_gpu = max(1, self.get_batch_size() // gpu_count)
self.set_batch_size( gpu_count*bs_per_gpu) self.set_batch_size( gpu_count*bs_per_gpu)
# Compute losses per GPU # Compute losses per GPU
@ -317,5 +326,9 @@ class QModel(ModelBase):
return self.predictor_func, (self.resolution, self.resolution, 3), merger.MergerConfigMasked(face_type=self.face_type, return self.predictor_func, (self.resolution, self.resolution, 3), merger.MergerConfigMasked(face_type=self.face_type,
default_mode = 'overlay', default_mode = 'overlay',
) )
#override
def get_config_schema_path(self):
config_path = Path(__file__).parent.absolute() / Path("config_schema.json")
return config_path
Model = QModel Model = QModel

View file

@ -0,0 +1,20 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "#/definitions/dfl_config",
"definitions": {
"dfl_config": {
"type": "object",
"additionalProperties": false,
"properties": {
"batch_size": {
"type": "integer",
"minimum": 1
}
},
"required": [
"batch_size",
],
"title": "dfl_config"
}
}
}

View file

@ -10,6 +10,8 @@ from facelib import FaceType
from models import ModelBase from models import ModelBase
from samplelib import * from samplelib import *
from pathlib import Path
class SAEHDModel(ModelBase): class SAEHDModel(ModelBase):
#override #override
@ -28,7 +30,7 @@ class SAEHDModel(ModelBase):
min_res = 64 min_res = 64
max_res = 640 max_res = 640
#default_usefp16 = self.options['use_fp16'] = self.load_or_def_option('use_fp16', False) default_usefp16 = self.options['use_fp16'] = self.load_or_def_option('use_fp16', False)
default_resolution = self.options['resolution'] = self.load_or_def_option('resolution', 128) default_resolution = self.options['resolution'] = self.load_or_def_option('resolution', 128)
default_face_type = self.options['face_type'] = self.load_or_def_option('face_type', 'f') default_face_type = self.options['face_type'] = self.load_or_def_option('face_type', 'f')
default_models_opt_on_gpu = self.options['models_opt_on_gpu'] = self.load_or_def_option('models_opt_on_gpu', True) default_models_opt_on_gpu = self.options['models_opt_on_gpu'] = self.load_or_def_option('models_opt_on_gpu', True)
@ -68,10 +70,11 @@ class SAEHDModel(ModelBase):
default_random_color = self.options['random_color'] = self.load_or_def_option('random_color', False) default_random_color = self.options['random_color'] = self.load_or_def_option('random_color', False)
default_clipgrad = self.options['clipgrad'] = self.load_or_def_option('clipgrad', False) default_clipgrad = self.options['clipgrad'] = self.load_or_def_option('clipgrad', False)
default_pretrain = self.options['pretrain'] = self.load_or_def_option('pretrain', False) default_pretrain = self.options['pretrain'] = self.load_or_def_option('pretrain', False)
default_use_fp16 = self.options['use_fp16'] = self.load_or_def_option('use_fp16', False) #default_use_fp16 = self.options['use_fp16'] = self.load_or_def_option('use_fp16', False)
ask_override = self.ask_override() ask_override = False if self.read_from_conf else self.ask_override()
if self.is_first_run() or ask_override: if self.is_first_run() or ask_override:
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
self.ask_session_name() self.ask_session_name()
self.ask_autobackup_hour() self.ask_autobackup_hour()
self.ask_maximum_n_backups() self.ask_maximum_n_backups()
@ -81,9 +84,10 @@ class SAEHDModel(ModelBase):
self.ask_random_src_flip() self.ask_random_src_flip()
self.ask_random_dst_flip() self.ask_random_dst_flip()
self.ask_batch_size(suggest_batch_size) self.ask_batch_size(suggest_batch_size)
#self.options['use_fp16'] = io.input_bool ("Use fp16", default_usefp16, help_message='Increases training/inference speed, reduces model size. Model may crash. Enable it after 1-5k iters.') self.options['use_fp16'] = io.input_bool ("Use fp16", default_usefp16, help_message='Increases training/inference speed, reduces model size. Model may crash. Enable it after 1-5k iters.')
if self.is_first_run(): if self.is_first_run():
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
resolution = io.input_int("Resolution", default_resolution, add_info="64-640", help_message="More resolution requires more VRAM and time to train. Value will be adjusted to multiple of 16 and 32 for -d archi.") resolution = io.input_int("Resolution", default_resolution, add_info="64-640", help_message="More resolution requires more VRAM and time to train. Value will be adjusted to multiple of 16 and 32 for -d archi.")
resolution = np.clip ( (resolution // 16) * 16, min_res, max_res) resolution = np.clip ( (resolution // 16) * 16, min_res, max_res)
self.options['resolution'] = resolution self.options['resolution'] = resolution
@ -91,13 +95,13 @@ class SAEHDModel(ModelBase):
while True: while True:
archi = io.input_str ("AE architecture", default_archi, help_message=\ archi = io.input_str ("AE architecture", default_archi, help_message=\
""" """
'df' keeps more identity-preserved face. 'df' keeps more identity-preserved face.
'liae' can fix overly different face shapes. 'liae' can fix overly different face shapes.
'-u' increased likeness of the face. '-u' increased likeness of the face.
'-d' (experimental) doubling the resolution using the same computation cost. '-d' (experimental) doubling the resolution using the same computation cost.
Examples: df, liae, df-d, df-ud, liae-ud, ... Examples: df, liae, df-d, df-ud, liae-ud, ...
""").lower() """).lower()
archi_split = archi.split('-') archi_split = archi.split('-')
@ -130,6 +134,7 @@ Examples: df, liae, df-d, df-ud, liae-ud, ...
default_d_mask_dims = self.options['d_mask_dims'] = self.load_or_def_option('d_mask_dims', default_d_mask_dims) default_d_mask_dims = self.options['d_mask_dims'] = self.load_or_def_option('d_mask_dims', default_d_mask_dims)
if self.is_first_run(): if self.is_first_run():
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
self.options['ae_dims'] = np.clip ( io.input_int("AutoEncoder dimensions", default_ae_dims, add_info="32-1024", help_message="All face information will packed to AE dims. If amount of AE dims are not enough, then for example closed eyes will not be recognized. More dims are better, but require more VRAM. You can fine-tune model size to fit your GPU." ), 32, 1024 ) self.options['ae_dims'] = np.clip ( io.input_int("AutoEncoder dimensions", default_ae_dims, add_info="32-1024", help_message="All face information will packed to AE dims. If amount of AE dims are not enough, then for example closed eyes will not be recognized. More dims are better, but require more VRAM. You can fine-tune model size to fit your GPU." ), 32, 1024 )
e_dims = np.clip ( io.input_int("Encoder dimensions", default_e_dims, add_info="16-256", help_message="More dims help to recognize more facial features and achieve sharper result, but require more VRAM. You can fine-tune model size to fit your GPU." ), 16, 256 ) e_dims = np.clip ( io.input_int("Encoder dimensions", default_e_dims, add_info="16-256", help_message="More dims help to recognize more facial features and achieve sharper result, but require more VRAM. You can fine-tune model size to fit your GPU." ), 16, 256 )
@ -142,6 +147,7 @@ Examples: df, liae, df-d, df-ud, liae-ud, ...
self.options['d_mask_dims'] = d_mask_dims + d_mask_dims % 2 self.options['d_mask_dims'] = d_mask_dims + d_mask_dims % 2
if self.is_first_run() or ask_override: if self.is_first_run() or ask_override:
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
if self.options['face_type'] == 'wf' or self.options['face_type'] == 'head' or self.options['face_type'] == 'custom': if self.options['face_type'] == 'wf' or self.options['face_type'] == 'head' or self.options['face_type'] == 'custom':
self.options['masked_training'] = io.input_bool ("Masked training", default_masked_training, help_message="This option is available only for 'whole_face' or 'head' type. Masked training clips training area to full_face mask or XSeg mask, thus network will train the faces properly.") self.options['masked_training'] = io.input_bool ("Masked training", default_masked_training, help_message="This option is available only for 'whole_face' or 'head' type. Masked training clips training area to full_face mask or XSeg mask, thus network will train the faces properly.")
@ -159,6 +165,7 @@ Examples: df, liae, df-d, df-ud, liae-ud, ...
default_gan_noise = self.options['gan_noise'] = self.load_or_def_option('gan_noise', 0.0) default_gan_noise = self.options['gan_noise'] = self.load_or_def_option('gan_noise', 0.0)
if self.is_first_run() or ask_override: if self.is_first_run() or ask_override:
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
self.options['models_opt_on_gpu'] = io.input_bool ("Place models and optimizer on GPU", default_models_opt_on_gpu, help_message="When you train on one GPU, by default model and optimizer weights are placed on GPU to accelerate the process. You can place they on CPU to free up extra VRAM, thus set bigger dimensions.") self.options['models_opt_on_gpu'] = io.input_bool ("Place models and optimizer on GPU", default_models_opt_on_gpu, help_message="When you train on one GPU, by default model and optimizer weights are placed on GPU to accelerate the process. You can place they on CPU to free up extra VRAM, thus set bigger dimensions.")
self.options['adabelief'] = io.input_bool ("Use AdaBelief optimizer?", default_adabelief, help_message="Use AdaBelief optimizer. It requires more VRAM, but the accuracy and the generalization of the model is higher.") self.options['adabelief'] = io.input_bool ("Use AdaBelief optimizer?", default_adabelief, help_message="Use AdaBelief optimizer. It requires more VRAM, but the accuracy and the generalization of the model is higher.")
@ -806,7 +813,7 @@ Examples: df, liae, df-d, df-ud, liae-ud, ...
'random_noise': self.options['random_noise'], 'random_noise': self.options['random_noise'],
'random_blur': self.options['random_blur'], 'random_blur': self.options['random_blur'],
'random_jpeg': self.options['random_jpeg'], 'random_jpeg': self.options['random_jpeg'],
'transform':True, 'channel_type' : channel_type, 'ct_mode': ct_mode, 'transform':True, 'channel_type' : channel_type, 'ct_mode': ct_mode, 'random_hsv_shift_amount' : random_hsv_power,
'face_type':self.face_type, 'data_format':nn.data_format, 'resolution': resolution}, 'face_type':self.face_type, 'data_format':nn.data_format, 'resolution': resolution},
{'sample_type': SampleProcessor.SampleType.FACE_IMAGE,'warp':False , 'transform':True, 'channel_type' : channel_type, 'ct_mode': ct_mode, 'face_type':self.face_type, 'data_format':nn.data_format, 'resolution': resolution}, {'sample_type': SampleProcessor.SampleType.FACE_IMAGE,'warp':False , 'transform':True, 'channel_type' : channel_type, 'ct_mode': ct_mode, 'face_type':self.face_type, 'data_format':nn.data_format, 'resolution': resolution},
{'sample_type': SampleProcessor.SampleType.FACE_MASK, 'warp':False , 'transform':True, 'channel_type' : SampleProcessor.ChannelType.G, 'face_mask_type' : SampleProcessor.FaceMaskType.FULL_FACE, 'face_type':self.face_type, 'data_format':nn.data_format, 'resolution': resolution}, {'sample_type': SampleProcessor.SampleType.FACE_MASK, 'warp':False , 'transform':True, 'channel_type' : SampleProcessor.ChannelType.G, 'face_mask_type' : SampleProcessor.FaceMaskType.FULL_FACE, 'face_type':self.face_type, 'data_format':nn.data_format, 'resolution': resolution},
@ -1053,4 +1060,9 @@ Examples: df, liae, df-d, df-ud, liae-ud, ...
import merger import merger
return self.predictor_func, (self.options['resolution'], self.options['resolution'], 3), merger.MergerConfigMasked(face_type=self.face_type, default_mode = 'overlay') return self.predictor_func, (self.options['resolution'], self.options['resolution'], 3), merger.MergerConfigMasked(face_type=self.face_type, default_mode = 'overlay')
#override
def get_config_schema_path(self):
config_path = Path(__file__).parent.absolute() / Path("config_schema.json")
return config_path
Model = SAEHDModel Model = SAEHDModel

View file

@ -11,6 +11,8 @@ from facelib import FaceType, XSegNet
from models import ModelBase from models import ModelBase
from samplelib import * from samplelib import *
from pathlib import Path
class XSegModel(ModelBase): class XSegModel(ModelBase):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -18,7 +20,7 @@ class XSegModel(ModelBase):
#override #override
def on_initialize_options(self): def on_initialize_options(self):
ask_override = self.ask_override() ask_override = False if self.read_from_conf else self.ask_override()
if not self.is_first_run() and ask_override: if not self.is_first_run() and ask_override:
if io.input_bool(f"Restart training?", False, help_message="Reset model weights and start training from scratch."): if io.input_bool(f"Restart training?", False, help_message="Reset model weights and start training from scratch."):
@ -28,9 +30,11 @@ class XSegModel(ModelBase):
default_pretrain = self.options['pretrain'] = self.load_or_def_option('pretrain', False) default_pretrain = self.options['pretrain'] = self.load_or_def_option('pretrain', False)
if self.is_first_run(): if self.is_first_run():
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
self.options['face_type'] = io.input_str ("Face type", default_face_type, ['h','mf','f','wf','head'], help_message="Half / mid face / full face / whole face / head. Choose the same as your deepfake model.").lower() self.options['face_type'] = io.input_str ("Face type", default_face_type, ['h','mf','f','wf','head'], help_message="Half / mid face / full face / whole face / head. Choose the same as your deepfake model.").lower()
if self.is_first_run() or ask_override: if self.is_first_run() or ask_override:
if (self.read_from_conf and not self.config_file_exists) or not self.read_from_conf:
self.ask_batch_size(4, range=[2,16]) self.ask_batch_size(4, range=[2,16])
self.options['pretrain'] = io.input_bool ("Enable pretraining mode", default_pretrain) self.options['pretrain'] = io.input_bool ("Enable pretraining mode", default_pretrain)
@ -51,14 +55,12 @@ class XSegModel(ModelBase):
self.resolution = resolution = 256 self.resolution = resolution = 256
self.face_type = {'h' : FaceType.HALF, self.face_type = {'h' : FaceType.HALF,
'mf' : FaceType.MID_FULL, 'mf' : FaceType.MID_FULL,
'f' : FaceType.FULL, 'f' : FaceType.FULL,
'wf' : FaceType.WHOLE_FACE, 'wf' : FaceType.WHOLE_FACE,
'head' : FaceType.HEAD}[ self.options['face_type'] ] 'head' : FaceType.HEAD}[ self.options['face_type'] ]
place_model_on_cpu = len(devices) == 0 place_model_on_cpu = len(devices) == 0
models_opt_device = '/CPU:0' if place_model_on_cpu else nn.tf_default_device_name models_opt_device = '/CPU:0' if place_model_on_cpu else nn.tf_default_device_name
@ -280,4 +282,9 @@ class XSegModel(ModelBase):
opset=13, opset=13,
output_path=output_path) output_path=output_path)
#override
def get_config_schema_path(self):
config_path = Path(__file__).parent.absolute() / Path("config_schema.json")
return config_path
Model = XSegModel Model = XSegModel

View file

@ -0,0 +1,39 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "#/definitions/dfl_config",
"definitions": {
"dfl_config": {
"type": "object",
"additionalProperties": false,
"properties": {
"use_fp16": {
"type": "boolean"
},
"face_type": {
"type": "string",
"enum": [
"h",
"mf",
"f",
"wf",
"head",
"custom"
]
},
"pretrain": {
"type": "boolean"
},
"batch_size": {
"type": "integer",
"minimum": 1
}
},
"required": [
"batch_size",
"face_type",
"pretrain",
],
"title": "dfl_config"
}
}
}

View file

@ -3,3 +3,5 @@ from .ModelBase import ModelBase
def import_model(model_class_name): def import_model(model_class_name):
module = __import__('Model_'+model_class_name, globals(), locals(), [], 1) module = __import__('Model_'+model_class_name, globals(), locals(), [], 1)
return getattr(module, 'Model') return getattr(module, 'Model')

View file

@ -11,3 +11,4 @@ tensorflow-gpu==2.4.0
tf2onnx==1.9.3 tf2onnx==1.9.3
tensorboardX tensorboardX
crc32c crc32c
jsonschema

View file

@ -14,3 +14,4 @@ Flask==1.1.1
flask-socketio==4.2.1 flask-socketio==4.2.1
tensorboardX tensorboardX
crc32c crc32c
jsonschema