{"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/lib\/options.py","language":"python","identifier":"Options.save","parameters":"(self, path_yaml)","argument_list":"","return_statement":"","docstring":"Write options dictionary to a yaml file","docstring_summary":"Write options dictionary to a yaml file","docstring_tokens":["Write","options","dictionary","to","a","yaml","file"],"function":"def save(self, path_yaml):\n \"\"\" Write options dictionary to a yaml file\n \"\"\"\n Options.save_yaml_opts(self.options, path_yaml)","function_tokens":["def","save","(","self",",","path_yaml",")",":","Options",".","save_yaml_opts","(","self",".","options",",","path_yaml",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/lib\/options.py#L278-L281"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/lib\/options.py","language":"python","identifier":"Options.load_yaml_opts","parameters":"(source)","argument_list":"","return_statement":"return result","docstring":"Load options dictionary from a yaml file","docstring_summary":"Load options dictionary from a yaml file","docstring_tokens":["Load","options","dictionary","from","a","yaml","file"],"function":"def load_yaml_opts(source):\n \"\"\" Load options dictionary from a yaml file\n \"\"\"\n result = {}\n if isinstance(source, str):\n with open(source, 'r') as yaml_file:\n options_dict = yaml.safe_load(yaml_file)\n elif isinstance(source, dict):\n options_dict = source\n else:\n raise TypeError('Unsupported source type: {}'.format(type(source)))\n includes = options_dict.get('__include__', False)\n if includes:\n if type(includes) != list:\n includes = [includes]\n for include in includes:\n filename = '{}\/{}'.format(os.path.dirname(source), include)\n if os.path.isfile(filename):\n parent = Options.load_yaml_opts(filename)\n else:\n parent = Options.load_yaml_opts(include)\n merge_dictionaries(result, parent)\n merge_dictionaries(result, options_dict) # to be sure the main options overwrite the parent options\n result.pop('__include__', None)\n result = OptionsDict(result)\n return result","function_tokens":["def","load_yaml_opts","(","source",")",":","result","=","{","}","if","isinstance","(","source",",","str",")",":","with","open","(","source",",","'r'",")","as","yaml_file",":","options_dict","=","yaml",".","safe_load","(","yaml_file",")","elif","isinstance","(","source",",","dict",")",":","options_dict","=","source","else",":","raise","TypeError","(","'Unsupported source type: {}'",".","format","(","type","(","source",")",")",")","includes","=","options_dict",".","get","(","'__include__'",",","False",")","if","includes",":","if","type","(","includes",")","!=","list",":","includes","=","[","includes","]","for","include","in","includes",":","filename","=","'{}\/{}'",".","format","(","os",".","path",".","dirname","(","source",")",",","include",")","if","os",".","path",".","isfile","(","filename",")",":","parent","=","Options",".","load_yaml_opts","(","filename",")","else",":","parent","=","Options",".","load_yaml_opts","(","include",")","merge_dictionaries","(","result",",","parent",")","merge_dictionaries","(","result",",","options_dict",")","# to be sure the main options overwrite the parent options","result",".","pop","(","'__include__'",",","None",")","result","=","OptionsDict","(","result",")","return","result"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/lib\/options.py#L291-L316"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/lib\/utils.py","language":"python","identifier":"env_info","parameters":"()","argument_list":"","return_statement":"return info","docstring":"Collects information about the environment, for reproducibility","docstring_summary":"Collects information about the environment, for reproducibility","docstring_tokens":["Collects","information","about","the","environment","for","reproducibility"],"function":"def env_info():\n \"\"\" Collects information about the environment, for reproducibility \"\"\"\n info = {}\n info['python_version'] = sys.version\n info['command'] = subprocess.list2cmdline(sys.argv)\n with open(os.devnull, 'w') as devnull:\n info['pip_modules'] = subprocess.check_output(['pip', 'freeze'], stderr=devnull)\n try:\n git_branch_cmd = ['git', 'rev-parse', '--abbrev-ref', 'HEAD']\n info['git_branch'] = subprocess.check_output(git_branch_cmd, stderr=devnull).strip().decode('UTF-8')\n git_local_commit_cmd = ['git', 'rev-parse', 'HEAD']\n git_status_cmd = ['git', 'status']\n git_origin_commit_cmd = ['git', 'rev-parse', 'origin\/{}'.format(info['git_branch'])]\n git_diff_origin_commit_cmd = ['git', 'diff', 'origin\/{}'.format(info['git_branch'])]\n info['git_origin_commit'] = subprocess.check_output(git_origin_commit_cmd, stderr=devnull)\n git_log_since_origin_cmd = ['git', 'log', '--pretty=oneline', '{}..HEAD'.format(info['git_origin_commit'])]\n info['git_local_commit'] = subprocess.check_output(git_local_commit_cmd, stderr=devnull)\n info['git_status'] = subprocess.check_output(git_status_cmd, stderr=devnull)\n info['git_diff_origin_commit'] = subprocess.check_output(git_diff_origin_commit_cmd, stderr=devnull)\n info['git_log_since_origin'] = subprocess.check_output(git_log_since_origin_cmd, stderr=devnull)\n except subprocess.CalledProcessError:\n pass\n info['creation_time'] = time.strftime('%y-%m-%d-%H-%M-%S')\n info['sysname'] = os.uname()[0]\n info['nodename'] = os.uname()[1]\n info['release'] = os.uname()[2]\n info['version'] = os.uname()[3]\n info['architecture'] = os.uname()[4]\n info['user'] = os.environ['USER']\n info['path'] = os.environ['PWD']\n info['conda_environment'] = os.environ.get('CONDA_DEFAULT_ENV', '')\n info['environment_vars'] = dict(os.environ)\n info = {k: info[k].decode(\"UTF-8\") if type(info[k]) == bytes else info[k] for k in info}\n return info","function_tokens":["def","env_info","(",")",":","info","=","{","}","info","[","'python_version'","]","=","sys",".","version","info","[","'command'","]","=","subprocess",".","list2cmdline","(","sys",".","argv",")","with","open","(","os",".","devnull",",","'w'",")","as","devnull",":","info","[","'pip_modules'","]","=","subprocess",".","check_output","(","[","'pip'",",","'freeze'","]",",","stderr","=","devnull",")","try",":","git_branch_cmd","=","[","'git'",",","'rev-parse'",",","'--abbrev-ref'",",","'HEAD'","]","info","[","'git_branch'","]","=","subprocess",".","check_output","(","git_branch_cmd",",","stderr","=","devnull",")",".","strip","(",")",".","decode","(","'UTF-8'",")","git_local_commit_cmd","=","[","'git'",",","'rev-parse'",",","'HEAD'","]","git_status_cmd","=","[","'git'",",","'status'","]","git_origin_commit_cmd","=","[","'git'",",","'rev-parse'",",","'origin\/{}'",".","format","(","info","[","'git_branch'","]",")","]","git_diff_origin_commit_cmd","=","[","'git'",",","'diff'",",","'origin\/{}'",".","format","(","info","[","'git_branch'","]",")","]","info","[","'git_origin_commit'","]","=","subprocess",".","check_output","(","git_origin_commit_cmd",",","stderr","=","devnull",")","git_log_since_origin_cmd","=","[","'git'",",","'log'",",","'--pretty=oneline'",",","'{}..HEAD'",".","format","(","info","[","'git_origin_commit'","]",")","]","info","[","'git_local_commit'","]","=","subprocess",".","check_output","(","git_local_commit_cmd",",","stderr","=","devnull",")","info","[","'git_status'","]","=","subprocess",".","check_output","(","git_status_cmd",",","stderr","=","devnull",")","info","[","'git_diff_origin_commit'","]","=","subprocess",".","check_output","(","git_diff_origin_commit_cmd",",","stderr","=","devnull",")","info","[","'git_log_since_origin'","]","=","subprocess",".","check_output","(","git_log_since_origin_cmd",",","stderr","=","devnull",")","except","subprocess",".","CalledProcessError",":","pass","info","[","'creation_time'","]","=","time",".","strftime","(","'%y-%m-%d-%H-%M-%S'",")","info","[","'sysname'","]","=","os",".","uname","(",")","[","0","]","info","[","'nodename'","]","=","os",".","uname","(",")","[","1","]","info","[","'release'","]","=","os",".","uname","(",")","[","2","]","info","[","'version'","]","=","os",".","uname","(",")","[","3","]","info","[","'architecture'","]","=","os",".","uname","(",")","[","4","]","info","[","'user'","]","=","os",".","environ","[","'USER'","]","info","[","'path'","]","=","os",".","environ","[","'PWD'","]","info","[","'conda_environment'","]","=","os",".","environ",".","get","(","'CONDA_DEFAULT_ENV'",",","''",")","info","[","'environment_vars'","]","=","dict","(","os",".","environ",")","info","=","{","k",":","info","[","k","]",".","decode","(","\"UTF-8\"",")","if","type","(","info","[","k","]",")","==","bytes","else","info","[","k","]","for","k","in","info","}","return","info"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/lib\/utils.py#L47-L80"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"Model.eval","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Activate evaluation mode","docstring_summary":"Activate evaluation mode","docstring_tokens":["Activate","evaluation","mode"],"function":"def eval(self):\n \"\"\" Activate evaluation mode\n \"\"\"\n super(Model, self).train(mode=False)\n self.mode = 'eval'","function_tokens":["def","eval","(","self",")",":","super","(","Model",",","self",")",".","train","(","mode","=","False",")","self",".","mode","=","'eval'"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L28-L32"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"Model.train","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Activate training mode","docstring_summary":"Activate training mode","docstring_tokens":["Activate","training","mode"],"function":"def train(self):\n \"\"\" Activate training mode\n \"\"\"\n super(Model, self).train(mode=True)\n self.mode = 'train'","function_tokens":["def","train","(","self",")",":","super","(","Model",",","self",")",".","train","(","mode","=","True",")","self",".","mode","=","'train'"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L34-L38"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"Model.cuda","parameters":"(self, device_id=None)","argument_list":"","return_statement":"return self._apply(lambda t: t.cuda(device_id))","docstring":"Moves all model parameters and buffers to the GPU.\n\n Args:\n device_id (int, optional): if specified, all parameters will be\n copied to that device","docstring_summary":"Moves all model parameters and buffers to the GPU.","docstring_tokens":["Moves","all","model","parameters","and","buffers","to","the","GPU","."],"function":"def cuda(self, device_id=None):\n \"\"\" Moves all model parameters and buffers to the GPU.\n\n Args:\n device_id (int, optional): if specified, all parameters will be\n copied to that device\n \"\"\"\n self.is_cuda = True\n return self._apply(lambda t: t.cuda(device_id))","function_tokens":["def","cuda","(","self",",","device_id","=","None",")",":","self",".","is_cuda","=","True","return","self",".","_apply","(","lambda","t",":","t",".","cuda","(","device_id",")",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L40-L48"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"Model.cpu","parameters":"(self)","argument_list":"","return_statement":"return self._apply(lambda t: t.cpu())","docstring":"Moves all model parameters and buffers to the CPU.","docstring_summary":"Moves all model parameters and buffers to the CPU.","docstring_tokens":["Moves","all","model","parameters","and","buffers","to","the","CPU","."],"function":"def cpu(self):\n \"\"\" Moves all model parameters and buffers to the CPU.\n \"\"\"\n self.is_cuda = False\n return self._apply(lambda t: t.cpu())","function_tokens":["def","cpu","(","self",")",":","self",".","is_cuda","=","False","return","self",".","_apply","(","lambda","t",":","t",".","cpu","(",")",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L50-L54"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"Model.prepare_batch","parameters":"(self, batch)","argument_list":"","return_statement":"return batch","docstring":"Prepare a batch with two functions: cuda_tf and detach_tf (only in eval mode)","docstring_summary":"Prepare a batch with two functions: cuda_tf and detach_tf (only in eval mode)","docstring_tokens":["Prepare","a","batch","with","two","functions",":","cuda_tf","and","detach_tf","(","only","in","eval","mode",")"],"function":"def prepare_batch(self, batch):\n \"\"\" Prepare a batch with two functions: cuda_tf and detach_tf (only in eval mode)\n \"\"\"\n if self.is_cuda:\n batch = self.cuda_tf()(batch)\n if self.mode == 'eval':\n batch = self.detach_tf()(batch)\n return batch","function_tokens":["def","prepare_batch","(","self",",","batch",")",":","if","self",".","is_cuda",":","batch","=","self",".","cuda_tf","(",")","(","batch",")","if","self",".","mode","==","'eval'",":","batch","=","self",".","detach_tf","(",")","(","batch",")","return","batch"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L56-L63"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"Model.forward","parameters":"(self, batch)","argument_list":"","return_statement":"return out","docstring":"Prepare the batch and feed it to the network, criterion and metric.\n\n Returns:\n out (dict): a dictionary of outputs","docstring_summary":"Prepare the batch and feed it to the network, criterion and metric.","docstring_tokens":["Prepare","the","batch","and","feed","it","to","the","network","criterion","and","metric","."],"function":"def forward(self, batch):\n \"\"\" Prepare the batch and feed it to the network, criterion and metric.\n\n Returns:\n out (dict): a dictionary of outputs\n \"\"\"\n batch = self.prepare_batch(batch)\n net_out = self.network(batch)\n\n cri_out = {}\n if self.mode in self.criterions:\n cri_tmp = self.criterions[self.mode](net_out, batch)\n if cri_tmp is not None:\n cri_out = cri_tmp\n\n met_out = {}\n if self.mode in self.metrics:\n met_tmp = self.metrics[self.mode](cri_out, net_out, batch)\n if met_tmp is not None:\n met_out = met_tmp\n\n out = {}\n if type(net_out) is dict:\n for key, value in net_out.items():\n out[key] = value\n if type(cri_out) is dict:\n for key, value in cri_out.items():\n out[key] = value\n if type(met_out) is dict:\n for key, value in met_out.items():\n out[key] = value\n return out","function_tokens":["def","forward","(","self",",","batch",")",":","batch","=","self",".","prepare_batch","(","batch",")","net_out","=","self",".","network","(","batch",")","cri_out","=","{","}","if","self",".","mode","in","self",".","criterions",":","cri_tmp","=","self",".","criterions","[","self",".","mode","]","(","net_out",",","batch",")","if","cri_tmp","is","not","None",":","cri_out","=","cri_tmp","met_out","=","{","}","if","self",".","mode","in","self",".","metrics",":","met_tmp","=","self",".","metrics","[","self",".","mode","]","(","cri_out",",","net_out",",","batch",")","if","met_tmp","is","not","None",":","met_out","=","met_tmp","out","=","{","}","if","type","(","net_out",")","is","dict",":","for","key",",","value","in","net_out",".","items","(",")",":","out","[","key","]","=","value","if","type","(","cri_out",")","is","dict",":","for","key",",","value","in","cri_out",".","items","(",")",":","out","[","key","]","=","value","if","type","(","met_out",")","is","dict",":","for","key",",","value","in","met_out",".","items","(",")",":","out","[","key","]","=","value","return","out"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L65-L96"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"DefaultModel._init_network","parameters":"(self, engine=None)","argument_list":"","return_statement":"return net_factory(engine)","docstring":"Create the network using the bootstrap network factory","docstring_summary":"Create the network using the bootstrap network factory","docstring_tokens":["Create","the","network","using","the","bootstrap","network","factory"],"function":"def _init_network(self, engine=None):\n \"\"\" Create the network using the bootstrap network factory\n \"\"\"\n return net_factory(engine)","function_tokens":["def","_init_network","(","self",",","engine","=","None",")",":","return","net_factory","(","engine",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L141-L144"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"DefaultModel._init_criterions","parameters":"(self, engine=None)","argument_list":"","return_statement":"return criterions","docstring":"Create the two criterions using the bootstrap criterion factory","docstring_summary":"Create the two criterions using the bootstrap criterion factory","docstring_tokens":["Create","the","two","criterions","using","the","bootstrap","criterion","factory"],"function":"def _init_criterions(self, engine=None):\n \"\"\" Create the two criterions using the bootstrap criterion factory\n \"\"\"\n # by default all modes have criterions\n if engine:\n modes = list(engine.dataset.keys()) # [train, val] for mnist\n else:\n modes = ['train', 'eval']\n\n criterions = {}\n for mode in modes:\n tmp_cri = cri_factory(engine, mode)\n if tmp_cri is not None:\n criterions[mode] = tmp_cri\n return criterions","function_tokens":["def","_init_criterions","(","self",",","engine","=","None",")",":","# by default all modes have criterions","if","engine",":","modes","=","list","(","engine",".","dataset",".","keys","(",")",")","# [train, val] for mnist","else",":","modes","=","[","'train'",",","'eval'","]","criterions","=","{","}","for","mode","in","modes",":","tmp_cri","=","cri_factory","(","engine",",","mode",")","if","tmp_cri","is","not","None",":","criterions","[","mode","]","=","tmp_cri","return","criterions"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L146-L160"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"DefaultModel._init_metrics","parameters":"(self, engine=None)","argument_list":"","return_statement":"return metrics","docstring":"Create the two metrics using the bootstrap metric factory","docstring_summary":"Create the two metrics using the bootstrap metric factory","docstring_tokens":["Create","the","two","metrics","using","the","bootstrap","metric","factory"],"function":"def _init_metrics(self, engine=None):\n \"\"\" Create the two metrics using the bootstrap metric factory\n \"\"\"\n # by default all modes have metrics\n if engine:\n modes = list(engine.dataset.keys())\n else:\n modes = ['train', 'eval']\n\n metrics = {}\n for mode in modes:\n tmp_met = met_factory(engine, mode)\n if tmp_met is not None:\n metrics[mode] = tmp_met\n return metrics","function_tokens":["def","_init_metrics","(","self",",","engine","=","None",")",":","# by default all modes have metrics","if","engine",":","modes","=","list","(","engine",".","dataset",".","keys","(",")",")","else",":","modes","=","[","'train'",",","'eval'","]","metrics","=","{","}","for","mode","in","modes",":","tmp_met","=","met_factory","(","engine",",","mode",")","if","tmp_met","is","not","None",":","metrics","[","mode","]","=","tmp_met","return","metrics"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L162-L176"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"SimpleModel.forward","parameters":"(self, batch)","argument_list":"","return_statement":"return out","docstring":"The forward call to the network uses batch['data'] instead of batch","docstring_summary":"The forward call to the network uses batch['data'] instead of batch","docstring_tokens":["The","forward","call","to","the","network","uses","batch","[","data","]","instead","of","batch"],"function":"def forward(self, batch):\n \"\"\" The forward call to the network uses batch['data'] instead of batch\n \"\"\"\n batch = self.prepare_batch(batch)\n net_out = self.network(batch['data'])\n\n cri_out = {}\n if self.mode in self.criterions:\n cri_tmp = self.criterions[self.mode](net_out, batch)\n if cri_tmp is not None:\n cri_out = cri_tmp\n\n met_out = {}\n if self.mode in self.metrics:\n met_tmp = self.metrics[self.mode](cri_out, net_out, batch)\n if met_tmp is not None:\n met_out = met_tmp\n\n out = {}\n if type(net_out) is dict:\n for key, value in net_out.items():\n out[key] = value\n if type(cri_out) is dict:\n for key, value in cri_out.items():\n out[key] = value\n if type(met_out) is dict:\n for key, value in met_out.items():\n out[key] = value\n return out","function_tokens":["def","forward","(","self",",","batch",")",":","batch","=","self",".","prepare_batch","(","batch",")","net_out","=","self",".","network","(","batch","[","'data'","]",")","cri_out","=","{","}","if","self",".","mode","in","self",".","criterions",":","cri_tmp","=","self",".","criterions","[","self",".","mode","]","(","net_out",",","batch",")","if","cri_tmp","is","not","None",":","cri_out","=","cri_tmp","met_out","=","{","}","if","self",".","mode","in","self",".","metrics",":","met_tmp","=","self",".","metrics","[","self",".","mode","]","(","cri_out",",","net_out",",","batch",")","if","met_tmp","is","not","None",":","met_out","=","met_tmp","out","=","{","}","if","type","(","net_out",")","is","dict",":","for","key",",","value","in","net_out",".","items","(",")",":","out","[","key","]","=","value","if","type","(","cri_out",")","is","dict",":","for","key",",","value","in","cri_out",".","items","(",")",":","out","[","key","]","=","value","if","type","(","met_out",")","is","dict",":","for","key",",","value","in","met_out",".","items","(",")",":","out","[","key","]","=","value","return","out"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L191-L219"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/metrics\/accuracy.py","language":"python","identifier":"accuracy","parameters":"(output, target, topk=None, ignore_index=None)","argument_list":"","return_statement":"return res","docstring":"Computes the precision@k for the specified values of k","docstring_summary":"Computes the precision","docstring_tokens":["Computes","the","precision"],"function":"def accuracy(output, target, topk=None, ignore_index=None):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n topk = topk or [1, 5]\n\n if ignore_index is not None:\n target_mask = (target != ignore_index)\n target = target[target_mask]\n output_mask = target_mask.unsqueeze(1)\n output_mask = output_mask.expand_as(output)\n output = output[output_mask]\n output = output.view(-1, output_mask.size(1))\n\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 \/ batch_size)[0])\n return res","function_tokens":["def","accuracy","(","output",",","target",",","topk","=","None",",","ignore_index","=","None",")",":","topk","=","topk","or","[","1",",","5","]","if","ignore_index","is","not","None",":","target_mask","=","(","target","!=","ignore_index",")","target","=","target","[","target_mask","]","output_mask","=","target_mask",".","unsqueeze","(","1",")","output_mask","=","output_mask",".","expand_as","(","output",")","output","=","output","[","output_mask","]","output","=","output",".","view","(","-","1",",","output_mask",".","size","(","1",")",")","maxk","=","max","(","topk",")","batch_size","=","target",".","size","(","0",")","_",",","pred","=","output",".","topk","(","maxk",",","1",",","True",",","True",")","pred","=","pred",".","t","(",")","correct","=","pred",".","eq","(","target",".","view","(","1",",","-","1",")",".","expand_as","(","pred",")",")","res","=","[","]","for","k","in","topk",":","correct_k","=","correct","[",":","k","]",".","view","(","-","1",")",".","float","(",")",".","sum","(","0",",","keepdim","=","True",")","res",".","append","(","correct_k",".","mul_","(","100.0","\/","batch_size",")","[","0","]",")","return","res"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/metrics\/accuracy.py#L19-L42"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/networks\/data_parallel.py","language":"python","identifier":"gather","parameters":"(outputs, target_device, dim=0)","argument_list":"","return_statement":"","docstring":"r\"\"\"\n Gathers tensors from different GPUs on a specified device\n (-1 means the CPU).","docstring_summary":"r\"\"\"\n Gathers tensors from different GPUs on a specified device\n (-1 means the CPU).","docstring_tokens":["r","Gathers","tensors","from","different","GPUs","on","a","specified","device","(","-","1","means","the","CPU",")","."],"function":"def gather(outputs, target_device, dim=0):\n r\"\"\"\n Gathers tensors from different GPUs on a specified device\n (-1 means the CPU).\n \"\"\"\n def gather_map(outputs):\n out = outputs[0]\n if torch.is_tensor(out):\n return Gather.apply(target_device, dim, *outputs)\n if out is None:\n return None\n if isinstance(out, dict):\n if not all((len(out) == len(d) for d in outputs)):\n raise ValueError('All dicts must have the same number of keys')\n return type(out)(((k, gather_map([d[k] for d in outputs]))\n for k in out))\n return type(out)(map(gather_map, zip(*outputs)))\n\n # Recursive function calls like this create reference cycles.\n # Setting the function to None clears the refcycle.\n try:\n return gather_map(outputs)\n finally:\n gather_map = None","function_tokens":["def","gather","(","outputs",",","target_device",",","dim","=","0",")",":","def","gather_map","(","outputs",")",":","out","=","outputs","[","0","]","if","torch",".","is_tensor","(","out",")",":","return","Gather",".","apply","(","target_device",",","dim",",","*","outputs",")","if","out","is","None",":","return","None","if","isinstance","(","out",",","dict",")",":","if","not","all","(","(","len","(","out",")","==","len","(","d",")","for","d","in","outputs",")",")",":","raise","ValueError","(","'All dicts must have the same number of keys'",")","return","type","(","out",")","(","(","(","k",",","gather_map","(","[","d","[","k","]","for","d","in","outputs","]",")",")","for","k","in","out",")",")","return","type","(","out",")","(","map","(","gather_map",",","zip","(","*","outputs",")",")",")","# Recursive function calls like this create reference cycles.","# Setting the function to None clears the refcycle.","try",":","return","gather_map","(","outputs",")","finally",":","gather_map","=","None"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/networks\/data_parallel.py#L6-L29"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.generate_view","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Generate a view.html via an asynchronous call to `self.view.generate()`","docstring_summary":"Generate a view.html via an asynchronous call to `self.view.generate()`","docstring_tokens":["Generate","a","view",".","html","via","an","asynchronous","call","to","self",".","view",".","generate","()"],"function":"def generate_view(self):\n \"\"\" Generate a view.html via an asynchronous call to `self.view.generate()`\n \"\"\"\n if self.view is not None:\n if hasattr(self.view, 'current_thread') and self.view.current_thread.is_alive():\n Logger()('Skipping view generation: another view is already being generated', log_level=Logger.WARNING)\n Logger()('Consider removing batch entries from views.items in order to speed it up', log_level=Logger.WARNING)\n else:\n # TODO: Redesign this threading system so it wont slow down training\n # Python threads don't really exist, because of the interpreter lock\n # we might need multi-proessing or some other way.\n self.view.current_thread = threading.Thread(target=self.view.generate)\n self.view.current_thread.start()","function_tokens":["def","generate_view","(","self",")",":","if","self",".","view","is","not","None",":","if","hasattr","(","self",".","view",",","'current_thread'",")","and","self",".","view",".","current_thread",".","is_alive","(",")",":","Logger","(",")","(","'Skipping view generation: another view is already being generated'",",","log_level","=","Logger",".","WARNING",")","Logger","(",")","(","'Consider removing batch entries from views.items in order to speed it up'",",","log_level","=","Logger",".","WARNING",")","else",":","# TODO: Redesign this threading system so it wont slow down training","# Python threads don't really exist, because of the interpreter lock","# we might need multi-proessing or some other way.","self",".","view",".","current_thread","=","threading",".","Thread","(","target","=","self",".","view",".","generate",")","self",".","view",".","current_thread",".","start","(",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L31-L43"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.hook","parameters":"(self, name)","argument_list":"","return_statement":"","docstring":"Run all the callback functions that have been registered\n for a hook.\n\n Args:\n name: the name of the hook","docstring_summary":"Run all the callback functions that have been registered\n for a hook.","docstring_tokens":["Run","all","the","callback","functions","that","have","been","registered","for","a","hook","."],"function":"def hook(self, name):\n \"\"\" Run all the callback functions that have been registered\n for a hook.\n\n Args:\n name: the name of the hook\n \"\"\"\n if name in self.hooks:\n for func in self.hooks[name]:\n func()","function_tokens":["def","hook","(","self",",","name",")",":","if","name","in","self",".","hooks",":","for","func","in","self",".","hooks","[","name","]",":","func","(",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L57-L66"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.register_hook","parameters":"(self, name, func)","argument_list":"","return_statement":"","docstring":"Register a callback function to be triggered when the hook\n is called.\n\n Args:\n name: the name of the hook\n func: the callback function (no argument)\n\n Example usage:\n\n .. code-block:: python\n\n def func():\n print('hooked!')\n\n engine.register_hook('train_on_start_batch', func)","docstring_summary":"Register a callback function to be triggered when the hook\n is called.","docstring_tokens":["Register","a","callback","function","to","be","triggered","when","the","hook","is","called","."],"function":"def register_hook(self, name, func):\n \"\"\" Register a callback function to be triggered when the hook\n is called.\n\n Args:\n name: the name of the hook\n func: the callback function (no argument)\n\n Example usage:\n\n .. code-block:: python\n\n def func():\n print('hooked!')\n\n engine.register_hook('train_on_start_batch', func)\n \"\"\"\n if name not in self.hooks:\n self.hooks[name] = []\n self.hooks[name].append(func)","function_tokens":["def","register_hook","(","self",",","name",",","func",")",":","if","name","not","in","self",".","hooks",":","self",".","hooks","[","name","]","=","[","]","self",".","hooks","[","name","]",".","append","(","func",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L68-L87"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.resume","parameters":"(self, map_location=None)","argument_list":"","return_statement":"","docstring":"Resume a checkpoint using the `bootstrap.lib.options.Options`","docstring_summary":"Resume a checkpoint using the `bootstrap.lib.options.Options`","docstring_tokens":["Resume","a","checkpoint","using","the","bootstrap",".","lib",".","options",".","Options"],"function":"def resume(self, map_location=None):\n \"\"\" Resume a checkpoint using the `bootstrap.lib.options.Options`\n \"\"\"\n Logger()('Loading {} checkpoint'.format(Options()['exp']['resume']))\n self.load(Options()['exp']['dir'],\n Options()['exp']['resume'],\n self.model, self.optimizer,\n map_location=map_location)\n self.epoch += 1","function_tokens":["def","resume","(","self",",","map_location","=","None",")",":","Logger","(",")","(","'Loading {} checkpoint'",".","format","(","Options","(",")","[","'exp'","]","[","'resume'","]",")",")","self",".","load","(","Options","(",")","[","'exp'","]","[","'dir'","]",",","Options","(",")","[","'exp'","]","[","'resume'","]",",","self",".","model",",","self",".","optimizer",",","map_location","=","map_location",")","self",".","epoch","+=","1"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L89-L97"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.eval","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Launch evaluation procedures","docstring_summary":"Launch evaluation procedures","docstring_tokens":["Launch","evaluation","procedures"],"function":"def eval(self):\n \"\"\" Launch evaluation procedures\n \"\"\"\n Logger()('Launching evaluation procedures')\n\n if Options()['dataset']['eval_split']:\n # self.epoch-1 to be equal to the same resumed epoch\n # or to be equal to -1 when not resumed\n self.eval_epoch(self.model, self.dataset['eval'], self.epoch - 1, logs_json=True)\n\n Logger()('Ending evaluation procedures')","function_tokens":["def","eval","(","self",")",":","Logger","(",")","(","'Launching evaluation procedures'",")","if","Options","(",")","[","'dataset'","]","[","'eval_split'","]",":","# self.epoch-1 to be equal to the same resumed epoch","# or to be equal to -1 when not resumed","self",".","eval_epoch","(","self",".","model",",","self",".","dataset","[","'eval'","]",",","self",".","epoch","-","1",",","logs_json","=","True",")","Logger","(",")","(","'Ending evaluation procedures'",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L99-L109"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.train","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Launch training procedures\n\n List of the hooks:\n\n - train_on_start: before the full training procedure","docstring_summary":"Launch training procedures","docstring_tokens":["Launch","training","procedures"],"function":"def train(self):\n \"\"\" Launch training procedures\n\n List of the hooks:\n\n - train_on_start: before the full training procedure\n\n \"\"\"\n Logger()('Launching training procedures')\n\n self.hook('train_on_start')\n while self.epoch < Options()['engine']['nb_epochs']:\n self.train_epoch(self.model, self.dataset['train'], self.optimizer, self.epoch)\n\n if Options()['dataset']['eval_split']:\n out = self.eval_epoch(self.model, self.dataset['eval'], self.epoch)\n\n if 'saving_criteria' in Options()['engine'] and Options()['engine']['saving_criteria'] is not None:\n for saving_criteria in Options()['engine']['saving_criteria']:\n if self.is_best(out, saving_criteria):\n name = saving_criteria.split(':')[0]\n Logger()('Saving best checkpoint for strategy {}'.format(name))\n self.save(Options()['exp']['dir'], 'best_{}'.format(name), self.model, self.optimizer)\n\n Logger()('Saving last checkpoint')\n self.save(Options()['exp']['dir'], 'last', self.model, self.optimizer)\n self.epoch += 1\n\n Logger()('Ending training procedures')","function_tokens":["def","train","(","self",")",":","Logger","(",")","(","'Launching training procedures'",")","self",".","hook","(","'train_on_start'",")","while","self",".","epoch","<","Options","(",")","[","'engine'","]","[","'nb_epochs'","]",":","self",".","train_epoch","(","self",".","model",",","self",".","dataset","[","'train'","]",",","self",".","optimizer",",","self",".","epoch",")","if","Options","(",")","[","'dataset'","]","[","'eval_split'","]",":","out","=","self",".","eval_epoch","(","self",".","model",",","self",".","dataset","[","'eval'","]",",","self",".","epoch",")","if","'saving_criteria'","in","Options","(",")","[","'engine'","]","and","Options","(",")","[","'engine'","]","[","'saving_criteria'","]","is","not","None",":","for","saving_criteria","in","Options","(",")","[","'engine'","]","[","'saving_criteria'","]",":","if","self",".","is_best","(","out",",","saving_criteria",")",":","name","=","saving_criteria",".","split","(","':'",")","[","0","]","Logger","(",")","(","'Saving best checkpoint for strategy {}'",".","format","(","name",")",")","self",".","save","(","Options","(",")","[","'exp'","]","[","'dir'","]",",","'best_{}'",".","format","(","name",")",",","self",".","model",",","self",".","optimizer",")","Logger","(",")","(","'Saving last checkpoint'",")","self",".","save","(","Options","(",")","[","'exp'","]","[","'dir'","]",",","'last'",",","self",".","model",",","self",".","optimizer",")","self",".","epoch","+=","1","Logger","(",")","(","'Ending training procedures'",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L111-L139"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.train_epoch","parameters":"(self, model, dataset, optimizer, epoch, mode='train')","argument_list":"","return_statement":"","docstring":"Launch training procedures for one epoch\n\n List of the hooks:\n\n - train_on_start_epoch: before the training procedure for an epoch\n - train_on_start_batch: before the training precedure for a batch\n - train_on_forward: after the forward of the model\n - train_on_backward: after the backward of the loss\n - train_on_update: after the optimization step\n - train_on_print: after the print to the terminal\n - train_on_end_batch: end of the training procedure for a batch\n - train_on_end_epoch: before saving the logs in logs.json\n - train_on_flush: end of the training procedure for an epoch","docstring_summary":"Launch training procedures for one epoch","docstring_tokens":["Launch","training","procedures","for","one","epoch"],"function":"def train_epoch(self, model, dataset, optimizer, epoch, mode='train'):\n \"\"\" Launch training procedures for one epoch\n\n List of the hooks:\n\n - train_on_start_epoch: before the training procedure for an epoch\n - train_on_start_batch: before the training precedure for a batch\n - train_on_forward: after the forward of the model\n - train_on_backward: after the backward of the loss\n - train_on_update: after the optimization step\n - train_on_print: after the print to the terminal\n - train_on_end_batch: end of the training procedure for a batch\n - train_on_end_epoch: before saving the logs in logs.json\n - train_on_flush: end of the training procedure for an epoch\n \"\"\"\n utils.set_random_seed(Options()['misc']['seed'] + epoch) # to be able to reproduce exps on reload\n Logger()('Training model on {}set for epoch {}'.format(dataset.split, epoch))\n model.train()\n\n timer = {\n 'begin': time.time(),\n 'elapsed': time.time(),\n 'process': None,\n 'load': None,\n 'run_avg': 0\n }\n out_epoch = {}\n batch_loader = dataset.make_batch_loader()\n\n self.hook(f'{mode}_on_start_epoch')\n for i, batch in enumerate(batch_loader):\n timer['load'] = time.time() - timer['elapsed']\n self.hook(f'{mode}_on_start_batch')\n\n optimizer.zero_grad()\n out = model(batch)\n self.hook(f'{mode}_on_forward')\n\n if not torch.isnan(out['loss']):\n out['loss'].backward()\n else:\n Logger()('NaN detected')\n # torch.cuda.synchronize()\n self.hook(f'{mode}_on_backward')\n\n optimizer.step()\n # torch.cuda.synchronize()\n self.hook(f'{mode}_on_update')\n\n timer['process'] = time.time() - timer['elapsed']\n if i == 0:\n timer['run_avg'] = timer['process']\n else:\n timer['run_avg'] = timer['run_avg'] * 0.8 + timer['process'] * 0.2\n\n Logger().log_value(f'{mode}_batch.epoch', epoch, should_print=False)\n Logger().log_value(f'{mode}_batch.batch', i, should_print=False)\n Logger().log_value(f'{mode}_batch.timer.process', timer['process'], should_print=False)\n Logger().log_value(f'{mode}_batch.timer.load', timer['load'], should_print=False)\n\n for key, value in out.items():\n if torch.is_tensor(value):\n if value.numel() <= 1:\n value = value.item() # get number from a torch scalar\n else:\n continue\n if isinstance(value, (list, dict, tuple)):\n continue\n if key not in out_epoch:\n out_epoch[key] = []\n out_epoch[key].append(value)\n Logger().log_value(f'{mode}_batch.' + key, value, should_print=False)\n\n if i % Options()['engine']['print_freq'] == 0 or i == len(batch_loader) - 1:\n Logger()(\"{}: epoch {} | batch {}\/{}\".format(mode, epoch, i, len(batch_loader) - 1))\n Logger()(\"{} elapsed: {} | left: {}\".format(\n ' ' * len(mode),\n datetime.timedelta(seconds=math.floor(time.time() - timer['begin'])),\n datetime.timedelta(seconds=math.floor(timer['run_avg'] * (len(batch_loader) - 1 - i)))))\n Logger()(\"{} process: {:.5f} | load: {:.5f}\".format(' ' * len(mode), timer['process'], timer['load']))\n Logger()(\"{} loss: {:.5f}\".format(' ' * len(mode), out['loss'].data.item()))\n self.hook(f'{mode}_on_print')\n\n timer['elapsed'] = time.time()\n self.hook(f'{mode}_on_end_batch')\n\n Logger().log_value(f'{mode}_epoch.epoch', epoch, should_print=True)\n for key, value in out_epoch.items():\n Logger().log_value(f'{mode}_epoch.' + key, np.asarray(value).mean(), should_print=True)\n\n self.hook(f'{mode}_on_end_epoch')\n Logger().flush()\n self.hook(f'{mode}_on_flush')","function_tokens":["def","train_epoch","(","self",",","model",",","dataset",",","optimizer",",","epoch",",","mode","=","'train'",")",":","utils",".","set_random_seed","(","Options","(",")","[","'misc'","]","[","'seed'","]","+","epoch",")","# to be able to reproduce exps on reload","Logger","(",")","(","'Training model on {}set for epoch {}'",".","format","(","dataset",".","split",",","epoch",")",")","model",".","train","(",")","timer","=","{","'begin'",":","time",".","time","(",")",",","'elapsed'",":","time",".","time","(",")",",","'process'",":","None",",","'load'",":","None",",","'run_avg'",":","0","}","out_epoch","=","{","}","batch_loader","=","dataset",".","make_batch_loader","(",")","self",".","hook","(","f'{mode}_on_start_epoch'",")","for","i",",","batch","in","enumerate","(","batch_loader",")",":","timer","[","'load'","]","=","time",".","time","(",")","-","timer","[","'elapsed'","]","self",".","hook","(","f'{mode}_on_start_batch'",")","optimizer",".","zero_grad","(",")","out","=","model","(","batch",")","self",".","hook","(","f'{mode}_on_forward'",")","if","not","torch",".","isnan","(","out","[","'loss'","]",")",":","out","[","'loss'","]",".","backward","(",")","else",":","Logger","(",")","(","'NaN detected'",")","# torch.cuda.synchronize()","self",".","hook","(","f'{mode}_on_backward'",")","optimizer",".","step","(",")","# torch.cuda.synchronize()","self",".","hook","(","f'{mode}_on_update'",")","timer","[","'process'","]","=","time",".","time","(",")","-","timer","[","'elapsed'","]","if","i","==","0",":","timer","[","'run_avg'","]","=","timer","[","'process'","]","else",":","timer","[","'run_avg'","]","=","timer","[","'run_avg'","]","*","0.8","+","timer","[","'process'","]","*","0.2","Logger","(",")",".","log_value","(","f'{mode}_batch.epoch'",",","epoch",",","should_print","=","False",")","Logger","(",")",".","log_value","(","f'{mode}_batch.batch'",",","i",",","should_print","=","False",")","Logger","(",")",".","log_value","(","f'{mode}_batch.timer.process'",",","timer","[","'process'","]",",","should_print","=","False",")","Logger","(",")",".","log_value","(","f'{mode}_batch.timer.load'",",","timer","[","'load'","]",",","should_print","=","False",")","for","key",",","value","in","out",".","items","(",")",":","if","torch",".","is_tensor","(","value",")",":","if","value",".","numel","(",")","<=","1",":","value","=","value",".","item","(",")","# get number from a torch scalar","else",":","continue","if","isinstance","(","value",",","(","list",",","dict",",","tuple",")",")",":","continue","if","key","not","in","out_epoch",":","out_epoch","[","key","]","=","[","]","out_epoch","[","key","]",".","append","(","value",")","Logger","(",")",".","log_value","(","f'{mode}_batch.'","+","key",",","value",",","should_print","=","False",")","if","i","%","Options","(",")","[","'engine'","]","[","'print_freq'","]","==","0","or","i","==","len","(","batch_loader",")","-","1",":","Logger","(",")","(","\"{}: epoch {} | batch {}\/{}\"",".","format","(","mode",",","epoch",",","i",",","len","(","batch_loader",")","-","1",")",")","Logger","(",")","(","\"{} elapsed: {} | left: {}\"",".","format","(","' '","*","len","(","mode",")",",","datetime",".","timedelta","(","seconds","=","math",".","floor","(","time",".","time","(",")","-","timer","[","'begin'","]",")",")",",","datetime",".","timedelta","(","seconds","=","math",".","floor","(","timer","[","'run_avg'","]","*","(","len","(","batch_loader",")","-","1","-","i",")",")",")",")",")","Logger","(",")","(","\"{} process: {:.5f} | load: {:.5f}\"",".","format","(","' '","*","len","(","mode",")",",","timer","[","'process'","]",",","timer","[","'load'","]",")",")","Logger","(",")","(","\"{} loss: {:.5f}\"",".","format","(","' '","*","len","(","mode",")",",","out","[","'loss'","]",".","data",".","item","(",")",")",")","self",".","hook","(","f'{mode}_on_print'",")","timer","[","'elapsed'","]","=","time",".","time","(",")","self",".","hook","(","f'{mode}_on_end_batch'",")","Logger","(",")",".","log_value","(","f'{mode}_epoch.epoch'",",","epoch",",","should_print","=","True",")","for","key",",","value","in","out_epoch",".","items","(",")",":","Logger","(",")",".","log_value","(","f'{mode}_epoch.'","+","key",",","np",".","asarray","(","value",")",".","mean","(",")",",","should_print","=","True",")","self",".","hook","(","f'{mode}_on_end_epoch'",")","Logger","(",")",".","flush","(",")","self",".","hook","(","f'{mode}_on_flush'",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L141-L233"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.eval_epoch","parameters":"(self, model, dataset, epoch, mode='eval', logs_json=True)","argument_list":"","return_statement":"return out","docstring":"Launch evaluation procedures for one epoch\n\n List of the hooks (``mode='eval'`` by default):\n\n - mode_on_start_epoch: before the evaluation procedure for an epoch\n - mode_on_start_batch: before the evaluation precedure for a batch\n - mode_on_forward: after the forward of the model\n - mode_on_print: after the print to the terminal\n - mode_on_end_batch: end of the evaluation procedure for a batch\n - mode_on_end_epoch: before saving the logs in logs.json\n - mode_on_flush: end of the evaluation procedure for an epoch\n\n Returns:\n out(dict): mean of all the scalar outputs of the model, indexed by output name, for this epoch","docstring_summary":"Launch evaluation procedures for one epoch","docstring_tokens":["Launch","evaluation","procedures","for","one","epoch"],"function":"def eval_epoch(self, model, dataset, epoch, mode='eval', logs_json=True):\n \"\"\" Launch evaluation procedures for one epoch\n\n List of the hooks (``mode='eval'`` by default):\n\n - mode_on_start_epoch: before the evaluation procedure for an epoch\n - mode_on_start_batch: before the evaluation precedure for a batch\n - mode_on_forward: after the forward of the model\n - mode_on_print: after the print to the terminal\n - mode_on_end_batch: end of the evaluation procedure for a batch\n - mode_on_end_epoch: before saving the logs in logs.json\n - mode_on_flush: end of the evaluation procedure for an epoch\n\n Returns:\n out(dict): mean of all the scalar outputs of the model, indexed by output name, for this epoch\n \"\"\"\n utils.set_random_seed(Options()['misc']['seed'] + epoch) # to be able to reproduce exps on reload\n Logger()('Evaluating model on {}set for epoch {}'.format(dataset.split, epoch))\n model.eval()\n\n timer = {\n 'begin': time.time(),\n 'elapsed': time.time(),\n 'process': None,\n 'load': None,\n 'run_avg': 0\n }\n out_epoch = {}\n batch_loader = dataset.make_batch_loader()\n\n self.hook('{}_on_start_epoch'.format(mode))\n for i, batch in enumerate(batch_loader):\n timer['load'] = time.time() - timer['elapsed']\n self.hook('{}_on_start_batch'.format(mode))\n\n with torch.no_grad():\n out = model(batch)\n # torch.cuda.synchronize()\n self.hook('{}_on_forward'.format(mode))\n\n timer['process'] = time.time() - timer['elapsed']\n if i == 0:\n timer['run_avg'] = timer['process']\n else:\n timer['run_avg'] = timer['run_avg'] * 0.8 + timer['process'] * 0.2\n\n Logger().log_value('{}_batch.batch'.format(mode), i, should_print=False)\n Logger().log_value('{}_batch.epoch'.format(mode), epoch, should_print=False)\n Logger().log_value('{}_batch.timer.process'.format(mode), timer['process'], should_print=False)\n Logger().log_value('{}_batch.timer.load'.format(mode), timer['load'], should_print=False)\n\n for key, value in out.items():\n if torch.is_tensor(value):\n if value.dim() <= 1:\n value = value.item() # get number from a torch scalar\n else:\n continue\n if isinstance(value, (list, dict, tuple)):\n continue\n if key not in out_epoch:\n out_epoch[key] = []\n out_epoch[key].append(value)\n Logger().log_value('{}_batch.{}'.format(mode, key), value, should_print=False)\n\n if i % Options()['engine']['print_freq'] == 0:\n Logger()(\"{}: epoch {} | batch {}\/{}\".format(mode, epoch, i, len(batch_loader) - 1))\n Logger()(\"{} elapsed: {} | left: {}\".format(\n ' ' * len(mode),\n datetime.timedelta(seconds=math.floor(time.time() - timer['begin'])),\n datetime.timedelta(seconds=math.floor(timer['run_avg'] * (len(batch_loader) - 1 - i)))))\n Logger()(\"{} process: {:.5f} | load: {:.5f}\".format(' ' * len(mode), timer['process'], timer['load']))\n self.hook('{}_on_print'.format(mode))\n\n timer['elapsed'] = time.time()\n self.hook('{}_on_end_batch'.format(mode))\n\n out = {}\n for key, value in out_epoch.items():\n out[key] = sum(value) \/ len(value)\n\n Logger().log_value('{}_epoch.epoch'.format(mode), epoch, should_print=True)\n for key, value in out.items():\n Logger().log_value('{}_epoch.{}'.format(mode, key), value, should_print=True)\n\n self.hook('{}_on_end_epoch'.format(mode))\n if logs_json:\n Logger().flush()\n\n self.hook('{}_on_flush'.format(mode))\n return out","function_tokens":["def","eval_epoch","(","self",",","model",",","dataset",",","epoch",",","mode","=","'eval'",",","logs_json","=","True",")",":","utils",".","set_random_seed","(","Options","(",")","[","'misc'","]","[","'seed'","]","+","epoch",")","# to be able to reproduce exps on reload","Logger","(",")","(","'Evaluating model on {}set for epoch {}'",".","format","(","dataset",".","split",",","epoch",")",")","model",".","eval","(",")","timer","=","{","'begin'",":","time",".","time","(",")",",","'elapsed'",":","time",".","time","(",")",",","'process'",":","None",",","'load'",":","None",",","'run_avg'",":","0","}","out_epoch","=","{","}","batch_loader","=","dataset",".","make_batch_loader","(",")","self",".","hook","(","'{}_on_start_epoch'",".","format","(","mode",")",")","for","i",",","batch","in","enumerate","(","batch_loader",")",":","timer","[","'load'","]","=","time",".","time","(",")","-","timer","[","'elapsed'","]","self",".","hook","(","'{}_on_start_batch'",".","format","(","mode",")",")","with","torch",".","no_grad","(",")",":","out","=","model","(","batch",")","# torch.cuda.synchronize()","self",".","hook","(","'{}_on_forward'",".","format","(","mode",")",")","timer","[","'process'","]","=","time",".","time","(",")","-","timer","[","'elapsed'","]","if","i","==","0",":","timer","[","'run_avg'","]","=","timer","[","'process'","]","else",":","timer","[","'run_avg'","]","=","timer","[","'run_avg'","]","*","0.8","+","timer","[","'process'","]","*","0.2","Logger","(",")",".","log_value","(","'{}_batch.batch'",".","format","(","mode",")",",","i",",","should_print","=","False",")","Logger","(",")",".","log_value","(","'{}_batch.epoch'",".","format","(","mode",")",",","epoch",",","should_print","=","False",")","Logger","(",")",".","log_value","(","'{}_batch.timer.process'",".","format","(","mode",")",",","timer","[","'process'","]",",","should_print","=","False",")","Logger","(",")",".","log_value","(","'{}_batch.timer.load'",".","format","(","mode",")",",","timer","[","'load'","]",",","should_print","=","False",")","for","key",",","value","in","out",".","items","(",")",":","if","torch",".","is_tensor","(","value",")",":","if","value",".","dim","(",")","<=","1",":","value","=","value",".","item","(",")","# get number from a torch scalar","else",":","continue","if","isinstance","(","value",",","(","list",",","dict",",","tuple",")",")",":","continue","if","key","not","in","out_epoch",":","out_epoch","[","key","]","=","[","]","out_epoch","[","key","]",".","append","(","value",")","Logger","(",")",".","log_value","(","'{}_batch.{}'",".","format","(","mode",",","key",")",",","value",",","should_print","=","False",")","if","i","%","Options","(",")","[","'engine'","]","[","'print_freq'","]","==","0",":","Logger","(",")","(","\"{}: epoch {} | batch {}\/{}\"",".","format","(","mode",",","epoch",",","i",",","len","(","batch_loader",")","-","1",")",")","Logger","(",")","(","\"{} elapsed: {} | left: {}\"",".","format","(","' '","*","len","(","mode",")",",","datetime",".","timedelta","(","seconds","=","math",".","floor","(","time",".","time","(",")","-","timer","[","'begin'","]",")",")",",","datetime",".","timedelta","(","seconds","=","math",".","floor","(","timer","[","'run_avg'","]","*","(","len","(","batch_loader",")","-","1","-","i",")",")",")",")",")","Logger","(",")","(","\"{} process: {:.5f} | load: {:.5f}\"",".","format","(","' '","*","len","(","mode",")",",","timer","[","'process'","]",",","timer","[","'load'","]",")",")","self",".","hook","(","'{}_on_print'",".","format","(","mode",")",")","timer","[","'elapsed'","]","=","time",".","time","(",")","self",".","hook","(","'{}_on_end_batch'",".","format","(","mode",")",")","out","=","{","}","for","key",",","value","in","out_epoch",".","items","(",")",":","out","[","key","]","=","sum","(","value",")","\/","len","(","value",")","Logger","(",")",".","log_value","(","'{}_epoch.epoch'",".","format","(","mode",")",",","epoch",",","should_print","=","True",")","for","key",",","value","in","out",".","items","(",")",":","Logger","(",")",".","log_value","(","'{}_epoch.{}'",".","format","(","mode",",","key",")",",","value",",","should_print","=","True",")","self",".","hook","(","'{}_on_end_epoch'",".","format","(","mode",")",")","if","logs_json",":","Logger","(",")",".","flush","(",")","self",".","hook","(","'{}_on_flush'",".","format","(","mode",")",")","return","out"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L235-L324"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.is_best","parameters":"(self, out, saving_criteria)","argument_list":"","return_statement":"return False","docstring":"Verify if the last model is the best for a specific saving criteria\n\n Args:\n out(dict): mean of all the scalar outputs of model indexed by output name\n saving_criteria(str):\n\n Returns:\n is_best(bool)\n\n Example usage:\n\n .. code-block:: python\n\n out = {\n 'loss': 0.2,\n 'acctop1': 87.02\n }\n\n engine.is_best(out, 'loss:min')","docstring_summary":"Verify if the last model is the best for a specific saving criteria","docstring_tokens":["Verify","if","the","last","model","is","the","best","for","a","specific","saving","criteria"],"function":"def is_best(self, out, saving_criteria):\n \"\"\" Verify if the last model is the best for a specific saving criteria\n\n Args:\n out(dict): mean of all the scalar outputs of model indexed by output name\n saving_criteria(str):\n\n Returns:\n is_best(bool)\n\n Example usage:\n\n .. code-block:: python\n\n out = {\n 'loss': 0.2,\n 'acctop1': 87.02\n }\n\n engine.is_best(out, 'loss:min')\n \"\"\"\n if ':min' in saving_criteria:\n name = saving_criteria.replace(':min', '')\n order = '<'\n elif ':max' in saving_criteria:\n name = saving_criteria.replace(':max', '')\n order = '>'\n else:\n error_msg = \"\"\"'--engine.saving_criteria' named '{}' does not specify order,\n you need to chose between '{}' or '{}' to specify if the criteria needs to be minimize or maximize\"\"\".format(\n saving_criteria, saving_criteria + ':min', saving_criteria + ':max')\n raise ValueError(error_msg)\n\n if name not in out:\n raise KeyError(\"'--engine.saving_criteria' named '{}' not in outputs '{}'\".format(name, list(out.keys())))\n\n if name not in self.best_out:\n self.best_out[name] = out[name]\n return True\n else:\n if eval('{} {} {}'.format(out[name], order, self.best_out[name])):\n self.best_out[name] = out[name]\n return True\n\n return False","function_tokens":["def","is_best","(","self",",","out",",","saving_criteria",")",":","if","':min'","in","saving_criteria",":","name","=","saving_criteria",".","replace","(","':min'",",","''",")","order","=","'<'","elif","':max'","in","saving_criteria",":","name","=","saving_criteria",".","replace","(","':max'",",","''",")","order","=","'>'","else",":","error_msg","=","\"\"\"'--engine.saving_criteria' named '{}' does not specify order,\n you need to chose between '{}' or '{}' to specify if the criteria needs to be minimize or maximize\"\"\"",".","format","(","saving_criteria",",","saving_criteria","+","':min'",",","saving_criteria","+","':max'",")","raise","ValueError","(","error_msg",")","if","name","not","in","out",":","raise","KeyError","(","\"'--engine.saving_criteria' named '{}' not in outputs '{}'\"",".","format","(","name",",","list","(","out",".","keys","(",")",")",")",")","if","name","not","in","self",".","best_out",":","self",".","best_out","[","name","]","=","out","[","name","]","return","True","else",":","if","eval","(","'{} {} {}'",".","format","(","out","[","name","]",",","order",",","self",".","best_out","[","name","]",")",")",":","self",".","best_out","[","name","]","=","out","[","name","]","return","True","return","False"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L326-L370"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.load","parameters":"(self, dir_logs, name, model, optimizer, map_location=None)","argument_list":"","return_statement":"","docstring":"Load a checkpoint\n\n Args:\n dir_logs: directory of the checkpoint\n name: name of the checkpoint\n model: model associated to the checkpoint\n optimizer: optimizer associated to the checkpoint","docstring_summary":"Load a checkpoint","docstring_tokens":["Load","a","checkpoint"],"function":"def load(self, dir_logs, name, model, optimizer, map_location=None):\n \"\"\" Load a checkpoint\n\n Args:\n dir_logs: directory of the checkpoint\n name: name of the checkpoint\n model: model associated to the checkpoint\n optimizer: optimizer associated to the checkpoint\n \"\"\"\n path_template = os.path.join(dir_logs, 'ckpt_{}_{}.pth.tar')\n\n Logger()('Loading model...')\n model_state = torch.load(path_template.format(name, 'model'), map_location=map_location)\n model.load_state_dict(model_state)\n\n if Options()['dataset']['train_split'] is not None:\n if os.path.isfile(path_template.format(name, 'optimizer')):\n Logger()('Loading optimizer...')\n optimizer_state = torch.load(path_template.format(name, 'optimizer'), map_location=map_location)\n optimizer.load_state_dict(optimizer_state)\n else:\n Logger()('No optimizer checkpoint', log_level=Logger.WARNING)\n\n if os.path.isfile(path_template.format(name, 'engine')):\n Logger()('Loading engine...')\n engine_state = torch.load(path_template.format(name, 'engine'), map_location=map_location)\n self.load_state_dict(engine_state)\n else:\n Logger()('No engine checkpoint', log_level=Logger.WARNING)","function_tokens":["def","load","(","self",",","dir_logs",",","name",",","model",",","optimizer",",","map_location","=","None",")",":","path_template","=","os",".","path",".","join","(","dir_logs",",","'ckpt_{}_{}.pth.tar'",")","Logger","(",")","(","'Loading model...'",")","model_state","=","torch",".","load","(","path_template",".","format","(","name",",","'model'",")",",","map_location","=","map_location",")","model",".","load_state_dict","(","model_state",")","if","Options","(",")","[","'dataset'","]","[","'train_split'","]","is","not","None",":","if","os",".","path",".","isfile","(","path_template",".","format","(","name",",","'optimizer'",")",")",":","Logger","(",")","(","'Loading optimizer...'",")","optimizer_state","=","torch",".","load","(","path_template",".","format","(","name",",","'optimizer'",")",",","map_location","=","map_location",")","optimizer",".","load_state_dict","(","optimizer_state",")","else",":","Logger","(",")","(","'No optimizer checkpoint'",",","log_level","=","Logger",".","WARNING",")","if","os",".","path",".","isfile","(","path_template",".","format","(","name",",","'engine'",")",")",":","Logger","(",")","(","'Loading engine...'",")","engine_state","=","torch",".","load","(","path_template",".","format","(","name",",","'engine'",")",",","map_location","=","map_location",")","self",".","load_state_dict","(","engine_state",")","else",":","Logger","(",")","(","'No engine checkpoint'",",","log_level","=","Logger",".","WARNING",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L372-L400"} {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.save","parameters":"(self, dir_logs, name, model, optimizer)","argument_list":"","return_statement":"","docstring":"Save a checkpoint\n\n Args:\n dir_logs: directory of the checkpoint\n name: name of the checkpoint\n model: model associated to the checkpoint\n optimizer: optimizer associated to the checkpoint","docstring_summary":"Save a checkpoint","docstring_tokens":["Save","a","checkpoint"],"function":"def save(self, dir_logs, name, model, optimizer):\n \"\"\" Save a checkpoint\n\n Args:\n dir_logs: directory of the checkpoint\n name: name of the checkpoint\n model: model associated to the checkpoint\n optimizer: optimizer associated to the checkpoint\n \"\"\"\n path_template = os.path.join(dir_logs, 'ckpt_{}_{}.pth.tar')\n\n Logger()('Saving model...')\n model_state = model.state_dict()\n torch.save(model_state, path_template.format(name, 'model'))\n\n Logger()('Saving optimizer...')\n optimizer_state = optimizer.state_dict()\n torch.save(optimizer_state, path_template.format(name, 'optimizer'))\n\n Logger()('Saving engine...')\n engine_state = self.state_dict()\n torch.save(engine_state, path_template.format(name, 'engine'))","function_tokens":["def","save","(","self",",","dir_logs",",","name",",","model",",","optimizer",")",":","path_template","=","os",".","path",".","join","(","dir_logs",",","'ckpt_{}_{}.pth.tar'",")","Logger","(",")","(","'Saving model...'",")","model_state","=","model",".","state_dict","(",")","torch",".","save","(","model_state",",","path_template",".","format","(","name",",","'model'",")",")","Logger","(",")","(","'Saving optimizer...'",")","optimizer_state","=","optimizer",".","state_dict","(",")","torch",".","save","(","optimizer_state",",","path_template",".","format","(","name",",","'optimizer'",")",")","Logger","(",")","(","'Saving engine...'",")","engine_state","=","self",".","state_dict","(",")","torch",".","save","(","engine_state",",","path_template",".","format","(","name",",","'engine'",")",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L402-L423"}