Dataset Viewer
Auto-converted to Parquet
code
stringlengths
118
171k
apis
sequence
extract_api
stringlengths
145
164k
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import numpy as np import oneflow as flow import onnxruntime as ort import onnx from collections import OrderedDict import tempfile import os import shutil def convert_to_onnx_and_check( job_func, print_outlier=False, explicit_init=True, external_data=False, ort_optimize=True, opset=None, ): check_point = flow.train.CheckPoint() if explicit_init: # it is a trick to keep check_point.save() from hanging when there is no variable @flow.global_function(flow.FunctionConfig()) def add_var(): return flow.get_variable( name="trick", shape=(1,), dtype=flow.float, initializer=flow.random_uniform_initializer(), ) check_point.init() flow_weight_dir = tempfile.TemporaryDirectory() check_point.save(flow_weight_dir.name) # TODO(daquexian): a more elegant way? while not os.path.exists(os.path.join(flow_weight_dir.name, "snapshot_done")): pass onnx_model_dir = tempfile.TemporaryDirectory() onnx_model_path = os.path.join(onnx_model_dir.name, "model.onnx") flow.onnx.export( job_func, flow_weight_dir.name, onnx_model_path, opset=opset, external_data=external_data, ) flow_weight_dir.cleanup() ort_sess_opt = ort.SessionOptions() ort_sess_opt.graph_optimization_level = ( ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED if ort_optimize else ort.GraphOptimizationLevel.ORT_DISABLE_ALL ) sess = ort.InferenceSession(onnx_model_path, sess_options=ort_sess_opt) onnx_model_dir.cleanup() assert len(sess.get_outputs()) == 1 assert len(sess.get_inputs()) <= 1 ipt_dict = OrderedDict() for ipt in sess.get_inputs(): ipt_data = np.random.uniform(low=-10, high=10, size=ipt.shape).astype( np.float32 ) ipt_dict[ipt.name] = ipt_data onnx_res = sess.run([], ipt_dict)[0] oneflow_res = job_func(*ipt_dict.values()).get().numpy() rtol, atol = 1e-2, 1e-5 if print_outlier: a = onnx_res.flatten() b = oneflow_res.flatten() for i in range(len(a)): if np.abs(a[i] - b[i]) > atol + rtol * np.abs(b[i]): print("a[{}]={}, b[{}]={}".format(i, a[i], i, b[i])) assert np.allclose(onnx_res, oneflow_res, rtol=rtol, atol=atol)
[ "oneflow.FunctionConfig", "oneflow.random_uniform_initializer", "oneflow.train.CheckPoint", "oneflow.onnx.export" ]
[((927, 950), 'oneflow.train.CheckPoint', 'flow.train.CheckPoint', ([], {}), '()\n', (948, 950), True, 'import oneflow as flow\n'), ((1396, 1425), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (1423, 1425), False, 'import tempfile\n'), ((1629, 1658), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (1656, 1658), False, 'import tempfile\n'), ((1681, 1728), 'os.path.join', 'os.path.join', (['onnx_model_dir.name', '"""model.onnx"""'], {}), "(onnx_model_dir.name, 'model.onnx')\n", (1693, 1728), False, 'import os\n'), ((1733, 1845), 'oneflow.onnx.export', 'flow.onnx.export', (['job_func', 'flow_weight_dir.name', 'onnx_model_path'], {'opset': 'opset', 'external_data': 'external_data'}), '(job_func, flow_weight_dir.name, onnx_model_path, opset=\n opset, external_data=external_data)\n', (1749, 1845), True, 'import oneflow as flow\n'), ((1937, 1957), 'onnxruntime.SessionOptions', 'ort.SessionOptions', ([], {}), '()\n', (1955, 1957), True, 'import onnxruntime as ort\n'), ((2156, 2220), 'onnxruntime.InferenceSession', 'ort.InferenceSession', (['onnx_model_path'], {'sess_options': 'ort_sess_opt'}), '(onnx_model_path, sess_options=ort_sess_opt)\n', (2176, 2220), True, 'import onnxruntime as ort\n'), ((2344, 2357), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2355, 2357), False, 'from collections import OrderedDict\n'), ((2937, 2993), 'numpy.allclose', 'np.allclose', (['onnx_res', 'oneflow_res'], {'rtol': 'rtol', 'atol': 'atol'}), '(onnx_res, oneflow_res, rtol=rtol, atol=atol)\n', (2948, 2993), True, 'import numpy as np\n'), ((1093, 1114), 'oneflow.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (1112, 1114), True, 'import oneflow as flow\n'), ((1541, 1592), 'os.path.join', 'os.path.join', (['flow_weight_dir.name', '"""snapshot_done"""'], {}), "(flow_weight_dir.name, 'snapshot_done')\n", (1553, 1592), False, 'import os\n'), ((2411, 2462), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-10)', 'high': '(10)', 'size': 'ipt.shape'}), '(low=-10, high=10, size=ipt.shape)\n', (2428, 2462), True, 'import numpy as np\n'), ((2807, 2826), 'numpy.abs', 'np.abs', (['(a[i] - b[i])'], {}), '(a[i] - b[i])\n', (2813, 2826), True, 'import numpy as np\n'), ((1297, 1330), 'oneflow.random_uniform_initializer', 'flow.random_uniform_initializer', ([], {}), '()\n', (1328, 1330), True, 'import oneflow as flow\n'), ((2843, 2855), 'numpy.abs', 'np.abs', (['b[i]'], {}), '(b[i])\n', (2849, 2855), True, 'import numpy as np\n')]
# coding=utf-8 # Copyright 2021 The OneFlow Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import oneflow as flow from oneflow.utils.data import Sampler class CyclicSampler(Sampler): """ This sampler supports cyclic sampling, and it is also compatible with non-data parallelism and data parallelism. Arguments: dataset: dataset to be sampled. micro_batch_size: batch size for per model instance. global_batch_size is micro_batch_size times data_parallel_size. shuffle: whether to shuffle the dataset. consumed_samples: the number of samples that have been trained at the current time, used for resuming training (default: ``0``). data_parallel_rank: local rank for data parallelism. data_parallel_size: the size of data parallelism. seed: random seed, used for reproducing experiments (default: ``0``). """ def __init__( self, dataset, micro_batch_size, shuffle=False, consumed_samples=0, data_parallel_rank=0, data_parallel_size=1, seed=0, ): self.dataset = dataset self.data_size = len(self.dataset) self.shuffle = shuffle self.data_parallel_rank = data_parallel_rank self.data_parallel_size = data_parallel_size self.micro_batch_size = micro_batch_size self.actual_batch_size = self.micro_batch_size * self.data_parallel_size self.data_size_per_epoch = self.data_size // self.actual_batch_size * self.micro_batch_size self.consumed_samples = consumed_samples self.seed = seed def __iter__(self): """divide the data into data_parallel_size buckets, and shuffle it if `shuffle` is set to `True`. Each processor samples from its own buckets and data_loader will load the corresponding data. """ epoch = self.consumed_samples // self.data_size_per_epoch current_epoch_samples = self.consumed_samples % self.data_size_per_epoch batch = [] while True: bucket_offset = current_epoch_samples // self.data_parallel_size start_idx = self.data_parallel_rank * self.data_size_per_epoch if self.shuffle: generator = flow.Generator() generator.manual_seed(self.seed + epoch) random_idx = flow.randperm(self.data_size_per_epoch, generator=generator).tolist() indices = [start_idx + x for x in random_idx[bucket_offset:]] else: seq_idx = flow.arange(self.data_size_per_epoch).tolist() indices = [start_idx + x for x in seq_idx[bucket_offset:]] epoch += 1 if hasattr(self.dataset, "supports_prefetch") and self.dataset.supports_prefetch: self.dataset.prefetch(indices) for idx in indices: batch.append(idx) if len(batch) == self.micro_batch_size: self.consumed_samples += self.actual_batch_size yield batch batch = [] current_epoch_samples = 0 def __len__(self): return self.data_size def set_consumed_samples(self, consumed_samples): """You can recover the training iteration by setting `consumed_samples`.""" self.consumed_samples = consumed_samples def set_epoch(self, epoch): """Used for restoring training status.""" self.epoch = epoch class SingleRoundSampler(Sampler): """ This sampler supports single round sampling, and it is also compatible with non data parallelism and data parallelism. Arguments: dataset: dataset to be sampled. micro_batch_size: batch size for per model instance, global_batch_size is micro_batch_size times data_parallel_size. shuffle: whether to shuffle the dataset. data_parallel_rank: local rank for data parallelism. data_parallel_size: the size of data parallelism. seed: random seed, used for reproducing experiments (default: ``0``). drop_last: whether to drop the remaining data (default: ``False``). """ def __init__( self, dataset, micro_batch_size, shuffle=False, data_parallel_rank=0, data_parallel_size=1, seed=0, drop_last=False, ): self.dataset = dataset self.data_size = len(self.dataset) self.shuffle = shuffle self.data_parallel_rank = data_parallel_rank self.data_parallel_size = data_parallel_size self.micro_batch_size = micro_batch_size self.seed = seed self.drop_last = drop_last def __iter__(self): bucket_size = self.data_size // self.data_parallel_size remain = self.data_size % self.data_parallel_size start_idx = self.data_parallel_rank * bucket_size if self.data_parallel_rank < remain: bucket_size += 1 start_idx += min(self.data_parallel_rank, remain) if self.shuffle: generator = flow.Generator() generator.manual_seed(self.seed) random_idx = flow.randperm(bucket_size, generator=generator).tolist() indices = [start_idx + x for x in random_idx] else: seq_idx = flow.arange(bucket_size).tolist() indices = [start_idx + x for x in seq_idx] if hasattr(self.dataset, "supports_prefetch") and self.dataset.supports_prefetch: self.dataset.prefetch(indices) batch = [] for idx in indices: batch.append(idx) if len(batch) == self.micro_batch_size: yield batch batch = [] if not self.drop_last: if self.data_parallel_rank >= remain and remain > 0: batch.append(0) if len(batch) > 0: yield batch def __len__(self): global_batch_size = self.micro_batch_size * self.data_parallel_size if self.drop_last: return self.data_size // global_batch_size else: return (self.data_size + global_batch_size - 1) // global_batch_size
[ "oneflow.arange", "oneflow.Generator", "oneflow.randperm" ]
[((5675, 5691), 'oneflow.Generator', 'flow.Generator', ([], {}), '()\n', (5689, 5691), True, 'import oneflow as flow\n'), ((2821, 2837), 'oneflow.Generator', 'flow.Generator', ([], {}), '()\n', (2835, 2837), True, 'import oneflow as flow\n'), ((5762, 5809), 'oneflow.randperm', 'flow.randperm', (['bucket_size'], {'generator': 'generator'}), '(bucket_size, generator=generator)\n', (5775, 5809), True, 'import oneflow as flow\n'), ((5913, 5937), 'oneflow.arange', 'flow.arange', (['bucket_size'], {}), '(bucket_size)\n', (5924, 5937), True, 'import oneflow as flow\n'), ((2924, 2984), 'oneflow.randperm', 'flow.randperm', (['self.data_size_per_epoch'], {'generator': 'generator'}), '(self.data_size_per_epoch, generator=generator)\n', (2937, 2984), True, 'import oneflow as flow\n'), ((3116, 3153), 'oneflow.arange', 'flow.arange', (['self.data_size_per_epoch'], {}), '(self.data_size_per_epoch)\n', (3127, 3153), True, 'import oneflow as flow\n')]
""" Modified from https://github.com/microsoft/Swin-Transformer/blob/main/main.py """ import os import time import argparse import datetime import numpy as np import oneflow as flow import oneflow.backends.cudnn as cudnn from flowvision.loss.cross_entropy import ( LabelSmoothingCrossEntropy, SoftTargetCrossEntropy, ) from flowvision.utils.metrics import accuracy, AverageMeter from config import get_config from models import build_model from data import build_loader from lr_scheduler import build_scheduler from optimizer import build_optimizer from logger import create_logger from utils import ( load_checkpoint, save_checkpoint, get_grad_norm, auto_resume_helper, reduce_tensor, ) def parse_option(): parser = argparse.ArgumentParser( "Flowvision image classification training and evaluation script", add_help=False ) parser.add_argument( "--model_arch", type=str, required=True, default="swin_tiny_patch4_window7_224", help="model for training", ) parser.add_argument( "--cfg", type=str, required=True, metavar="FILE", help="path to config file", ) parser.add_argument( "--opts", help="Modify config options by adding 'KEY VALUE' pairs. ", default=None, nargs="+", ) # easy config modification parser.add_argument( "--batch-size", type=int, default=8, help="batch size for single GPU" ) parser.add_argument("--data-path", type=str, help="path to dataset") parser.add_argument( "--zip", action="store_true", help="use zipped dataset instead of folder dataset", ) parser.add_argument( "--cache-mode", type=str, default="part", choices=["no", "full", "part"], help="no: no cache, " "full: cache all data, " "part: sharding the dataset into nonoverlapping pieces and only cache one piece", ) parser.add_argument("--resume", help="resume from checkpoint") parser.add_argument( "--accumulation-steps", type=int, help="gradient accumulation steps" ) parser.add_argument( "--use-checkpoint", action="store_true", help="whether to use gradient checkpointing to save memory", ) parser.add_argument( "--output", default="output", type=str, metavar="PATH", help="root of output folder, the full path is <output>/<model_name>/<tag> (default: output)", ) parser.add_argument("--tag", help="tag of experiment") parser.add_argument("--eval", action="store_true", help="Perform evaluation only") parser.add_argument( "--throughput", action="store_true", help="Test throughput only" ) # distributed training parser.add_argument( "--local_rank", type=int, default=0, required=False, help="local rank for DistributedDataParallel", ) args, unparsed = parser.parse_known_args() config = get_config(args) return args, config def main(config): ( dataset_train, dataset_val, data_loader_train, data_loader_val, mixup_fn, ) = build_loader(config) logger.info(f"Creating model:{config.MODEL.ARCH}") model = build_model(config) model.cuda() logger.info(str(model)) optimizer = build_optimizer(config, model) model = flow.nn.parallel.DistributedDataParallel(model, broadcast_buffers=False) # FIXME: model with DDP wrapper doesn't have model.module model_without_ddp = model n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) logger.info(f"number of params: {n_parameters}") if hasattr(model_without_ddp, "flops"): flops = model_without_ddp.flops() logger.info(f"number of GFLOPs: {flops / 1e9}") lr_scheduler = build_scheduler(config, optimizer, len(data_loader_train)) if config.AUG.MIXUP > 0.0: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif config.MODEL.LABEL_SMOOTHING > 0.0: criterion = LabelSmoothingCrossEntropy(smoothing=config.MODEL.LABEL_SMOOTHING) else: criterion = flow.nn.CrossEntropyLoss() max_accuracy = 0.0 if config.TRAIN.AUTO_RESUME: resume_file = auto_resume_helper(config.OUTPUT) if resume_file: if config.MODEL.RESUME: logger.warning( f"auto-resume changing resume file from {config.MODEL.RESUME} to {resume_file}" ) config.defrost() config.MODEL.RESUME = resume_file config.freeze() logger.info(f"auto resuming from {resume_file}") else: logger.info(f"no checkpoint found in {config.OUTPUT}, ignoring auto resume") if config.MODEL.RESUME: max_accuracy = load_checkpoint( config, model_without_ddp, optimizer, lr_scheduler, logger ) acc1, acc5, loss = validate(config, data_loader_val, model) logger.info( f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%" ) if config.EVAL_MODE: return if config.THROUGHPUT_MODE: throughput(data_loader_val, model, logger) return logger.info("Start training") start_time = time.time() for epoch in range(config.TRAIN.START_EPOCH, config.TRAIN.EPOCHS): data_loader_train.sampler.set_epoch(epoch) train_one_epoch( config, model, criterion, data_loader_train, optimizer, epoch, mixup_fn, lr_scheduler, ) if flow.env.get_rank() == 0 and ( epoch % config.SAVE_FREQ == 0 or epoch == (config.TRAIN.EPOCHS - 1) ): save_checkpoint( config, epoch, model_without_ddp, max_accuracy, optimizer, lr_scheduler, logger, ) # no validate acc1, acc5, loss = validate(config, data_loader_val, model) logger.info( f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%" ) max_accuracy = max(max_accuracy, acc1) logger.info(f"Max accuracy: {max_accuracy:.2f}%") total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) logger.info("Training time {}".format(total_time_str)) def train_one_epoch( config, model, criterion, data_loader, optimizer, epoch, mixup_fn, lr_scheduler ): model.train() optimizer.zero_grad() num_steps = len(data_loader) batch_time = AverageMeter() loss_meter = AverageMeter() norm_meter = AverageMeter() start = time.time() end = time.time() for idx, (samples, targets) in enumerate(data_loader): samples = samples.cuda() targets = targets.cuda() if mixup_fn is not None: samples, targets = mixup_fn(samples, targets) outputs = model(samples) if config.TRAIN.ACCUMULATION_STEPS > 1: loss = criterion(outputs, targets) loss = loss / config.TRAIN.ACCUMULATION_STEPS loss.backward() if config.TRAIN.CLIP_GRAD: grad_norm = flow.nn.utils.clip_grad_norm_( model.parameters(), config.TRAIN.CLIP_GRAD ) else: grad_norm = get_grad_norm(model.parameters()) if (idx + 1) % config.TRAIN.ACCUMULATION_STEPS == 0: optimizer.step() optimizer.zero_grad() lr_scheduler.step_update(epoch * num_steps + idx) else: loss = criterion(outputs, targets) optimizer.zero_grad() loss.backward() if config.TRAIN.CLIP_GRAD: grad_norm = flow.nn.utils.clip_grad_norm_( model.parameters(), config.TRAIN.CLIP_GRAD ) else: grad_norm = get_grad_norm(model.parameters()) optimizer.step() lr_scheduler.step_update(epoch * num_steps + idx) loss_meter.update(loss.item(), targets.size(0)) norm_meter.update(grad_norm) batch_time.update(time.time() - end) end = time.time() if idx % config.PRINT_FREQ == 0: lr = optimizer.param_groups[0]["lr"] etas = batch_time.avg * (num_steps - idx) logger.info( f"Train: [{epoch}/{config.TRAIN.EPOCHS}][{idx}/{num_steps}]\t" f"eta {datetime.timedelta(seconds=int(etas))} lr {lr:.6f}\t" f"time {batch_time.val:.4f} ({batch_time.avg:.4f})\t" f"loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t" f"grad_norm {norm_meter.val:.4f} ({norm_meter.avg:.4f})\t" ) epoch_time = time.time() - start logger.info( f"EPOCH {epoch} training takes {datetime.timedelta(seconds=int(epoch_time))}" ) @flow.no_grad() def validate(config, data_loader, model): criterion = flow.nn.CrossEntropyLoss() model.eval() batch_time = AverageMeter() loss_meter = AverageMeter() acc1_meter = AverageMeter() acc5_meter = AverageMeter() end = time.time() for idx, (images, target) in enumerate(data_loader): images = images.cuda() target = target.cuda() # compute output output = model(images) # measure accuracy and record loss loss = criterion(output, target) acc1, acc5 = accuracy(output, target, topk=(1, 5)) acc1 = reduce_tensor(acc1) acc5 = reduce_tensor(acc5) loss = reduce_tensor(loss) loss_meter.update(loss.item(), target.size(0)) acc1_meter.update(acc1.item(), target.size(0)) acc5_meter.update(acc5.item(), target.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() if idx % config.PRINT_FREQ == 0: logger.info( f"Test: [{idx}/{len(data_loader)}]\t" f"Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t" f"Loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t" f"Acc@1 {acc1_meter.val:.3f} ({acc1_meter.avg:.3f})\t" f"Acc@5 {acc5_meter.val:.3f} ({acc5_meter.avg:.3f})\t" ) logger.info(f" * Acc@1 {acc1_meter.avg:.3f} Acc@5 {acc5_meter.avg:.3f}") return acc1_meter.avg, acc5_meter.avg, loss_meter.avg @flow.no_grad() def throughput(data_loader, model, logger): model.eval() for idx, (images, _) in enumerate(data_loader): images = images.cuda() batch_size = images.shape[0] for i in range(50): model(images) # TODO: add flow.cuda.synchronize() logger.info(f"throughput averaged with 30 times") tic1 = time.time() for i in range(30): model(images) tic2 = time.time() logger.info( f"batch_size {batch_size} throughput {30 * batch_size / (tic2 - tic1)}" ) return if __name__ == "__main__": _, config = parse_option() if "RANK" in os.environ and "WORLD_SIZE" in os.environ: rank = flow.env.get_rank() world_size = flow.env.get_world_size() print(f"RANK and WORLD_SIZE in environ: {rank}/{world_size}") else: rank = -1 world_size = -1 seed = config.SEED + flow.env.get_rank() flow.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True linear_scaled_lr = ( config.TRAIN.BASE_LR * config.DATA.BATCH_SIZE * flow.env.get_world_size() / 512.0 ) linear_scaled_warmup_lr = ( config.TRAIN.WARMUP_LR * config.DATA.BATCH_SIZE * flow.env.get_world_size() / 512.0 ) linear_scaled_min_lr = ( config.TRAIN.MIN_LR * config.DATA.BATCH_SIZE * flow.env.get_world_size() / 512.0 ) # gradient accumulation also need to scale the learning rate if config.TRAIN.ACCUMULATION_STEPS > 1: linear_scaled_lr = linear_scaled_lr * config.TRAIN.ACCUMULATION_STEPS linear_scaled_warmup_lr = ( linear_scaled_warmup_lr * config.TRAIN.ACCUMULATION_STEPS ) linear_scaled_min_lr = linear_scaled_min_lr * config.TRAIN.ACCUMULATION_STEPS config.defrost() config.TRAIN.BASE_LR = linear_scaled_lr config.TRAIN.WARMUP_LR = linear_scaled_warmup_lr config.TRAIN.MIN_LR = linear_scaled_min_lr config.freeze() os.makedirs(config.OUTPUT, exist_ok=True) logger = create_logger( output_dir=config.OUTPUT, dist_rank=flow.env.get_rank(), name=f"{config.MODEL.ARCH}", ) if flow.env.get_rank() == 0: path = os.path.join(config.OUTPUT, "config.json") with open(path, "w") as f: f.write(config.dump()) logger.info(f"Full config saved to {path}") # print config logger.info(config.dump()) main(config)
[ "oneflow.env.get_rank", "oneflow.nn.CrossEntropyLoss", "oneflow.no_grad", "oneflow.env.get_world_size", "oneflow.manual_seed", "oneflow.nn.parallel.DistributedDataParallel" ]
[((9189, 9203), 'oneflow.no_grad', 'flow.no_grad', ([], {}), '()\n', (9201, 9203), True, 'import oneflow as flow\n'), ((10709, 10723), 'oneflow.no_grad', 'flow.no_grad', ([], {}), '()\n', (10721, 10723), True, 'import oneflow as flow\n'), ((754, 868), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""Flowvision image classification training and evaluation script"""'], {'add_help': '(False)'}), "(\n 'Flowvision image classification training and evaluation script',\n add_help=False)\n", (777, 868), False, 'import argparse\n'), ((3034, 3050), 'config.get_config', 'get_config', (['args'], {}), '(args)\n', (3044, 3050), False, 'from config import get_config\n'), ((3224, 3244), 'data.build_loader', 'build_loader', (['config'], {}), '(config)\n', (3236, 3244), False, 'from data import build_loader\n'), ((3313, 3332), 'models.build_model', 'build_model', (['config'], {}), '(config)\n', (3324, 3332), False, 'from models import build_model\n'), ((3395, 3425), 'optimizer.build_optimizer', 'build_optimizer', (['config', 'model'], {}), '(config, model)\n', (3410, 3425), False, 'from optimizer import build_optimizer\n'), ((3438, 3510), 'oneflow.nn.parallel.DistributedDataParallel', 'flow.nn.parallel.DistributedDataParallel', (['model'], {'broadcast_buffers': '(False)'}), '(model, broadcast_buffers=False)\n', (3478, 3510), True, 'import oneflow as flow\n'), ((5411, 5422), 'time.time', 'time.time', ([], {}), '()\n', (5420, 5422), False, 'import time\n'), ((6827, 6841), 'flowvision.utils.metrics.AverageMeter', 'AverageMeter', ([], {}), '()\n', (6839, 6841), False, 'from flowvision.utils.metrics import accuracy, AverageMeter\n'), ((6859, 6873), 'flowvision.utils.metrics.AverageMeter', 'AverageMeter', ([], {}), '()\n', (6871, 6873), False, 'from flowvision.utils.metrics import accuracy, AverageMeter\n'), ((6891, 6905), 'flowvision.utils.metrics.AverageMeter', 'AverageMeter', ([], {}), '()\n', (6903, 6905), False, 'from flowvision.utils.metrics import accuracy, AverageMeter\n'), ((6919, 6930), 'time.time', 'time.time', ([], {}), '()\n', (6928, 6930), False, 'import time\n'), ((6941, 6952), 'time.time', 'time.time', ([], {}), '()\n', (6950, 6952), False, 'import time\n'), ((9262, 9288), 'oneflow.nn.CrossEntropyLoss', 'flow.nn.CrossEntropyLoss', ([], {}), '()\n', (9286, 9288), True, 'import oneflow as flow\n'), ((9324, 9338), 'flowvision.utils.metrics.AverageMeter', 'AverageMeter', ([], {}), '()\n', (9336, 9338), False, 'from flowvision.utils.metrics import accuracy, AverageMeter\n'), ((9356, 9370), 'flowvision.utils.metrics.AverageMeter', 'AverageMeter', ([], {}), '()\n', (9368, 9370), False, 'from flowvision.utils.metrics import accuracy, AverageMeter\n'), ((9388, 9402), 'flowvision.utils.metrics.AverageMeter', 'AverageMeter', ([], {}), '()\n', (9400, 9402), False, 'from flowvision.utils.metrics import accuracy, AverageMeter\n'), ((9420, 9434), 'flowvision.utils.metrics.AverageMeter', 'AverageMeter', ([], {}), '()\n', (9432, 9434), False, 'from flowvision.utils.metrics import accuracy, AverageMeter\n'), ((9446, 9457), 'time.time', 'time.time', ([], {}), '()\n', (9455, 9457), False, 'import time\n'), ((11676, 11698), 'oneflow.manual_seed', 'flow.manual_seed', (['seed'], {}), '(seed)\n', (11692, 11698), True, 'import oneflow as flow\n'), ((11703, 11723), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (11717, 11723), True, 'import numpy as np\n'), ((12755, 12796), 'os.makedirs', 'os.makedirs', (['config.OUTPUT'], {'exist_ok': '(True)'}), '(config.OUTPUT, exist_ok=True)\n', (12766, 12796), False, 'import os\n'), ((4069, 4093), 'flowvision.loss.cross_entropy.SoftTargetCrossEntropy', 'SoftTargetCrossEntropy', ([], {}), '()\n', (4091, 4093), False, 'from flowvision.loss.cross_entropy import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy\n'), ((4363, 4396), 'utils.auto_resume_helper', 'auto_resume_helper', (['config.OUTPUT'], {}), '(config.OUTPUT)\n', (4381, 4396), False, 'from utils import load_checkpoint, save_checkpoint, get_grad_norm, auto_resume_helper, reduce_tensor\n'), ((4926, 5001), 'utils.load_checkpoint', 'load_checkpoint', (['config', 'model_without_ddp', 'optimizer', 'lr_scheduler', 'logger'], {}), '(config, model_without_ddp, optimizer, lr_scheduler, logger)\n', (4941, 5001), False, 'from utils import load_checkpoint, save_checkpoint, get_grad_norm, auto_resume_helper, reduce_tensor\n'), ((6468, 6479), 'time.time', 'time.time', ([], {}), '()\n', (6477, 6479), False, 'import time\n'), ((8473, 8484), 'time.time', 'time.time', ([], {}), '()\n', (8482, 8484), False, 'import time\n'), ((9057, 9068), 'time.time', 'time.time', ([], {}), '()\n', (9066, 9068), False, 'import time\n'), ((9740, 9777), 'flowvision.utils.metrics.accuracy', 'accuracy', (['output', 'target'], {'topk': '(1, 5)'}), '(output, target, topk=(1, 5))\n', (9748, 9777), False, 'from flowvision.utils.metrics import accuracy, AverageMeter\n'), ((9794, 9813), 'utils.reduce_tensor', 'reduce_tensor', (['acc1'], {}), '(acc1)\n', (9807, 9813), False, 'from utils import load_checkpoint, save_checkpoint, get_grad_norm, auto_resume_helper, reduce_tensor\n'), ((9829, 9848), 'utils.reduce_tensor', 'reduce_tensor', (['acc5'], {}), '(acc5)\n', (9842, 9848), False, 'from utils import load_checkpoint, save_checkpoint, get_grad_norm, auto_resume_helper, reduce_tensor\n'), ((9864, 9883), 'utils.reduce_tensor', 'reduce_tensor', (['loss'], {}), '(loss)\n', (9877, 9883), False, 'from utils import load_checkpoint, save_checkpoint, get_grad_norm, auto_resume_helper, reduce_tensor\n'), ((10141, 10152), 'time.time', 'time.time', ([], {}), '()\n', (10150, 10152), False, 'import time\n'), ((11077, 11088), 'time.time', 'time.time', ([], {}), '()\n', (11086, 11088), False, 'import time\n'), ((11159, 11170), 'time.time', 'time.time', ([], {}), '()\n', (11168, 11170), False, 'import time\n'), ((11437, 11456), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (11454, 11456), True, 'import oneflow as flow\n'), ((11478, 11503), 'oneflow.env.get_world_size', 'flow.env.get_world_size', ([], {}), '()\n', (11501, 11503), True, 'import oneflow as flow\n'), ((11652, 11671), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (11669, 11671), True, 'import oneflow as flow\n'), ((12949, 12968), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (12966, 12968), True, 'import oneflow as flow\n'), ((12990, 13032), 'os.path.join', 'os.path.join', (['config.OUTPUT', '"""config.json"""'], {}), "(config.OUTPUT, 'config.json')\n", (13002, 13032), False, 'import os\n'), ((4159, 4225), 'flowvision.loss.cross_entropy.LabelSmoothingCrossEntropy', 'LabelSmoothingCrossEntropy', ([], {'smoothing': 'config.MODEL.LABEL_SMOOTHING'}), '(smoothing=config.MODEL.LABEL_SMOOTHING)\n', (4185, 4225), False, 'from flowvision.loss.cross_entropy import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy\n'), ((4256, 4282), 'oneflow.nn.CrossEntropyLoss', 'flow.nn.CrossEntropyLoss', ([], {}), '()\n', (4280, 4282), True, 'import oneflow as flow\n'), ((5909, 6009), 'utils.save_checkpoint', 'save_checkpoint', (['config', 'epoch', 'model_without_ddp', 'max_accuracy', 'optimizer', 'lr_scheduler', 'logger'], {}), '(config, epoch, model_without_ddp, max_accuracy, optimizer,\n lr_scheduler, logger)\n', (5924, 6009), False, 'from utils import load_checkpoint, save_checkpoint, get_grad_norm, auto_resume_helper, reduce_tensor\n'), ((11849, 11874), 'oneflow.env.get_world_size', 'flow.env.get_world_size', ([], {}), '()\n', (11872, 11874), True, 'import oneflow as flow\n'), ((12003, 12028), 'oneflow.env.get_world_size', 'flow.env.get_world_size', ([], {}), '()\n', (12026, 12028), True, 'import oneflow as flow\n'), ((12135, 12160), 'oneflow.env.get_world_size', 'flow.env.get_world_size', ([], {}), '()\n', (12158, 12160), True, 'import oneflow as flow\n'), ((12877, 12896), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (12894, 12896), True, 'import oneflow as flow\n'), ((5775, 5794), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (5792, 5794), True, 'import oneflow as flow\n'), ((8440, 8451), 'time.time', 'time.time', ([], {}), '()\n', (8449, 8451), False, 'import time\n'), ((10108, 10119), 'time.time', 'time.time', ([], {}), '()\n', (10117, 10119), False, 'import time\n')]
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest from collections import OrderedDict import numpy as np import oneflow.experimental as flow from test_util import GenArgList def _test_gather_nd(test_case, device): input = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) indices = np.array([[0], [2]]) np_out = np.array([[1, 2, 3], [7, 8, 9]]) output = flow.gather_nd( flow.Tensor(input, dtype=flow.float, device=flow.device(device)), flow.Tensor(indices, dtype=flow.int, device=flow.device(device)), ) test_case.assertTrue(np.array_equal(output.numpy(), np_out)) def _test_gather_nd_t(test_case, device): input = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) indices = np.array([[0, 2], [2, 1]]) np_out = np.array([3, 8]) output = flow.gather_nd( flow.Tensor(input, dtype=flow.float, device=flow.device(device)), flow.Tensor(indices, dtype=flow.int, device=flow.device(device)), ) test_case.assertTrue(np.array_equal(output.numpy(), np_out)) def _test_gather_nd_backward(test_case, device): input = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) indices = np.array([[0], [2]]) np_out = np.array([[1, 2, 3], [7, 8, 9]]) np_grad = np.array([[1, 1, 1], [0, 0, 0], [1, 1, 1]]) of_input = flow.Tensor( input, requires_grad=True, dtype=flow.float, device=flow.device(device) ) output = flow.gather_nd( of_input, flow.Tensor(indices, dtype=flow.int, device=flow.device(device)) ) out_sum = output.sum() out_sum.backward() test_case.assertTrue(np.array_equal(output.numpy(), np_out)) test_case.assertTrue(np.array_equal(of_input.grad.numpy(), np_grad)) def _test_gather_nd_backward_t(test_case, device): input = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) indices = np.array([[0, 2], [2, 1]]) np_out = np.array([3, 8]) np_grad = np.array([[0, 0, 1], [0, 0, 0], [0, 1, 0]]) of_input = flow.Tensor( input, requires_grad=True, dtype=flow.float, device=flow.device(device) ) output = flow.gather_nd( of_input, flow.Tensor(indices, dtype=flow.int, device=flow.device(device)) ) out_sum = output.sum() out_sum.backward() test_case.assertTrue(np.array_equal(output.numpy(), np_out)) test_case.assertTrue(np.array_equal(of_input.grad.numpy(), np_grad)) @flow.unittest.skip_unless_1n1d() class TestGather_nd(flow.unittest.TestCase): def test_gather_nd(test_case): arg_dict = OrderedDict() arg_dict["test_fun"] = [ _test_gather_nd, _test_gather_nd_t, _test_gather_nd_backward, _test_gather_nd_backward_t, ] arg_dict["device"] = ["cpu", "cuda"] for arg in GenArgList(arg_dict): arg[0](test_case, *arg[1:]) if __name__ == "__main__": unittest.main()
[ "oneflow.experimental.unittest.skip_unless_1n1d", "oneflow.experimental.device" ]
[((2909, 2941), 'oneflow.experimental.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (2939, 2941), True, 'import oneflow.experimental as flow\n'), ((786, 829), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'], {}), '([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n', (794, 829), True, 'import numpy as np\n'), ((844, 864), 'numpy.array', 'np.array', (['[[0], [2]]'], {}), '([[0], [2]])\n', (852, 864), True, 'import numpy as np\n'), ((878, 910), 'numpy.array', 'np.array', (['[[1, 2, 3], [7, 8, 9]]'], {}), '([[1, 2, 3], [7, 8, 9]])\n', (886, 910), True, 'import numpy as np\n'), ((1215, 1258), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'], {}), '([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n', (1223, 1258), True, 'import numpy as np\n'), ((1273, 1299), 'numpy.array', 'np.array', (['[[0, 2], [2, 1]]'], {}), '([[0, 2], [2, 1]])\n', (1281, 1299), True, 'import numpy as np\n'), ((1313, 1329), 'numpy.array', 'np.array', (['[3, 8]'], {}), '([3, 8])\n', (1321, 1329), True, 'import numpy as np\n'), ((1641, 1684), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'], {}), '([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n', (1649, 1684), True, 'import numpy as np\n'), ((1699, 1719), 'numpy.array', 'np.array', (['[[0], [2]]'], {}), '([[0], [2]])\n', (1707, 1719), True, 'import numpy as np\n'), ((1733, 1765), 'numpy.array', 'np.array', (['[[1, 2, 3], [7, 8, 9]]'], {}), '([[1, 2, 3], [7, 8, 9]])\n', (1741, 1765), True, 'import numpy as np\n'), ((1781, 1824), 'numpy.array', 'np.array', (['[[1, 1, 1], [0, 0, 0], [1, 1, 1]]'], {}), '([[1, 1, 1], [0, 0, 0], [1, 1, 1]])\n', (1789, 1824), True, 'import numpy as np\n'), ((2311, 2354), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'], {}), '([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n', (2319, 2354), True, 'import numpy as np\n'), ((2369, 2395), 'numpy.array', 'np.array', (['[[0, 2], [2, 1]]'], {}), '([[0, 2], [2, 1]])\n', (2377, 2395), True, 'import numpy as np\n'), ((2409, 2425), 'numpy.array', 'np.array', (['[3, 8]'], {}), '([3, 8])\n', (2417, 2425), True, 'import numpy as np\n'), ((2441, 2484), 'numpy.array', 'np.array', (['[[0, 0, 1], [0, 0, 0], [0, 1, 0]]'], {}), '([[0, 0, 1], [0, 0, 0], [0, 1, 0]])\n', (2449, 2484), True, 'import numpy as np\n'), ((3395, 3410), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3408, 3410), False, 'import unittest\n'), ((3041, 3054), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3052, 3054), False, 'from collections import OrderedDict\n'), ((3300, 3320), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (3310, 3320), False, 'from test_util import GenArgList\n'), ((1913, 1932), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (1924, 1932), True, 'import oneflow.experimental as flow\n'), ((2573, 2592), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (2584, 2592), True, 'import oneflow.experimental as flow\n'), ((992, 1011), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (1003, 1011), True, 'import oneflow.experimental as flow\n'), ((1066, 1085), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (1077, 1085), True, 'import oneflow.experimental as flow\n'), ((1411, 1430), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (1422, 1430), True, 'import oneflow.experimental as flow\n'), ((1485, 1504), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (1496, 1504), True, 'import oneflow.experimental as flow\n'), ((2030, 2049), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (2041, 2049), True, 'import oneflow.experimental as flow\n'), ((2690, 2709), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (2701, 2709), True, 'import oneflow.experimental as flow\n')]
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import enum import inspect from google.protobuf import text_format import oneflow._oneflow_internal import oneflow.core.job.job_set_pb2 as job_set_util import oneflow.framework.c_api_util as c_api_util class MultiClientSession(object): class Status(enum.Enum): CREATED = 1 INITED = 2 CLOSED = 3 def __init__(self, sess_id): self.sess_ = oneflow._oneflow_internal.RegsiterSession(sess_id) oneflow._oneflow_internal.CreateMultiClientSessionContext() self.config_proto_ = self._make_config_proto() self.function_flag_name2default_val_ = {} self._update_function_flag_name2defaultVal() self.scope_attr_name2default_val_ = {} self._update_scope_attr_name2defaultVal() self.status_ = self.Status.CREATED def __del__(self): self.TryClose() def TryInit(self): self._check_status(self.Status.CREATED, self.Status.INITED) if self.status_ == self.Status.CREATED: config_proto_str = text_format.MessageToString(self.config_proto) oneflow._oneflow_internal.InitMultiClientSessionContext(config_proto_str) self.status_ = self.Status.INITED def TryClose(self): if self.status_ != self.Status.CLOSED: oneflow._oneflow_internal.TryDestroyMultiClientSessionContext() oneflow._oneflow_internal.ClearSessionById(self.id) self.status_ = self.Status.CLOSED @property def status(self): return self.status_ @property def id(self): return self.sess_.id @property def config_proto(self): return self.config_proto_ @property def resource(self): self._check_status(self.Status.INITED) return c_api_util.CurrentResource() @property def function_flag_name2default_val(self): return self.function_flag_name2default_val_ @property def scope_attr_name2default_val(self): return self.scope_attr_name2default_val_ @property def is_running(self): return self.status_ == self.Status.INITED def AnyGlobalFunctionDefined(self): return False def _check_status(self, *status): check_success = False for stat in status: if self.status_ == stat: check_success = True break if check_success is False: caller_func_name = inspect.stack()[1].function allowed_status = " or ".join([str(stat) for stat in status]) raise ValueError( "The calling to {} is only allowed when status is {}, but current status is {}".format( caller_func_name, allowed_status, self.status_ ) ) def _make_config_proto(self): config_proto = job_set_util.ConfigProto() config_proto.resource.SetInParent() config_proto.session_id = self.id return config_proto def _update_function_flag_name2defaultVal(self): items = c_api_util.GetFunctionConfigDef().attr_name2attr_def.items() self.function_flag_name2default_val_ = {k: v.default_val for (k, v) in items} def _update_scope_attr_name2defaultVal(self): items = c_api_util.GetScopeConfigDef().attr_name2attr_def.items() self.scope_attr_name2default_val_ = {k: v.default_val for (k, v) in items}
[ "oneflow.framework.c_api_util.CurrentResource", "oneflow.framework.c_api_util.GetScopeConfigDef", "oneflow.framework.c_api_util.GetFunctionConfigDef", "oneflow.core.job.job_set_pb2.ConfigProto" ]
[((2346, 2374), 'oneflow.framework.c_api_util.CurrentResource', 'c_api_util.CurrentResource', ([], {}), '()\n', (2372, 2374), True, 'import oneflow.framework.c_api_util as c_api_util\n'), ((3399, 3425), 'oneflow.core.job.job_set_pb2.ConfigProto', 'job_set_util.ConfigProto', ([], {}), '()\n', (3423, 3425), True, 'import oneflow.core.job.job_set_pb2 as job_set_util\n'), ((1608, 1654), 'google.protobuf.text_format.MessageToString', 'text_format.MessageToString', (['self.config_proto'], {}), '(self.config_proto)\n', (1635, 1654), False, 'from google.protobuf import text_format\n'), ((3007, 3022), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (3020, 3022), False, 'import inspect\n'), ((3610, 3643), 'oneflow.framework.c_api_util.GetFunctionConfigDef', 'c_api_util.GetFunctionConfigDef', ([], {}), '()\n', (3641, 3643), True, 'import oneflow.framework.c_api_util as c_api_util\n'), ((3824, 3854), 'oneflow.framework.c_api_util.GetScopeConfigDef', 'c_api_util.GetScopeConfigDef', ([], {}), '()\n', (3852, 3854), True, 'import oneflow.framework.c_api_util as c_api_util\n')]
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import absolute_import import sys from functools import reduce from typing import Any, Optional, Sequence, Union import numpy as np import oneflow import oneflow.core.operator.op_conf_pb2 as op_conf_util import oneflow.core.operator.interface_blob_conf_pb2 as inter_face_blob_conf_util import oneflow.python.framework.c_api_util as c_api_util import oneflow.python.framework.compile_context as compile_context import oneflow.python.framework.distribute as distribute_util import oneflow.python.framework.id_util as id_util import oneflow.python.framework.placement_context as placement_ctx import oneflow.python.framework.remote_blob as remote_blob_util import oneflow.python.framework.dtype as dtype_util from oneflow.python.oneflow_export import oneflow_export import oneflow_api.oneflow.core.register.logical_blob_id as lbi_util import oneflow_api from functools import reduce import traceback class ArgBlobDef(object): def __init__( self, shape, dtype, batch_axis, name=None, distribute=oneflow_api.distribute.auto(), ): lbi = lbi_util.LogicalBlobId() if name is None: name = id_util.UniqueStr("Input_") lbi.set_op_name(name) lbi.set_blob_name("out") self.lbi_ = lbi assert type(shape) is tuple for dim in shape: assert type(dim) is int assert dim > 0 self.shape_ = shape self.dtype_ = dtype assert type(batch_axis) is int self.batch_axis_ = batch_axis self.distribute_ = distribute @property def lbi(self): return self.lbi_ @property def op_name(self): return self.lbi_.op_name() @property def blob_name(self): return self.lbi_.blob_name() @property def unique_name(self): return self.op_name + "/" + self.blob_name + self._Distribute2Str() @property def shape(self): return self.shape_ @property def dtype(self): return self.dtype_ @property def batch_axis(self): return self.batch_axis_ @property def is_dynamic(self): raise NotImplementedError @property def is_tensor_list(self): raise NotImplementedError def with_distribute(self, distribute): return type(self)( shape=self.shape_, dtype=self.dtype_, batch_axis=self.batch_axis_, name=self.op_name, ) def Clone(self, op_name=None): return type(self)( shape=self.shape_, dtype=self.dtype_, batch_axis=self.batch_axis_, name=op_name, ) def AddAndInferOp(self, op_conf): raise NotImplementedError def EagerAddAndInferOp(self, op_conf): raise NotImplementedError def CheckAndAsyncPush(self, session, arg_ndarray): self._CheckNdarray(arg_ndarray) self._AsyncPush(session, arg_ndarray) def _CheckNdarray(self, ndarray): raise NotImplementedError def _AsyncPush(self, session, arg_ndarray): raise NotImplementedError def SetBatchAxisAndSplitAxis(self, interface_blob_conf): raise NotImplementedError def ToInterfaceBlobConf(self): interface_blob_conf = inter_face_blob_conf_util.InterfaceBlobConf() interface_blob_conf.shape.dim.extend(self.shape_) interface_blob_conf.data_type = self.dtype_.oneflow_proto_dtype interface_blob_conf.is_dynamic = self.is_dynamic interface_blob_conf.is_tensor_list = self.is_tensor_list self.SetBatchAxisAndSplitAxis(interface_blob_conf) return interface_blob_conf def _Distribute2Str(self): if type(self.distribute_) is oneflow_api.distribute.AutoDistribute: return "" elif type(self.distribute_) is oneflow_api.distribute.SplitDistribute: return ":S" + str(self.distribute_.axis) elif type(self.distribute_) is oneflow_api.distribute.BroadcastDistribute: return ":B" else: raise NotImplementedError class FixedTensorDef(ArgBlobDef): def __init__( self, shape: Sequence[int], dtype: dtype_util.dtype = dtype_util.float, batch_axis: int = 0, name: Optional[str] = None, ) -> None: if batch_axis is None: batch_axis = oneflow_api.INVALID_BATCH_AXIS assert type(batch_axis) is int if batch_axis != oneflow_api.INVALID_BATCH_AXIS: if batch_axis < 0: batch_axis += len(shape) assert batch_axis >= 0 assert batch_axis < len(shape) ArgBlobDef.__init__( self, shape, dtype=dtype, batch_axis=batch_axis, name=name, ) @property def is_dynamic(self) -> bool: return False @property def is_tensor_list(self) -> bool: return False def AddAndInferOp(self, op_conf: op_conf_util.OperatorConf) -> Any: return compile_context.CurJobAddConsistentOp(op_conf) def EagerAddAndInferOp(self, op_conf: op_conf_util.OperatorConf) -> Any: parallel_symbol = oneflow.current_scope().device_parallel_desc_symbol if ( parallel_symbol.device_tag == "gpu" and list(dict(parallel_symbol.machine_id2device_id_list).keys()) == [0] and parallel_symbol.parallel_num == 1 ): device_tag = "gpu" device_ids = "0:%s" % (parallel_symbol.machine_id2device_id_list[0][0]) else: device_tag = "cpu" device_ids = "0:0" with oneflow.scope.placement(device_tag, device_ids): return compile_context.CurJobAddConsistentOp(op_conf) def SetBatchAxisAndSplitAxis( self, interface_blob_conf: inter_face_blob_conf_util.InterfaceBlobConf ) -> None: if self.batch_axis == oneflow_api.INVALID_BATCH_AXIS: interface_blob_conf.batch_axis.ClearField("value") interface_blob_conf.split_axis.ClearField("value") else: assert type(self.batch_axis) is int interface_blob_conf.batch_axis.value = self.batch_axis interface_blob_conf.split_axis.value = self.batch_axis def _CheckNdarray(self, ndarray: np.ndarray) -> None: assert isinstance(ndarray, np.ndarray) assert ndarray.shape == self.shape def _AsyncPush(self, session: object, arg_ndarray: np.ndarray) -> None: session.AsyncPush(self.op_name, _MakePushNdarrayCallback(arg_ndarray)) class MirroredTensorDef(ArgBlobDef): def __init__( self, shape: Sequence[int], dtype: dtype_util.dtype = dtype_util.float, batch_axis: int = 0, name: Optional[str] = None, ) -> None: assert type(shape) is tuple assert type(batch_axis) is int if batch_axis != oneflow_api.INVALID_BATCH_AXIS: if batch_axis < 0: batch_axis += len(shape) assert batch_axis >= 0 assert batch_axis < len(shape) ArgBlobDef.__init__(self, shape, dtype=dtype, batch_axis=batch_axis, name=name) self.sub_consistent_blob_list_ = [] @property def is_dynamic(self) -> bool: return True @property def is_tensor_list(self) -> bool: return False def AddAndInferOp(self, op_conf: op_conf_util.OperatorConf) -> None: _AddAndInferMirroredOp( self.unique_name, op_conf, self.sub_consistent_blob_list_ ) def EagerAddAndInferOp(self, op_conf: op_conf_util.OperatorConf) -> Any: return compile_context.CurJobAddMirroredOp(op_conf) def SetBatchAxisAndSplitAxis( self, interface_blob_conf: inter_face_blob_conf_util.InterfaceBlobConf ) -> None: assert type(self.batch_axis) is int interface_blob_conf.batch_axis.value = self.batch_axis interface_blob_conf.split_axis.ClearField("value") def _CheckNdarray(self, ndarray_list: Sequence[np.ndarray]) -> None: assert isinstance(ndarray_list, (list, tuple)) assert len(self.sub_consistent_blob_list_) == len(ndarray_list) def GetElemCnt(shape): return reduce(lambda x, y: x * y, shape, 1) for consistent_blob, ndarray in zip( self.sub_consistent_blob_list_, ndarray_list ): assert type(ndarray) is np.ndarray assert len(ndarray.shape) == len(self.shape) assert GetElemCnt(ndarray.shape) <= GetElemCnt(self.shape) def _AsyncPush(self, session: object, ndarray_list: Sequence[np.ndarray]) -> None: for i in range(len(ndarray_list)): sub_blob = self.sub_consistent_blob_list_[i] session.AsyncPush( sub_blob.op_name, _MakePushNdarrayCallback(ndarray_list[i]) ) class MirroredTensorListDef(ArgBlobDef): def __init__( self, shape: Sequence[int], dtype: dtype_util.dtype = dtype_util.float, batch_axis: int = 0, name: Optional[str] = None, ) -> None: assert type(shape) is tuple assert type(batch_axis) is int if batch_axis != oneflow_api.INVALID_BATCH_AXIS: if batch_axis < 0: batch_axis += len(shape) assert batch_axis >= 0 assert batch_axis < len(shape) ArgBlobDef.__init__(self, shape, dtype=dtype, batch_axis=batch_axis, name=name) self.sub_consistent_blob_list_ = [] @property def is_dynamic(self) -> bool: return True @property def is_tensor_list(self) -> bool: return True def AddAndInferOp(self, op_conf: op_conf_util.OperatorConf) -> None: _AddAndInferMirroredOp( self.unique_name, op_conf, self.sub_consistent_blob_list_ ) def EagerAddAndInferOp(self, op_conf: op_conf_util.OperatorConf) -> Any: return compile_context.CurJobAddMirroredOp(op_conf) def SetBatchAxisAndSplitAxis( self, interface_blob_conf: inter_face_blob_conf_util.InterfaceBlobConf ) -> None: assert type(self.batch_axis) is int interface_blob_conf.batch_axis.value = self.batch_axis interface_blob_conf.split_axis.ClearField("value") def _CheckNdarray(self, ndarray_lists: Sequence[np.ndarray]) -> None: assert isinstance(ndarray_lists, (list, tuple)) assert len(self.sub_consistent_blob_list_) == len(ndarray_lists) def GetElemCnt(shape): return reduce(lambda x, y: x * y, shape, 1) for consistent_blob, ndarray_list in zip( self.sub_consistent_blob_list_, ndarray_lists ): assert type(ndarray_list) is list elem_cnt = 0 for ndarray in ndarray_list: assert type(ndarray) is np.ndarray assert len(ndarray.shape) == len(self.shape) elem_cnt += GetElemCnt(ndarray.shape) assert elem_cnt <= GetElemCnt(self.shape) def _AsyncPush(self, session: object, ndarray_lists: Sequence[np.ndarray]) -> None: for i in range(len(ndarray_lists)): sub_blob = self.sub_consistent_blob_list_[i] session.AsyncPush( sub_blob.op_name, _MakePushNdarrayListCallback(ndarray_lists[i]) ) def _AddAndInferMirroredOp(mirrored_lbn, op_conf, sub_consistent_blob_list): compile_context.CurJobAddMirroredOp(op_conf) job_name = oneflow_api.JobBuildAndInferCtx_GetCurrentJobName() num_sub_lbi = c_api_util.JobBuildAndInferCtx_MirroredBlobGetNumSubLbi( job_name, mirrored_lbn ) for i in range(num_sub_lbi): sub_lbi = c_api_util.JobBuildAndInferCtx_MirroredBlobGetSubLbi( job_name, mirrored_lbn, i ) lbi = lbi_util.LogicalBlobId() lbi.set_op_name(sub_lbi.op_name) lbi.set_blob_name(sub_lbi.blob_name) sub_consistent_blob_list.append( oneflow_api.ConsistentBlob(lbi, "", oneflow_api.distribute.auto()) ) def _MakePushNdarrayCallback(ndarray): copied = np.copy(ndarray) def Copy(ofblob): capacity = reduce(lambda x, y: x * y, ofblob.static_shape, 1) elem_cnt = reduce(lambda x, y: x * y, copied.shape, 1) assert elem_cnt <= capacity, "%s v.s. %s" % (copied.shape, ofblob.static_shape) ofblob.CopyFromNdarray(copied) return Copy def _MakePushNdarrayListCallback(ndarray_list): copied = [np.copy(ndarray) for ndarray in ndarray_list] return lambda ofblob: ofblob.CopyFromNdarrayList(copied) @oneflow_export("FixedTensorDef") class DeprecatedFixedTensorDef(FixedTensorDef): def __init__(self, *args, **kwargs): running_script = traceback.format_stack()[-2].split(",")[0].split(" ")[3] if not running_script.endswith('input_blob_def.py"'): print( "WARNING: oneflow.FixedTensorDef has been deprecated. " "Please use oneflow.typing.Numpy.Placeholder instead." ) print( """For instance: - def job_func(images=oneflow.FixedTensorDef((32, 1, 28, 28), dtype=flow.float)) + def job_func(images:oneflow.typing.Numpy.Placeholder((32, 1, 28, 28), dtype=flow.float))""" ) print(traceback.format_stack()[-2]) super().__init__(*args, **kwargs) @oneflow_export("MirroredTensorDef") class DeprecatedMirroredTensorDef(MirroredTensorDef): def __init__(self, *args, **kwargs): running_script = traceback.format_stack()[-2].split(",")[0].split(" ")[3] if not running_script.endswith('input_blob_def.py"'): print( "WARNING: oneflow.MirroredTensorDef has been deprecated. " "Please use oneflow.typing.ListNumpy.Placeholder instead." ) print( """For instance: - def job_func(images=oneflow.MirroredTensorDef((32, 1, 28, 28), dtype=flow.float)) + def job_func(images:oneflow.typing.ListNumpy.Placeholder((32, 1, 28, 28), dtype=flow.float))""" ) print(traceback.format_stack()[-2]) super().__init__(*args, **kwargs) @oneflow_export("MirroredTensorListDef") class DeprecatedTensorListDef(MirroredTensorListDef): def __init__(self, *args, **kwargs): running_script = traceback.format_stack()[-2].split(",")[0].split(" ")[3] if not running_script.endswith('input_blob_def.py"'): print( "WARNING: oneflow.MirroredTensorListDef has been deprecated. " "Please use oneflow.typing.ListListNumpy.Placeholder instead." ) print( """For instance: - def job_func(images=oneflow.MirroredTensorListDef((32, 1, 28, 28), dtype=flow.float)) + def job_func(images:oneflow.typing.ListListNumpy.Placeholder((32, 1, 28, 28), dtype=flow.float))""" ) print(traceback.format_stack()[-2]) super().__init__(*args, **kwargs)
[ "oneflow.python.framework.c_api_util.JobBuildAndInferCtx_MirroredBlobGetSubLbi", "oneflow.python.framework.compile_context.CurJobAddMirroredOp", "oneflow.python.framework.compile_context.CurJobAddConsistentOp", "oneflow.current_scope", "oneflow.python.framework.c_api_util.JobBuildAndInferCtx_MirroredBlobGetNumSubLbi", "oneflow.core.operator.interface_blob_conf_pb2.InterfaceBlobConf", "oneflow.scope.placement", "oneflow.python.framework.id_util.UniqueStr", "oneflow.python.oneflow_export.oneflow_export" ]
[((13187, 13219), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""FixedTensorDef"""'], {}), "('FixedTensorDef')\n", (13201, 13219), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((13988, 14023), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""MirroredTensorDef"""'], {}), "('MirroredTensorDef')\n", (14002, 14023), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((14812, 14851), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""MirroredTensorListDef"""'], {}), "('MirroredTensorListDef')\n", (14826, 14851), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((12010, 12054), 'oneflow.python.framework.compile_context.CurJobAddMirroredOp', 'compile_context.CurJobAddMirroredOp', (['op_conf'], {}), '(op_conf)\n', (12045, 12054), True, 'import oneflow.python.framework.compile_context as compile_context\n'), ((12070, 12121), 'oneflow_api.JobBuildAndInferCtx_GetCurrentJobName', 'oneflow_api.JobBuildAndInferCtx_GetCurrentJobName', ([], {}), '()\n', (12119, 12121), False, 'import oneflow_api\n'), ((12140, 12219), 'oneflow.python.framework.c_api_util.JobBuildAndInferCtx_MirroredBlobGetNumSubLbi', 'c_api_util.JobBuildAndInferCtx_MirroredBlobGetNumSubLbi', (['job_name', 'mirrored_lbn'], {}), '(job_name, mirrored_lbn)\n', (12195, 12219), True, 'import oneflow.python.framework.c_api_util as c_api_util\n'), ((12696, 12712), 'numpy.copy', 'np.copy', (['ndarray'], {}), '(ndarray)\n', (12703, 12712), True, 'import numpy as np\n'), ((1654, 1683), 'oneflow_api.distribute.auto', 'oneflow_api.distribute.auto', ([], {}), '()\n', (1681, 1683), False, 'import oneflow_api\n'), ((1706, 1730), 'oneflow_api.oneflow.core.register.logical_blob_id.LogicalBlobId', 'lbi_util.LogicalBlobId', ([], {}), '()\n', (1728, 1730), True, 'import oneflow_api.oneflow.core.register.logical_blob_id as lbi_util\n'), ((3894, 3939), 'oneflow.core.operator.interface_blob_conf_pb2.InterfaceBlobConf', 'inter_face_blob_conf_util.InterfaceBlobConf', ([], {}), '()\n', (3937, 3939), True, 'import oneflow.core.operator.interface_blob_conf_pb2 as inter_face_blob_conf_util\n'), ((5613, 5659), 'oneflow.python.framework.compile_context.CurJobAddConsistentOp', 'compile_context.CurJobAddConsistentOp', (['op_conf'], {}), '(op_conf)\n', (5650, 5659), True, 'import oneflow.python.framework.compile_context as compile_context\n'), ((8228, 8272), 'oneflow.python.framework.compile_context.CurJobAddMirroredOp', 'compile_context.CurJobAddMirroredOp', (['op_conf'], {}), '(op_conf)\n', (8263, 8272), True, 'import oneflow.python.framework.compile_context as compile_context\n'), ((10527, 10571), 'oneflow.python.framework.compile_context.CurJobAddMirroredOp', 'compile_context.CurJobAddMirroredOp', (['op_conf'], {}), '(op_conf)\n', (10562, 10571), True, 'import oneflow.python.framework.compile_context as compile_context\n'), ((12285, 12364), 'oneflow.python.framework.c_api_util.JobBuildAndInferCtx_MirroredBlobGetSubLbi', 'c_api_util.JobBuildAndInferCtx_MirroredBlobGetSubLbi', (['job_name', 'mirrored_lbn', 'i'], {}), '(job_name, mirrored_lbn, i)\n', (12337, 12364), True, 'import oneflow.python.framework.c_api_util as c_api_util\n'), ((12401, 12425), 'oneflow_api.oneflow.core.register.logical_blob_id.LogicalBlobId', 'lbi_util.LogicalBlobId', ([], {}), '()\n', (12423, 12425), True, 'import oneflow_api.oneflow.core.register.logical_blob_id as lbi_util\n'), ((12755, 12805), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 'ofblob.static_shape', '(1)'], {}), '(lambda x, y: x * y, ofblob.static_shape, 1)\n', (12761, 12805), False, 'from functools import reduce\n'), ((12825, 12868), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 'copied.shape', '(1)'], {}), '(lambda x, y: x * y, copied.shape, 1)\n', (12831, 12868), False, 'from functools import reduce\n'), ((13077, 13093), 'numpy.copy', 'np.copy', (['ndarray'], {}), '(ndarray)\n', (13084, 13093), True, 'import numpy as np\n'), ((1775, 1802), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""Input_"""'], {}), "('Input_')\n", (1792, 1802), True, 'import oneflow.python.framework.id_util as id_util\n'), ((5764, 5787), 'oneflow.current_scope', 'oneflow.current_scope', ([], {}), '()\n', (5785, 5787), False, 'import oneflow\n'), ((6226, 6273), 'oneflow.scope.placement', 'oneflow.scope.placement', (['device_tag', 'device_ids'], {}), '(device_tag, device_ids)\n', (6249, 6273), False, 'import oneflow\n'), ((6294, 6340), 'oneflow.python.framework.compile_context.CurJobAddConsistentOp', 'compile_context.CurJobAddConsistentOp', (['op_conf'], {}), '(op_conf)\n', (6331, 6340), True, 'import oneflow.python.framework.compile_context as compile_context\n'), ((8820, 8856), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 'shape', '(1)'], {}), '(lambda x, y: x * y, shape, 1)\n', (8826, 8856), False, 'from functools import reduce\n'), ((11122, 11158), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 'shape', '(1)'], {}), '(lambda x, y: x * y, shape, 1)\n', (11128, 11158), False, 'from functools import reduce\n'), ((12601, 12630), 'oneflow_api.distribute.auto', 'oneflow_api.distribute.auto', ([], {}), '()\n', (12628, 12630), False, 'import oneflow_api\n'), ((13912, 13936), 'traceback.format_stack', 'traceback.format_stack', ([], {}), '()\n', (13934, 13936), False, 'import traceback\n'), ((14736, 14760), 'traceback.format_stack', 'traceback.format_stack', ([], {}), '()\n', (14758, 14760), False, 'import traceback\n'), ((15580, 15604), 'traceback.format_stack', 'traceback.format_stack', ([], {}), '()\n', (15602, 15604), False, 'import traceback\n'), ((13334, 13358), 'traceback.format_stack', 'traceback.format_stack', ([], {}), '()\n', (13356, 13358), False, 'import traceback\n'), ((14144, 14168), 'traceback.format_stack', 'traceback.format_stack', ([], {}), '()\n', (14166, 14168), False, 'import traceback\n'), ((14972, 14996), 'traceback.format_stack', 'traceback.format_stack', ([], {}), '()\n', (14994, 14996), False, 'import traceback\n')]
import os import time import pickle from tqdm import tqdm import librosa import soundfile as sf import numpy as np import oneflow as flow import utils.data_utils as preprocess from utils.dataset import trainingDataset from model.model import Generator, Discriminator class CycleGANTrainr(object): def __init__( self, logf0s_normalization, mcep_normalization, coded_sps_A_norm, coded_sps_B_norm, model_checkpoint, validation_A_dir, output_A_dir, validation_B_dir, output_B_dir, restart_training_at=None, ): self.start_epoch = 0 self.num_epochs = 200000 self.mini_batch_size = 10 self.dataset_A = self.loadPickleFile(coded_sps_A_norm) self.dataset_B = self.loadPickleFile(coded_sps_B_norm) self.device = flow.device("cuda" if flow.cuda.is_available() else "cpu") # Speech Parameters logf0s_normalization = np.load(logf0s_normalization) self.log_f0s_mean_A = logf0s_normalization["mean_A"] self.log_f0s_std_A = logf0s_normalization["std_A"] self.log_f0s_mean_B = logf0s_normalization["mean_B"] self.log_f0s_std_B = logf0s_normalization["std_B"] mcep_normalization = np.load(mcep_normalization) self.coded_sps_A_mean = mcep_normalization["mean_A"] self.coded_sps_A_std = mcep_normalization["std_A"] self.coded_sps_B_mean = mcep_normalization["mean_B"] self.coded_sps_B_std = mcep_normalization["std_B"] # Generator and Discriminator self.generator_A2B = Generator().to(self.device) self.generator_B2A = Generator().to(self.device) self.discriminator_A = Discriminator().to(self.device) self.discriminator_B = Discriminator().to(self.device) # Loss Functions criterion_mse = flow.nn.MSELoss() # Optimizer g_params = list(self.generator_A2B.parameters()) + list( self.generator_B2A.parameters() ) d_params = list(self.discriminator_A.parameters()) + list( self.discriminator_B.parameters() ) # Initial learning rates self.generator_lr = 2e-4 self.discriminator_lr = 1e-4 # Learning rate decay self.generator_lr_decay = self.generator_lr / 200000 self.discriminator_lr_decay = self.discriminator_lr / 200000 # Starts learning rate decay from after this many iterations have passed self.start_decay = 10000 self.generator_optimizer = flow.optim.Adam( g_params, lr=self.generator_lr, betas=(0.5, 0.999) ) self.discriminator_optimizer = flow.optim.Adam( d_params, lr=self.discriminator_lr, betas=(0.5, 0.999) ) # To Load save previously saved models self.modelCheckpoint = model_checkpoint os.makedirs(self.modelCheckpoint, exist_ok=True) # Validation set Parameters self.validation_A_dir = validation_A_dir self.output_A_dir = output_A_dir os.makedirs(self.output_A_dir, exist_ok=True) self.validation_B_dir = validation_B_dir self.output_B_dir = output_B_dir os.makedirs(self.output_B_dir, exist_ok=True) # Storing Discriminatior and Generator Loss self.generator_loss_store = [] self.discriminator_loss_store = [] self.file_name = "log_store_non_sigmoid.txt" def adjust_lr_rate(self, optimizer, name="generator"): if name == "generator": self.generator_lr = max(0.0, self.generator_lr - self.generator_lr_decay) for param_groups in optimizer.param_groups: param_groups["lr"] = self.generator_lr else: self.discriminator_lr = max( 0.0, self.discriminator_lr - self.discriminator_lr_decay ) for param_groups in optimizer.param_groups: param_groups["lr"] = self.discriminator_lr def reset_grad(self): self.generator_optimizer.zero_grad() self.discriminator_optimizer.zero_grad() def train(self): # Training Begins for epoch in range(self.start_epoch, self.num_epochs): start_time_epoch = time.time() # Constants cycle_loss_lambda = 10 identity_loss_lambda = 5 # Preparing Dataset n_samples = len(self.dataset_A) dataset = trainingDataset( datasetA=self.dataset_A, datasetB=self.dataset_B, n_frames=128 ) train_loader = flow.utils.data.DataLoader( dataset=dataset, batch_size=self.mini_batch_size, shuffle=True, drop_last=False, ) pbar = tqdm(enumerate(train_loader)) for i, (real_A, real_B) in enumerate(train_loader): num_iterations = (n_samples // self.mini_batch_size) * epoch + i if num_iterations > 10000: identity_loss_lambda = 0 if num_iterations > self.start_decay: self.adjust_lr_rate(self.generator_optimizer, name="generator") self.adjust_lr_rate(self.generator_optimizer, name="discriminator") real_A = real_A.to(self.device).float() real_B = real_B.to(self.device).float() # Generator Loss function fake_B = self.generator_A2B(real_A) cycle_A = self.generator_B2A(fake_B) fake_A = self.generator_B2A(real_B) cycle_B = self.generator_A2B(fake_A) identity_A = self.generator_B2A(real_A) identity_B = self.generator_A2B(real_B) d_fake_A = self.discriminator_A(fake_A) d_fake_B = self.discriminator_B(fake_B) # for the second step adverserial loss d_fake_cycle_A = self.discriminator_A(cycle_A) d_fake_cycle_B = self.discriminator_B(cycle_B) # Generator Cycle loss cycleLoss = flow.mean(flow.abs(real_A - cycle_A)) + flow.mean( flow.abs(real_B - cycle_B) ) # Generator Identity Loss identiyLoss = flow.mean(flow.abs(real_A - identity_A)) + flow.mean( flow.abs(real_B - identity_B) ) # Generator Loss generator_loss_A2B = flow.mean((1 - d_fake_B) ** 2) generator_loss_B2A = flow.mean((1 - d_fake_A) ** 2) # Total Generator Loss generator_loss = ( generator_loss_A2B + generator_loss_B2A + cycle_loss_lambda * cycleLoss + identity_loss_lambda * identiyLoss ) self.generator_loss_store.append(generator_loss.item()) # Backprop for Generator self.reset_grad() generator_loss.backward() self.generator_optimizer.step() # Discriminator Feed Forward d_real_A = self.discriminator_A(real_A) d_real_B = self.discriminator_B(real_B) generated_A = self.generator_B2A(real_B) d_fake_A = self.discriminator_A(generated_A) # for the second step adverserial loss cycled_B = self.generator_A2B(generated_A) d_cycled_B = self.discriminator_B(cycled_B) generated_B = self.generator_A2B(real_A) d_fake_B = self.discriminator_B(generated_B) # for the second step adverserial loss cycled_A = self.generator_B2A(generated_B) d_cycled_A = self.discriminator_A(cycled_A) # Loss Functions d_loss_A_real = flow.mean((1 - d_real_A) ** 2) d_loss_A_fake = flow.mean((0 - d_fake_A) ** 2) d_loss_A = (d_loss_A_real + d_loss_A_fake) / 2.0 d_loss_B_real = flow.mean((1 - d_real_B) ** 2) d_loss_B_fake = flow.mean((0 - d_fake_B) ** 2) d_loss_B = (d_loss_B_real + d_loss_B_fake) / 2.0 # the second step adverserial loss d_loss_A_cycled = flow.mean((0 - d_cycled_A) ** 2) d_loss_B_cycled = flow.mean((0 - d_cycled_B) ** 2) d_loss_A_2nd = (d_loss_A_real + d_loss_A_cycled) / 2.0 d_loss_B_2nd = (d_loss_B_real + d_loss_B_cycled) / 2.0 # Final Loss for discriminator with the second step adverserial loss d_loss = (d_loss_A + d_loss_B) / 2.0 + ( d_loss_A_2nd + d_loss_B_2nd ) / 2.0 self.discriminator_loss_store.append(d_loss.item()) # Backprop for Discriminator self.reset_grad() d_loss.backward() self.discriminator_optimizer.step() if (i + 1) % 2 == 0: pbar.set_description( "Iter:{} Generator Loss:{:.4f} Discrimator Loss:{:.4f} GA2B:{:.4f} GB2A:{:.4f} G_id:{:.4f} G_cyc:{:.4f} D_A:{:.4f} D_B:{:.4f}".format( num_iterations, generator_loss.item(), d_loss.item(), generator_loss_A2B, generator_loss_B2A, identiyLoss, cycleLoss, d_loss_A, d_loss_B, ) ) if epoch % 2000 == 0 and epoch != 0: end_time = time.time() store_to_file = "Epoch: {} Generator Loss: {:.4f} Discriminator Loss: {}, Time: {:.2f}\n\n".format( epoch, generator_loss.item(), d_loss.item(), end_time - start_time_epoch, ) self.store_to_file(store_to_file) print( "Epoch: {} Generator Loss: {:.4f} Discriminator Loss: {}, Time: {:.2f}\n\n".format( epoch, generator_loss.item(), d_loss.item(), end_time - start_time_epoch, ) ) # Save the Entire model print("Saving model Checkpoint ......") store_to_file = "Saving model Checkpoint ......" self.store_to_file(store_to_file) self.saveModelCheckPoint(epoch, self.modelCheckpoint) print("Model Saved!") if epoch % 2000 == 0 and epoch != 0: # Validation Set validation_start_time = time.time() self.validation_for_A_dir() self.validation_for_B_dir() validation_end_time = time.time() store_to_file = "Time taken for validation Set: {}".format( validation_end_time - validation_start_time ) self.store_to_file(store_to_file) print( "Time taken for validation Set: {}".format( validation_end_time - validation_start_time ) ) def infer(self, PATH="sample"): num_mcep = 36 sampling_rate = 16000 frame_period = 5.0 n_frames = 128 infer_A_dir = PATH output_A_dir = PATH for file in os.listdir(infer_A_dir): filePath = os.path.join(infer_A_dir, file) wav, _ = librosa.load(filePath, sr=sampling_rate, mono=True) wav = preprocess.wav_padding( wav=wav, sr=sampling_rate, frame_period=frame_period, multiple=4 ) f0, timeaxis, sp, ap = preprocess.world_decompose( wav=wav, fs=sampling_rate, frame_period=frame_period ) f0_converted = preprocess.pitch_conversion( f0=f0, mean_log_src=self.log_f0s_mean_A, std_log_src=self.log_f0s_std_A, mean_log_target=self.log_f0s_mean_B, std_log_target=self.log_f0s_std_B, ) coded_sp = preprocess.world_encode_spectral_envelop( sp=sp, fs=sampling_rate, dim=num_mcep ) coded_sp_transposed = coded_sp.T coded_sp_norm = ( coded_sp_transposed - self.coded_sps_A_mean ) / self.coded_sps_A_std coded_sp_norm = np.array([coded_sp_norm]) if flow.cuda.is_available(): coded_sp_norm = flow.tensor(coded_sp_norm).cuda().float() else: coded_sp_norm = flow.tensor(coded_sp_norm).float() coded_sp_converted_norm = self.generator_A2B(coded_sp_norm) coded_sp_converted_norm = coded_sp_converted_norm.cpu().detach().numpy() coded_sp_converted_norm = np.squeeze(coded_sp_converted_norm) coded_sp_converted = ( coded_sp_converted_norm * self.coded_sps_B_std + self.coded_sps_B_mean ) coded_sp_converted = coded_sp_converted.T coded_sp_converted = np.ascontiguousarray(coded_sp_converted) decoded_sp_converted = preprocess.world_decode_spectral_envelop( coded_sp=coded_sp_converted, fs=sampling_rate ) wav_transformed = preprocess.world_speech_synthesis( f0=f0_converted, decoded_sp=decoded_sp_converted, ap=ap, fs=sampling_rate, frame_period=frame_period, ) sf.write( os.path.join(output_A_dir, "convert_" + os.path.basename(file)), wav_transformed, sampling_rate, ) def validation_for_A_dir(self): num_mcep = 36 sampling_rate = 16000 frame_period = 5.0 n_frames = 128 validation_A_dir = self.validation_A_dir output_A_dir = self.output_A_dir print("Generating Validation Data B from A...") for file in os.listdir(validation_A_dir): filePath = os.path.join(validation_A_dir, file) wav, _ = librosa.load(filePath, sr=sampling_rate, mono=True) wav = preprocess.wav_padding( wav=wav, sr=sampling_rate, frame_period=frame_period, multiple=4 ) f0, timeaxis, sp, ap = preprocess.world_decompose( wav=wav, fs=sampling_rate, frame_period=frame_period ) f0_converted = preprocess.pitch_conversion( f0=f0, mean_log_src=self.log_f0s_mean_A, std_log_src=self.log_f0s_std_A, mean_log_target=self.log_f0s_mean_B, std_log_target=self.log_f0s_std_B, ) coded_sp = preprocess.world_encode_spectral_envelop( sp=sp, fs=sampling_rate, dim=num_mcep ) coded_sp_transposed = coded_sp.T coded_sp_norm = ( coded_sp_transposed - self.coded_sps_A_mean ) / self.coded_sps_A_std coded_sp_norm = np.array([coded_sp_norm]) if flow.cuda.is_available(): coded_sp_norm = flow.tensor(coded_sp_norm).cuda().float() else: coded_sp_norm = flow.tensor(coded_sp_norm).float() coded_sp_converted_norm = self.generator_A2B(coded_sp_norm) coded_sp_converted_norm = coded_sp_converted_norm.cpu().detach().numpy() coded_sp_converted_norm = np.squeeze(coded_sp_converted_norm) coded_sp_converted = ( coded_sp_converted_norm * self.coded_sps_B_std + self.coded_sps_B_mean ) coded_sp_converted = coded_sp_converted.T coded_sp_converted = np.ascontiguousarray(coded_sp_converted) decoded_sp_converted = preprocess.world_decode_spectral_envelop( coded_sp=coded_sp_converted, fs=sampling_rate ) wav_transformed = preprocess.world_speech_synthesis( f0=f0_converted, decoded_sp=decoded_sp_converted, ap=ap, fs=sampling_rate, frame_period=frame_period, ) sf.write( os.path.join(output_A_dir, os.path.basename(file)), wav_transformed, sampling_rate, ) def validation_for_B_dir(self): num_mcep = 36 sampling_rate = 16000 frame_period = 5.0 n_frames = 128 validation_B_dir = self.validation_B_dir output_B_dir = self.output_B_dir print("Generating Validation Data A from B...") for file in os.listdir(validation_B_dir): filePath = os.path.join(validation_B_dir, file) wav, _ = librosa.load(filePath, sr=sampling_rate, mono=True) wav = preprocess.wav_padding( wav=wav, sr=sampling_rate, frame_period=frame_period, multiple=4 ) f0, timeaxis, sp, ap = preprocess.world_decompose( wav=wav, fs=sampling_rate, frame_period=frame_period ) f0_converted = preprocess.pitch_conversion( f0=f0, mean_log_src=self.log_f0s_mean_B, std_log_src=self.log_f0s_std_B, mean_log_target=self.log_f0s_mean_A, std_log_target=self.log_f0s_std_A, ) coded_sp = preprocess.world_encode_spectral_envelop( sp=sp, fs=sampling_rate, dim=num_mcep ) coded_sp_transposed = coded_sp.T coded_sp_norm = ( coded_sp_transposed - self.coded_sps_B_mean ) / self.coded_sps_B_std coded_sp_norm = np.array([coded_sp_norm]) if flow.cuda.is_available(): coded_sp_norm = flow.tensor(coded_sp_norm).cuda().float() else: coded_sp_norm = flow.tensor(coded_sp_norm).float() coded_sp_converted_norm = self.generator_B2A(coded_sp_norm) coded_sp_converted_norm = coded_sp_converted_norm.cpu().detach().numpy() coded_sp_converted_norm = np.squeeze(coded_sp_converted_norm) coded_sp_converted = ( coded_sp_converted_norm * self.coded_sps_A_std + self.coded_sps_A_mean ) coded_sp_converted = coded_sp_converted.T coded_sp_converted = np.ascontiguousarray(coded_sp_converted) decoded_sp_converted = preprocess.world_decode_spectral_envelop( coded_sp=coded_sp_converted, fs=sampling_rate ) wav_transformed = preprocess.world_speech_synthesis( f0=f0_converted, decoded_sp=decoded_sp_converted, ap=ap, fs=sampling_rate, frame_period=frame_period, ) sf.write( os.path.join(output_B_dir, os.path.basename(file)), wav_transformed, sampling_rate, ) def savePickle(self, variable, fileName): with open(fileName, "wb") as f: pickle.dump(variable, f) def loadPickleFile(self, fileName): with open(fileName, "rb") as f: return pickle.load(f) def store_to_file(self, doc): doc = doc + "\n" with open(self.file_name, "a") as myfile: myfile.write(doc) def saveModelCheckPoint(self, epoch, PATH): flow.save( self.generator_A2B.state_dict(), os.path.join(PATH, "generator_A2B_%d" % epoch), ) flow.save( self.generator_B2A.state_dict(), os.path.join(PATH, "generator_B2A_%d" % epoch), ) flow.save( self.discriminator_A.state_dict(), os.path.join(PATH, "discriminator_A_%d" % epoch), ) flow.save( self.discriminator_B.state_dict(), os.path.join(PATH, "discriminator_B_%d" % epoch), ) def loadModel(self, PATH): self.generator_A2B.load_state_dict( flow.load(os.path.join(PATH, "generator_A2B")) ) self.generator_B2A.load_state_dict( flow.load(os.path.join(PATH, "generator_B2A")) ) self.discriminator_A.load_state_dict( flow.load(os.path.join(PATH, "discriminator_A")) ) self.discriminator_B.load_state_dict( flow.load(os.path.join(PATH, "discriminator_B")) )
[ "oneflow.optim.Adam", "oneflow.tensor", "oneflow.mean", "oneflow.utils.data.DataLoader", "oneflow.cuda.is_available", "oneflow.abs", "oneflow.nn.MSELoss" ]
[((969, 998), 'numpy.load', 'np.load', (['logf0s_normalization'], {}), '(logf0s_normalization)\n', (976, 998), True, 'import numpy as np\n'), ((1269, 1296), 'numpy.load', 'np.load', (['mcep_normalization'], {}), '(mcep_normalization)\n', (1276, 1296), True, 'import numpy as np\n'), ((1866, 1883), 'oneflow.nn.MSELoss', 'flow.nn.MSELoss', ([], {}), '()\n', (1881, 1883), True, 'import oneflow as flow\n'), ((2563, 2630), 'oneflow.optim.Adam', 'flow.optim.Adam', (['g_params'], {'lr': 'self.generator_lr', 'betas': '(0.5, 0.999)'}), '(g_params, lr=self.generator_lr, betas=(0.5, 0.999))\n', (2578, 2630), True, 'import oneflow as flow\n'), ((2692, 2763), 'oneflow.optim.Adam', 'flow.optim.Adam', (['d_params'], {'lr': 'self.discriminator_lr', 'betas': '(0.5, 0.999)'}), '(d_params, lr=self.discriminator_lr, betas=(0.5, 0.999))\n', (2707, 2763), True, 'import oneflow as flow\n'), ((2890, 2938), 'os.makedirs', 'os.makedirs', (['self.modelCheckpoint'], {'exist_ok': '(True)'}), '(self.modelCheckpoint, exist_ok=True)\n', (2901, 2938), False, 'import os\n'), ((3074, 3119), 'os.makedirs', 'os.makedirs', (['self.output_A_dir'], {'exist_ok': '(True)'}), '(self.output_A_dir, exist_ok=True)\n', (3085, 3119), False, 'import os\n'), ((3218, 3263), 'os.makedirs', 'os.makedirs', (['self.output_B_dir'], {'exist_ok': '(True)'}), '(self.output_B_dir, exist_ok=True)\n', (3229, 3263), False, 'import os\n'), ((11748, 11771), 'os.listdir', 'os.listdir', (['infer_A_dir'], {}), '(infer_A_dir)\n', (11758, 11771), False, 'import os\n'), ((14437, 14465), 'os.listdir', 'os.listdir', (['validation_A_dir'], {}), '(validation_A_dir)\n', (14447, 14465), False, 'import os\n'), ((17123, 17151), 'os.listdir', 'os.listdir', (['validation_B_dir'], {}), '(validation_B_dir)\n', (17133, 17151), False, 'import os\n'), ((4262, 4273), 'time.time', 'time.time', ([], {}), '()\n', (4271, 4273), False, 'import time\n'), ((4471, 4550), 'utils.dataset.trainingDataset', 'trainingDataset', ([], {'datasetA': 'self.dataset_A', 'datasetB': 'self.dataset_B', 'n_frames': '(128)'}), '(datasetA=self.dataset_A, datasetB=self.dataset_B, n_frames=128)\n', (4486, 4550), False, 'from utils.dataset import trainingDataset\n'), ((4609, 4720), 'oneflow.utils.data.DataLoader', 'flow.utils.data.DataLoader', ([], {'dataset': 'dataset', 'batch_size': 'self.mini_batch_size', 'shuffle': '(True)', 'drop_last': '(False)'}), '(dataset=dataset, batch_size=self.mini_batch_size,\n shuffle=True, drop_last=False)\n', (4635, 4720), True, 'import oneflow as flow\n'), ((11796, 11827), 'os.path.join', 'os.path.join', (['infer_A_dir', 'file'], {}), '(infer_A_dir, file)\n', (11808, 11827), False, 'import os\n'), ((11849, 11900), 'librosa.load', 'librosa.load', (['filePath'], {'sr': 'sampling_rate', 'mono': '(True)'}), '(filePath, sr=sampling_rate, mono=True)\n', (11861, 11900), False, 'import librosa\n'), ((11919, 12011), 'utils.data_utils.wav_padding', 'preprocess.wav_padding', ([], {'wav': 'wav', 'sr': 'sampling_rate', 'frame_period': 'frame_period', 'multiple': '(4)'}), '(wav=wav, sr=sampling_rate, frame_period=frame_period,\n multiple=4)\n', (11941, 12011), True, 'import utils.data_utils as preprocess\n'), ((12073, 12158), 'utils.data_utils.world_decompose', 'preprocess.world_decompose', ([], {'wav': 'wav', 'fs': 'sampling_rate', 'frame_period': 'frame_period'}), '(wav=wav, fs=sampling_rate, frame_period=frame_period\n )\n', (12099, 12158), True, 'import utils.data_utils as preprocess\n'), ((12211, 12391), 'utils.data_utils.pitch_conversion', 'preprocess.pitch_conversion', ([], {'f0': 'f0', 'mean_log_src': 'self.log_f0s_mean_A', 'std_log_src': 'self.log_f0s_std_A', 'mean_log_target': 'self.log_f0s_mean_B', 'std_log_target': 'self.log_f0s_std_B'}), '(f0=f0, mean_log_src=self.log_f0s_mean_A,\n std_log_src=self.log_f0s_std_A, mean_log_target=self.log_f0s_mean_B,\n std_log_target=self.log_f0s_std_B)\n', (12238, 12391), True, 'import utils.data_utils as preprocess\n'), ((12502, 12581), 'utils.data_utils.world_encode_spectral_envelop', 'preprocess.world_encode_spectral_envelop', ([], {'sp': 'sp', 'fs': 'sampling_rate', 'dim': 'num_mcep'}), '(sp=sp, fs=sampling_rate, dim=num_mcep)\n', (12542, 12581), True, 'import utils.data_utils as preprocess\n'), ((12812, 12837), 'numpy.array', 'np.array', (['[coded_sp_norm]'], {}), '([coded_sp_norm])\n', (12820, 12837), True, 'import numpy as np\n'), ((12854, 12878), 'oneflow.cuda.is_available', 'flow.cuda.is_available', ([], {}), '()\n', (12876, 12878), True, 'import oneflow as flow\n'), ((13235, 13270), 'numpy.squeeze', 'np.squeeze', (['coded_sp_converted_norm'], {}), '(coded_sp_converted_norm)\n', (13245, 13270), True, 'import numpy as np\n'), ((13494, 13534), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['coded_sp_converted'], {}), '(coded_sp_converted)\n', (13514, 13534), True, 'import numpy as np\n'), ((13570, 13662), 'utils.data_utils.world_decode_spectral_envelop', 'preprocess.world_decode_spectral_envelop', ([], {'coded_sp': 'coded_sp_converted', 'fs': 'sampling_rate'}), '(coded_sp=coded_sp_converted, fs=\n sampling_rate)\n', (13610, 13662), True, 'import utils.data_utils as preprocess\n'), ((13718, 13858), 'utils.data_utils.world_speech_synthesis', 'preprocess.world_speech_synthesis', ([], {'f0': 'f0_converted', 'decoded_sp': 'decoded_sp_converted', 'ap': 'ap', 'fs': 'sampling_rate', 'frame_period': 'frame_period'}), '(f0=f0_converted, decoded_sp=\n decoded_sp_converted, ap=ap, fs=sampling_rate, frame_period=frame_period)\n', (13751, 13858), True, 'import utils.data_utils as preprocess\n'), ((14490, 14526), 'os.path.join', 'os.path.join', (['validation_A_dir', 'file'], {}), '(validation_A_dir, file)\n', (14502, 14526), False, 'import os\n'), ((14548, 14599), 'librosa.load', 'librosa.load', (['filePath'], {'sr': 'sampling_rate', 'mono': '(True)'}), '(filePath, sr=sampling_rate, mono=True)\n', (14560, 14599), False, 'import librosa\n'), ((14618, 14710), 'utils.data_utils.wav_padding', 'preprocess.wav_padding', ([], {'wav': 'wav', 'sr': 'sampling_rate', 'frame_period': 'frame_period', 'multiple': '(4)'}), '(wav=wav, sr=sampling_rate, frame_period=frame_period,\n multiple=4)\n', (14640, 14710), True, 'import utils.data_utils as preprocess\n'), ((14772, 14857), 'utils.data_utils.world_decompose', 'preprocess.world_decompose', ([], {'wav': 'wav', 'fs': 'sampling_rate', 'frame_period': 'frame_period'}), '(wav=wav, fs=sampling_rate, frame_period=frame_period\n )\n', (14798, 14857), True, 'import utils.data_utils as preprocess\n'), ((14910, 15090), 'utils.data_utils.pitch_conversion', 'preprocess.pitch_conversion', ([], {'f0': 'f0', 'mean_log_src': 'self.log_f0s_mean_A', 'std_log_src': 'self.log_f0s_std_A', 'mean_log_target': 'self.log_f0s_mean_B', 'std_log_target': 'self.log_f0s_std_B'}), '(f0=f0, mean_log_src=self.log_f0s_mean_A,\n std_log_src=self.log_f0s_std_A, mean_log_target=self.log_f0s_mean_B,\n std_log_target=self.log_f0s_std_B)\n', (14937, 15090), True, 'import utils.data_utils as preprocess\n'), ((15201, 15280), 'utils.data_utils.world_encode_spectral_envelop', 'preprocess.world_encode_spectral_envelop', ([], {'sp': 'sp', 'fs': 'sampling_rate', 'dim': 'num_mcep'}), '(sp=sp, fs=sampling_rate, dim=num_mcep)\n', (15241, 15280), True, 'import utils.data_utils as preprocess\n'), ((15511, 15536), 'numpy.array', 'np.array', (['[coded_sp_norm]'], {}), '([coded_sp_norm])\n', (15519, 15536), True, 'import numpy as np\n'), ((15553, 15577), 'oneflow.cuda.is_available', 'flow.cuda.is_available', ([], {}), '()\n', (15575, 15577), True, 'import oneflow as flow\n'), ((15934, 15969), 'numpy.squeeze', 'np.squeeze', (['coded_sp_converted_norm'], {}), '(coded_sp_converted_norm)\n', (15944, 15969), True, 'import numpy as np\n'), ((16193, 16233), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['coded_sp_converted'], {}), '(coded_sp_converted)\n', (16213, 16233), True, 'import numpy as np\n'), ((16269, 16361), 'utils.data_utils.world_decode_spectral_envelop', 'preprocess.world_decode_spectral_envelop', ([], {'coded_sp': 'coded_sp_converted', 'fs': 'sampling_rate'}), '(coded_sp=coded_sp_converted, fs=\n sampling_rate)\n', (16309, 16361), True, 'import utils.data_utils as preprocess\n'), ((16417, 16557), 'utils.data_utils.world_speech_synthesis', 'preprocess.world_speech_synthesis', ([], {'f0': 'f0_converted', 'decoded_sp': 'decoded_sp_converted', 'ap': 'ap', 'fs': 'sampling_rate', 'frame_period': 'frame_period'}), '(f0=f0_converted, decoded_sp=\n decoded_sp_converted, ap=ap, fs=sampling_rate, frame_period=frame_period)\n', (16450, 16557), True, 'import utils.data_utils as preprocess\n'), ((17176, 17212), 'os.path.join', 'os.path.join', (['validation_B_dir', 'file'], {}), '(validation_B_dir, file)\n', (17188, 17212), False, 'import os\n'), ((17234, 17285), 'librosa.load', 'librosa.load', (['filePath'], {'sr': 'sampling_rate', 'mono': '(True)'}), '(filePath, sr=sampling_rate, mono=True)\n', (17246, 17285), False, 'import librosa\n'), ((17304, 17396), 'utils.data_utils.wav_padding', 'preprocess.wav_padding', ([], {'wav': 'wav', 'sr': 'sampling_rate', 'frame_period': 'frame_period', 'multiple': '(4)'}), '(wav=wav, sr=sampling_rate, frame_period=frame_period,\n multiple=4)\n', (17326, 17396), True, 'import utils.data_utils as preprocess\n'), ((17458, 17543), 'utils.data_utils.world_decompose', 'preprocess.world_decompose', ([], {'wav': 'wav', 'fs': 'sampling_rate', 'frame_period': 'frame_period'}), '(wav=wav, fs=sampling_rate, frame_period=frame_period\n )\n', (17484, 17543), True, 'import utils.data_utils as preprocess\n'), ((17596, 17776), 'utils.data_utils.pitch_conversion', 'preprocess.pitch_conversion', ([], {'f0': 'f0', 'mean_log_src': 'self.log_f0s_mean_B', 'std_log_src': 'self.log_f0s_std_B', 'mean_log_target': 'self.log_f0s_mean_A', 'std_log_target': 'self.log_f0s_std_A'}), '(f0=f0, mean_log_src=self.log_f0s_mean_B,\n std_log_src=self.log_f0s_std_B, mean_log_target=self.log_f0s_mean_A,\n std_log_target=self.log_f0s_std_A)\n', (17623, 17776), True, 'import utils.data_utils as preprocess\n'), ((17887, 17966), 'utils.data_utils.world_encode_spectral_envelop', 'preprocess.world_encode_spectral_envelop', ([], {'sp': 'sp', 'fs': 'sampling_rate', 'dim': 'num_mcep'}), '(sp=sp, fs=sampling_rate, dim=num_mcep)\n', (17927, 17966), True, 'import utils.data_utils as preprocess\n'), ((18197, 18222), 'numpy.array', 'np.array', (['[coded_sp_norm]'], {}), '([coded_sp_norm])\n', (18205, 18222), True, 'import numpy as np\n'), ((18239, 18263), 'oneflow.cuda.is_available', 'flow.cuda.is_available', ([], {}), '()\n', (18261, 18263), True, 'import oneflow as flow\n'), ((18620, 18655), 'numpy.squeeze', 'np.squeeze', (['coded_sp_converted_norm'], {}), '(coded_sp_converted_norm)\n', (18630, 18655), True, 'import numpy as np\n'), ((18879, 18919), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['coded_sp_converted'], {}), '(coded_sp_converted)\n', (18899, 18919), True, 'import numpy as np\n'), ((18955, 19047), 'utils.data_utils.world_decode_spectral_envelop', 'preprocess.world_decode_spectral_envelop', ([], {'coded_sp': 'coded_sp_converted', 'fs': 'sampling_rate'}), '(coded_sp=coded_sp_converted, fs=\n sampling_rate)\n', (18995, 19047), True, 'import utils.data_utils as preprocess\n'), ((19103, 19243), 'utils.data_utils.world_speech_synthesis', 'preprocess.world_speech_synthesis', ([], {'f0': 'f0_converted', 'decoded_sp': 'decoded_sp_converted', 'ap': 'ap', 'fs': 'sampling_rate', 'frame_period': 'frame_period'}), '(f0=f0_converted, decoded_sp=\n decoded_sp_converted, ap=ap, fs=sampling_rate, frame_period=frame_period)\n', (19136, 19243), True, 'import utils.data_utils as preprocess\n'), ((19602, 19626), 'pickle.dump', 'pickle.dump', (['variable', 'f'], {}), '(variable, f)\n', (19613, 19626), False, 'import pickle\n'), ((19727, 19741), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (19738, 19741), False, 'import pickle\n'), ((20007, 20053), 'os.path.join', 'os.path.join', (['PATH', "('generator_A2B_%d' % epoch)"], {}), "(PATH, 'generator_A2B_%d' % epoch)\n", (20019, 20053), False, 'import os\n'), ((20141, 20187), 'os.path.join', 'os.path.join', (['PATH', "('generator_B2A_%d' % epoch)"], {}), "(PATH, 'generator_B2A_%d' % epoch)\n", (20153, 20187), False, 'import os\n'), ((20277, 20325), 'os.path.join', 'os.path.join', (['PATH', "('discriminator_A_%d' % epoch)"], {}), "(PATH, 'discriminator_A_%d' % epoch)\n", (20289, 20325), False, 'import os\n'), ((20415, 20463), 'os.path.join', 'os.path.join', (['PATH', "('discriminator_B_%d' % epoch)"], {}), "(PATH, 'discriminator_B_%d' % epoch)\n", (20427, 20463), False, 'import os\n'), ((872, 896), 'oneflow.cuda.is_available', 'flow.cuda.is_available', ([], {}), '()\n', (894, 896), True, 'import oneflow as flow\n'), ((1605, 1616), 'model.model.Generator', 'Generator', ([], {}), '()\n', (1614, 1616), False, 'from model.model import Generator, Discriminator\n'), ((1662, 1673), 'model.model.Generator', 'Generator', ([], {}), '()\n', (1671, 1673), False, 'from model.model import Generator, Discriminator\n'), ((1721, 1736), 'model.model.Discriminator', 'Discriminator', ([], {}), '()\n', (1734, 1736), False, 'from model.model import Generator, Discriminator\n'), ((1784, 1799), 'model.model.Discriminator', 'Discriminator', ([], {}), '()\n', (1797, 1799), False, 'from model.model import Generator, Discriminator\n'), ((6533, 6563), 'oneflow.mean', 'flow.mean', (['((1 - d_fake_B) ** 2)'], {}), '((1 - d_fake_B) ** 2)\n', (6542, 6563), True, 'import oneflow as flow\n'), ((6601, 6631), 'oneflow.mean', 'flow.mean', (['((1 - d_fake_A) ** 2)'], {}), '((1 - d_fake_A) ** 2)\n', (6610, 6631), True, 'import oneflow as flow\n'), ((7965, 7995), 'oneflow.mean', 'flow.mean', (['((1 - d_real_A) ** 2)'], {}), '((1 - d_real_A) ** 2)\n', (7974, 7995), True, 'import oneflow as flow\n'), ((8028, 8058), 'oneflow.mean', 'flow.mean', (['((0 - d_fake_A) ** 2)'], {}), '((0 - d_fake_A) ** 2)\n', (8037, 8058), True, 'import oneflow as flow\n'), ((8157, 8187), 'oneflow.mean', 'flow.mean', (['((1 - d_real_B) ** 2)'], {}), '((1 - d_real_B) ** 2)\n', (8166, 8187), True, 'import oneflow as flow\n'), ((8220, 8250), 'oneflow.mean', 'flow.mean', (['((0 - d_fake_B) ** 2)'], {}), '((0 - d_fake_B) ** 2)\n', (8229, 8250), True, 'import oneflow as flow\n'), ((8402, 8434), 'oneflow.mean', 'flow.mean', (['((0 - d_cycled_A) ** 2)'], {}), '((0 - d_cycled_A) ** 2)\n', (8411, 8434), True, 'import oneflow as flow\n'), ((8469, 8501), 'oneflow.mean', 'flow.mean', (['((0 - d_cycled_B) ** 2)'], {}), '((0 - d_cycled_B) ** 2)\n', (8478, 8501), True, 'import oneflow as flow\n'), ((9848, 9859), 'time.time', 'time.time', ([], {}), '()\n', (9857, 9859), False, 'import time\n'), ((10980, 10991), 'time.time', 'time.time', ([], {}), '()\n', (10989, 10991), False, 'import time\n'), ((11118, 11129), 'time.time', 'time.time', ([], {}), '()\n', (11127, 11129), False, 'import time\n'), ((20573, 20608), 'os.path.join', 'os.path.join', (['PATH', '"""generator_A2B"""'], {}), "(PATH, 'generator_A2B')\n", (20585, 20608), False, 'import os\n'), ((20686, 20721), 'os.path.join', 'os.path.join', (['PATH', '"""generator_B2A"""'], {}), "(PATH, 'generator_B2A')\n", (20698, 20721), False, 'import os\n'), ((20801, 20838), 'os.path.join', 'os.path.join', (['PATH', '"""discriminator_A"""'], {}), "(PATH, 'discriminator_A')\n", (20813, 20838), False, 'import os\n'), ((20918, 20955), 'os.path.join', 'os.path.join', (['PATH', '"""discriminator_B"""'], {}), "(PATH, 'discriminator_B')\n", (20930, 20955), False, 'import os\n'), ((16714, 16736), 'os.path.basename', 'os.path.basename', (['file'], {}), '(file)\n', (16730, 16736), False, 'import os\n'), ((19400, 19422), 'os.path.basename', 'os.path.basename', (['file'], {}), '(file)\n', (19416, 19422), False, 'import os\n'), ((6161, 6187), 'oneflow.abs', 'flow.abs', (['(real_A - cycle_A)'], {}), '(real_A - cycle_A)\n', (6169, 6187), True, 'import oneflow as flow\n'), ((6222, 6248), 'oneflow.abs', 'flow.abs', (['(real_B - cycle_B)'], {}), '(real_B - cycle_B)\n', (6230, 6248), True, 'import oneflow as flow\n'), ((6350, 6379), 'oneflow.abs', 'flow.abs', (['(real_A - identity_A)'], {}), '(real_A - identity_A)\n', (6358, 6379), True, 'import oneflow as flow\n'), ((6414, 6443), 'oneflow.abs', 'flow.abs', (['(real_B - identity_B)'], {}), '(real_B - identity_B)\n', (6422, 6443), True, 'import oneflow as flow\n'), ((13004, 13030), 'oneflow.tensor', 'flow.tensor', (['coded_sp_norm'], {}), '(coded_sp_norm)\n', (13015, 13030), True, 'import oneflow as flow\n'), ((14028, 14050), 'os.path.basename', 'os.path.basename', (['file'], {}), '(file)\n', (14044, 14050), False, 'import os\n'), ((15703, 15729), 'oneflow.tensor', 'flow.tensor', (['coded_sp_norm'], {}), '(coded_sp_norm)\n', (15714, 15729), True, 'import oneflow as flow\n'), ((18389, 18415), 'oneflow.tensor', 'flow.tensor', (['coded_sp_norm'], {}), '(coded_sp_norm)\n', (18400, 18415), True, 'import oneflow as flow\n'), ((12912, 12938), 'oneflow.tensor', 'flow.tensor', (['coded_sp_norm'], {}), '(coded_sp_norm)\n', (12923, 12938), True, 'import oneflow as flow\n'), ((15611, 15637), 'oneflow.tensor', 'flow.tensor', (['coded_sp_norm'], {}), '(coded_sp_norm)\n', (15622, 15637), True, 'import oneflow as flow\n'), ((18297, 18323), 'oneflow.tensor', 'flow.tensor', (['coded_sp_norm'], {}), '(coded_sp_norm)\n', (18308, 18323), True, 'import oneflow as flow\n')]
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import oneflow from oneflow.framework.docstr.utils import add_docstr add_docstr( oneflow.tensor, r""" Constructs a tensor with data, return a consistent tensor if placement and sbp are in kwargs, otherwise return a local tensor. Arguments: data: Initial data for the tensor. Can be a list, tuple, NumPy ndarray, scalar or tensor. Keyword Arguments: dtype (oneflow.dtype, optional) – the desired data type of returned tensor. Default: if None, infers data type from data. device (oneflow.device, optional): the desired device of returned tensor. If placement and sbp is None, uses the current cpu for the default tensor type. placement (oneflow.placement, optional): the desired placement of returned tensor. sbp (oneflow.sbp or tuple of oneflow.sbp, optional): the desired sbp of returned tensor. requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: False Noted: The Keyword Argument device is mutually exclusive with placement and sbp. Consistent tensor only can be constructed from tensor. For example: .. code-block:: python >>> import oneflow as flow >>> x = flow.tensor([1,2,3]) >>> x tensor([1, 2, 3], dtype=oneflow.int64) """, ) add_docstr( oneflow.Tensor.atan2, r""" See :func:`oneflow.atan2` """, ) add_docstr( oneflow.Tensor.expand_as, """ expand_as(other) -> Tensor Expand this tensor to the same size as :attr:`other`. ``self.expand_as(other)`` is equivalent to ``self.expand(other.size())``. Please see :meth:`~Tensor.expand` for more information about ``expand``. Args: other (:class:`oneflow.Tensor`): The result tensor has the same size as :attr:`other`. """, ) add_docstr( oneflow.Tensor.numel, """ See :func:`oneflow.numel` """, ) add_docstr( oneflow.Tensor.transpose, """ See :func:`oneflow.transpose` """, ) add_docstr( oneflow.Tensor.logical_not, """ logical_not() -> Tensor See :func:`oneflow.logical_not` """, ) add_docstr( oneflow.Tensor.std, """ See :func:`oneflow.std` """, ) add_docstr( oneflow.Tensor.var, """ See :func:`oneflow.var` """, ) add_docstr( oneflow.Tensor.squeeze, """ See :func:`oneflow.squeeze` """, ) add_docstr( oneflow.Tensor.negative, """ See :func:`oneflow.negative` """, ) add_docstr( oneflow.Tensor.neg, """ See :func:`oneflow.neg` """, ) add_docstr( oneflow.Tensor.unfold, """ The interface is consistent with PyTorch. The documentation is referenced from: https://pytorch.org/docs/stable/generated/torch.Tensor.unfold.html#torch.Tensor.unfold Returns a view of the original tensor which contains all slices of `size` size from `self` tensor in the dimension `dimension`. Step between two slices is given by `step`. If sizedim is the size of dimension `dimension` for `self`, the size of dimension dimension in the returned tensor will be (sizedim - size) / step + 1. An additional dimension of size `size` is appended in the returned tensor. Args: dimension (int): dimension in which unfolding happens size (int): the size of each slice that is unfolded step (int): the step between each slice For example: .. code-block:: python >>> import numpy as np >>> import oneflow as flow >>> x = flow.arange(1., 8) >>> x tensor([ 1., 2., 3., 4., 5., 6., 7.]) >>> x.unfold(0, 2, 1) tensor([[ 1., 2.], [ 2., 3.], [ 3., 4.], [ 4., 5.], [ 5., 6.], [ 6., 7.]]) >>> x.unfold(0, 2, 2) tensor([[ 1., 2.], [ 3., 4.], [ 5., 6.]]) """, ) add_docstr( oneflow.Tensor.matmul, """ See :func:`oneflow.matmul` """, ) add_docstr( oneflow.Tensor.narrow, """ See :func:`oneflow.narrow` """, ) add_docstr( oneflow.Tensor.unsqueeze, """ See :func:`oneflow.unsqueeze` """, ) add_docstr( oneflow.Tensor.permute, """ See :func:`oneflow.permute` """, ) add_docstr( oneflow.Tensor.to, """Performs Tensor dtype and/or device conversion. A flow.dtype and flow.device are inferred from the arguments of `input.to(*args, **kwargs)`. .. note:: If the ``input`` Tensor already has the correct :class:`flow.dtype` and :class:`flow.device`, then ``input`` is returned. Otherwise, the returned tensor is a copy of ``input`` with the desired. Args: input (oneflow.Tensor): An input tensor. *args (oneflow.Tensor or oneflow.device or oneflow.dtype): Positional arguments **kwargs (oneflow.device or oneflow.dtype) : Key-value arguments Returns: oneflow.Tensor: A Tensor. For example: .. code-block:: python >>> import numpy as np >>> import oneflow as flow >>> arr = np.random.randint(1, 9, size=(1, 2, 3, 4)) >>> input = flow.Tensor(arr) >>> output = input.to(dtype=flow.float32) >>> np.array_equal(arr.astype(np.float32), output.numpy()) True """, )
[ "oneflow.framework.docstr.utils.add_docstr" ]
[((660, 1959), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.tensor', '"""\n Constructs a tensor with data, return a consistent tensor if placement and sbp are in kwargs,\n otherwise return a local tensor. \n \n Arguments:\n data: Initial data for the tensor. Can be a list, tuple, NumPy ndarray, scalar or tensor.\n Keyword Arguments:\n dtype (oneflow.dtype, optional) – the desired data type of returned tensor.\n Default: if None, infers data type from data.\n device (oneflow.device, optional): the desired device of returned tensor. If placement\n and sbp is None, uses the current cpu for the default tensor type.\n placement (oneflow.placement, optional): the desired placement of returned tensor.\n sbp (oneflow.sbp or tuple of oneflow.sbp, optional): the desired sbp of returned tensor.\n requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: False\n\n Noted:\n The Keyword Argument device is mutually exclusive with placement and sbp.\n Consistent tensor only can be constructed from tensor.\n\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n \n >>> x = flow.tensor([1,2,3])\n >>> x\n tensor([1, 2, 3], dtype=oneflow.int64)\n\n """'], {}), '(oneflow.tensor,\n """\n Constructs a tensor with data, return a consistent tensor if placement and sbp are in kwargs,\n otherwise return a local tensor. \n \n Arguments:\n data: Initial data for the tensor. Can be a list, tuple, NumPy ndarray, scalar or tensor.\n Keyword Arguments:\n dtype (oneflow.dtype, optional) – the desired data type of returned tensor.\n Default: if None, infers data type from data.\n device (oneflow.device, optional): the desired device of returned tensor. If placement\n and sbp is None, uses the current cpu for the default tensor type.\n placement (oneflow.placement, optional): the desired placement of returned tensor.\n sbp (oneflow.sbp or tuple of oneflow.sbp, optional): the desired sbp of returned tensor.\n requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: False\n\n Noted:\n The Keyword Argument device is mutually exclusive with placement and sbp.\n Consistent tensor only can be constructed from tensor.\n\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n \n >>> x = flow.tensor([1,2,3])\n >>> x\n tensor([1, 2, 3], dtype=oneflow.int64)\n\n """\n )\n', (670, 1959), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((1964, 2039), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.atan2', '"""\n See :func:`oneflow.atan2`\n """'], {}), '(oneflow.Tensor.atan2, """\n See :func:`oneflow.atan2`\n """)\n', (1974, 2039), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((2053, 2475), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.expand_as', '"""\n expand_as(other) -> Tensor\n\n Expand this tensor to the same size as :attr:`other`.\n ``self.expand_as(other)`` is equivalent to ``self.expand(other.size())``.\n\n Please see :meth:`~Tensor.expand` for more information about ``expand``.\n\n Args:\n other (:class:`oneflow.Tensor`): The result tensor has the same size\n as :attr:`other`.\n """'], {}), '(oneflow.Tensor.expand_as,\n """\n expand_as(other) -> Tensor\n\n Expand this tensor to the same size as :attr:`other`.\n ``self.expand_as(other)`` is equivalent to ``self.expand(other.size())``.\n\n Please see :meth:`~Tensor.expand` for more information about ``expand``.\n\n Args:\n other (:class:`oneflow.Tensor`): The result tensor has the same size\n as :attr:`other`.\n """\n )\n', (2063, 2475), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((2479, 2554), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.numel', '"""\n See :func:`oneflow.numel`\n """'], {}), '(oneflow.Tensor.numel, """\n See :func:`oneflow.numel`\n """)\n', (2489, 2554), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((2567, 2654), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.transpose', '"""\n See :func:`oneflow.transpose`\n """'], {}), '(oneflow.Tensor.transpose,\n """\n See :func:`oneflow.transpose`\n """)\n', (2577, 2654), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((2663, 2787), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.logical_not', '"""\n logical_not() -> Tensor\n See :func:`oneflow.logical_not`\n """'], {}), '(oneflow.Tensor.logical_not,\n """\n logical_not() -> Tensor\n See :func:`oneflow.logical_not`\n """\n )\n', (2673, 2787), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((2791, 2862), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.std', '"""\n See :func:`oneflow.std`\n """'], {}), '(oneflow.Tensor.std, """\n See :func:`oneflow.std`\n """)\n', (2801, 2862), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((2875, 2946), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.var', '"""\n See :func:`oneflow.var`\n """'], {}), '(oneflow.Tensor.var, """\n See :func:`oneflow.var`\n """)\n', (2885, 2946), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((2959, 3038), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.squeeze', '"""\n See :func:`oneflow.squeeze`\n """'], {}), '(oneflow.Tensor.squeeze, """\n See :func:`oneflow.squeeze`\n """)\n', (2969, 3038), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((3051, 3136), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.negative', '"""\n See :func:`oneflow.negative`\n """'], {}), '(oneflow.Tensor.negative,\n """\n See :func:`oneflow.negative`\n """)\n', (3061, 3136), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((3145, 3216), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.neg', '"""\n See :func:`oneflow.neg`\n """'], {}), '(oneflow.Tensor.neg, """\n See :func:`oneflow.neg`\n """)\n', (3155, 3216), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((3229, 4596), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.unfold', '"""\n The interface is consistent with PyTorch.\n The documentation is referenced from: https://pytorch.org/docs/stable/generated/torch.Tensor.unfold.html#torch.Tensor.unfold\n\n Returns a view of the original tensor which contains all slices of `size` size from `self`\n tensor in the dimension `dimension`.\n\n Step between two slices is given by `step`.\n\n If sizedim is the size of dimension `dimension` for `self`, the size of dimension dimension in the\n returned tensor will be (sizedim - size) / step + 1.\n\n An additional dimension of size `size` is appended in the returned tensor.\n\n Args:\n dimension (int): dimension in which unfolding happens\n size (int): the size of each slice that is unfolded\n step (int): the step between each slice\n\n For example:\n\n .. code-block:: python\n\n >>> import numpy as np\n >>> import oneflow as flow\n\n >>> x = flow.arange(1., 8)\n >>> x\n tensor([ 1., 2., 3., 4., 5., 6., 7.])\n >>> x.unfold(0, 2, 1)\n tensor([[ 1., 2.],\n [ 2., 3.],\n [ 3., 4.],\n [ 4., 5.],\n [ 5., 6.],\n [ 6., 7.]])\n >>> x.unfold(0, 2, 2)\n tensor([[ 1., 2.],\n [ 3., 4.],\n [ 5., 6.]])\n """'], {}), '(oneflow.Tensor.unfold,\n """\n The interface is consistent with PyTorch.\n The documentation is referenced from: https://pytorch.org/docs/stable/generated/torch.Tensor.unfold.html#torch.Tensor.unfold\n\n Returns a view of the original tensor which contains all slices of `size` size from `self`\n tensor in the dimension `dimension`.\n\n Step between two slices is given by `step`.\n\n If sizedim is the size of dimension `dimension` for `self`, the size of dimension dimension in the\n returned tensor will be (sizedim - size) / step + 1.\n\n An additional dimension of size `size` is appended in the returned tensor.\n\n Args:\n dimension (int): dimension in which unfolding happens\n size (int): the size of each slice that is unfolded\n step (int): the step between each slice\n\n For example:\n\n .. code-block:: python\n\n >>> import numpy as np\n >>> import oneflow as flow\n\n >>> x = flow.arange(1., 8)\n >>> x\n tensor([ 1., 2., 3., 4., 5., 6., 7.])\n >>> x.unfold(0, 2, 1)\n tensor([[ 1., 2.],\n [ 2., 3.],\n [ 3., 4.],\n [ 4., 5.],\n [ 5., 6.],\n [ 6., 7.]])\n >>> x.unfold(0, 2, 2)\n tensor([[ 1., 2.],\n [ 3., 4.],\n [ 5., 6.]])\n """\n )\n', (3239, 4596), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4600, 4677), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.matmul', '"""\n See :func:`oneflow.matmul`\n """'], {}), '(oneflow.Tensor.matmul, """\n See :func:`oneflow.matmul`\n """)\n', (4610, 4677), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4690, 4767), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.narrow', '"""\n See :func:`oneflow.narrow`\n """'], {}), '(oneflow.Tensor.narrow, """\n See :func:`oneflow.narrow`\n """)\n', (4700, 4767), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4780, 4867), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.unsqueeze', '"""\n See :func:`oneflow.unsqueeze`\n """'], {}), '(oneflow.Tensor.unsqueeze,\n """\n See :func:`oneflow.unsqueeze`\n """)\n', (4790, 4867), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4876, 4955), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.permute', '"""\n See :func:`oneflow.permute`\n """'], {}), '(oneflow.Tensor.permute, """\n See :func:`oneflow.permute`\n """)\n', (4886, 4955), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4968, 6012), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.to', '"""Performs Tensor dtype and/or device conversion.\n A flow.dtype and flow.device are inferred from the arguments of `input.to(*args, **kwargs)`.\n\n .. note::\n If the ``input`` Tensor already\n has the correct :class:`flow.dtype` and :class:`flow.device`, then ``input`` is returned.\n Otherwise, the returned tensor is a copy of ``input`` with the desired.\n\n Args:\n input (oneflow.Tensor): An input tensor.\n *args (oneflow.Tensor or oneflow.device or oneflow.dtype): Positional arguments\n **kwargs (oneflow.device or oneflow.dtype) : Key-value arguments\n\n Returns:\n oneflow.Tensor: A Tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import numpy as np\n >>> import oneflow as flow\n\n >>> arr = np.random.randint(1, 9, size=(1, 2, 3, 4))\n >>> input = flow.Tensor(arr)\n >>> output = input.to(dtype=flow.float32)\n >>> np.array_equal(arr.astype(np.float32), output.numpy())\n True\n\n """'], {}), '(oneflow.Tensor.to,\n """Performs Tensor dtype and/or device conversion.\n A flow.dtype and flow.device are inferred from the arguments of `input.to(*args, **kwargs)`.\n\n .. note::\n If the ``input`` Tensor already\n has the correct :class:`flow.dtype` and :class:`flow.device`, then ``input`` is returned.\n Otherwise, the returned tensor is a copy of ``input`` with the desired.\n\n Args:\n input (oneflow.Tensor): An input tensor.\n *args (oneflow.Tensor or oneflow.device or oneflow.dtype): Positional arguments\n **kwargs (oneflow.device or oneflow.dtype) : Key-value arguments\n\n Returns:\n oneflow.Tensor: A Tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import numpy as np\n >>> import oneflow as flow\n\n >>> arr = np.random.randint(1, 9, size=(1, 2, 3, 4))\n >>> input = flow.Tensor(arr)\n >>> output = input.to(dtype=flow.float32)\n >>> np.array_equal(arr.astype(np.float32), output.numpy())\n True\n\n """\n )\n', (4978, 6012), False, 'from oneflow.framework.docstr.utils import add_docstr\n')]
import sys import oneflow as flow import oneflow.typing as tp import argparse import numpy as np import os import shutil import json from typing import Tuple from textcnn import TextCNN sys.path.append("../..") from text_classification.utils import pad_sequences, load_imdb_data parser = argparse.ArgumentParser() parser.add_argument('--ksize_list', type=str, default='2,3,4,5') parser.add_argument('--n_filters', type=int, default=100) parser.add_argument('--emb_dim', type=int, default=100) parser.add_argument('--dropout', type=float, default=0.5) parser.add_argument('--lr', type=float, default=1e-4) parser.add_argument('--sequence_length', type=int, default=150) parser.add_argument('--batch_size', type=int, default=32) parser.add_argument('--model_load_dir', type=str, default='') parser.add_argument('--model_save_every_n_iter', type=int, default=1000) parser.add_argument('--n_steps', type=int, default=10000) parser.add_argument('--n_epochs', type=int, default=15) parser.add_argument('--model_save_dir', type=str, default='./best_model') args = parser.parse_args() assert ',' in args.ksize_list args.ksize_list = [int(n) for n in args.ksize_list.split(',')] args.emb_num = 50000 args.n_classes = 2 model = TextCNN( args.emb_num, args.emb_dim, ksize_list=args.ksize_list, n_filters_list=[args.n_filters] * len(args.ksize_list), n_classes=args.n_classes, dropout=args.dropout) def get_train_config(): config = flow.function_config() config.default_data_type(flow.float) return config def get_eval_config(): config = flow.function_config() config.default_data_type(flow.float) return config @flow.global_function('train', get_train_config()) def train_job(text: tp.Numpy.Placeholder((args.batch_size, args.sequence_length), dtype=flow.int32), label: tp.Numpy.Placeholder((args.batch_size,), dtype=flow.int32) ) -> tp.Numpy: with flow.scope.placement("gpu", "0:0"): logits = model.get_logits(text, is_train=True) loss = flow.nn.sparse_softmax_cross_entropy_with_logits(label, logits, name="softmax_loss") lr_scheduler = flow.optimizer.PiecewiseConstantScheduler([], [args.lr]) flow.optimizer.Adam(lr_scheduler).minimize(loss) return loss @flow.global_function('predict', get_eval_config()) def eval_job(text: tp.Numpy.Placeholder((args.batch_size, args.sequence_length), dtype=flow.int32), label: tp.Numpy.Placeholder((args.batch_size,), dtype=flow.int32) ) -> Tuple[tp.Numpy, tp.Numpy]: with flow.scope.placement("gpu", "0:0"): logits = model.get_logits(text, is_train=False) loss = flow.nn.sparse_softmax_cross_entropy_with_logits(label, logits, name="softmax_loss") return label, logits def suffle_batch(data, label, batch_size): permu = np.random.permutation(len(data)) data, label = data[permu], label[permu] batch_n = len(data) // batch_size x_batch = np.array([data[i * batch_size:i * batch_size + batch_size] for i in range(batch_n)], dtype=np.int32) y_batch = np.array([label[i * batch_size:i * batch_size + batch_size] for i in range(batch_n)], dtype=np.int32) return x_batch, y_batch def acc(labels, logits, g): predictions = np.argmax(logits, 1) right_count = np.sum(predictions == labels) g["total"] += labels.shape[0] g["correct"] += right_count def train(checkpoint): path = '../imdb' (train_data, train_labels), (test_data, test_labels) = load_imdb_data(path) with open(os.path.join(path, 'word_index.json')) as f: word_index = json.load(f) word_index = {k: (v + 2) for k, v in word_index.items()} word_index["<PAD>"] = 0 word_index["<UNK>"] = 1 train_data = pad_sequences(train_data, value=word_index["<PAD>"], padding='post', maxlen=args.sequence_length) test_data = pad_sequences(test_data, value=word_index["<PAD>"], padding='post', maxlen=args.sequence_length) best_accuracy = 0.0 best_epoch = 0 for epoch in range(1, args.n_epochs + 1): print("[Epoch:{}]".format(epoch)) data, label = suffle_batch(train_data, train_labels, args.batch_size) for i, (texts, labels) in enumerate(zip(data, label)): loss = train_job(texts, labels).mean() if i % 20 == 0: print(loss) data, label = suffle_batch(test_data, test_labels, args.batch_size) g = {"correct": 0, "total": 0} for i, (texts, labels) in enumerate(zip(data, label)): labels, logits = eval_job(texts, labels) acc(labels, logits, g) accuracy = g["correct"] * 100 / g["total"] print("[Epoch:{0:d} ] accuracy: {1:.1f}%".format(epoch, accuracy)) if accuracy > best_accuracy: best_accuracy = accuracy best_epoch = epoch if not os.path.exists(args.model_save_dir): os.mkdir(args.model_save_dir) else: shutil.rmtree(args.model_save_dir) assert not os.path.exists(args.model_save_dir) os.mkdir(args.model_save_dir) print("Epoch:{} save best model.".format(best_epoch)) checkpoint.save(args.model_save_dir) print("Epoch:{} get best accuracy:{}".format(best_epoch, best_accuracy)) if __name__ == '__main__': checkpoint = flow.train.CheckPoint() checkpoint.init() train(checkpoint)
[ "oneflow.nn.sparse_softmax_cross_entropy_with_logits", "oneflow.optimizer.Adam", "oneflow.function_config", "oneflow.optimizer.PiecewiseConstantScheduler", "oneflow.train.CheckPoint", "oneflow.scope.placement", "oneflow.typing.Numpy.Placeholder" ]
[((188, 212), 'sys.path.append', 'sys.path.append', (['"""../.."""'], {}), "('../..')\n", (203, 212), False, 'import sys\n'), ((291, 316), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (314, 316), False, 'import argparse\n'), ((1447, 1469), 'oneflow.function_config', 'flow.function_config', ([], {}), '()\n', (1467, 1469), True, 'import oneflow as flow\n'), ((1567, 1589), 'oneflow.function_config', 'flow.function_config', ([], {}), '()\n', (1587, 1589), True, 'import oneflow as flow\n'), ((2131, 2187), 'oneflow.optimizer.PiecewiseConstantScheduler', 'flow.optimizer.PiecewiseConstantScheduler', (['[]', '[args.lr]'], {}), '([], [args.lr])\n', (2172, 2187), True, 'import oneflow as flow\n'), ((3244, 3264), 'numpy.argmax', 'np.argmax', (['logits', '(1)'], {}), '(logits, 1)\n', (3253, 3264), True, 'import numpy as np\n'), ((3283, 3312), 'numpy.sum', 'np.sum', (['(predictions == labels)'], {}), '(predictions == labels)\n', (3289, 3312), True, 'import numpy as np\n'), ((3484, 3504), 'text_classification.utils.load_imdb_data', 'load_imdb_data', (['path'], {}), '(path)\n', (3498, 3504), False, 'from text_classification.utils import pad_sequences, load_imdb_data\n'), ((3734, 3836), 'text_classification.utils.pad_sequences', 'pad_sequences', (['train_data'], {'value': "word_index['<PAD>']", 'padding': '"""post"""', 'maxlen': 'args.sequence_length'}), "(train_data, value=word_index['<PAD>'], padding='post', maxlen\n =args.sequence_length)\n", (3747, 3836), False, 'from text_classification.utils import pad_sequences, load_imdb_data\n'), ((3848, 3949), 'text_classification.utils.pad_sequences', 'pad_sequences', (['test_data'], {'value': "word_index['<PAD>']", 'padding': '"""post"""', 'maxlen': 'args.sequence_length'}), "(test_data, value=word_index['<PAD>'], padding='post', maxlen=\n args.sequence_length)\n", (3861, 3949), False, 'from text_classification.utils import pad_sequences, load_imdb_data\n'), ((5343, 5366), 'oneflow.train.CheckPoint', 'flow.train.CheckPoint', ([], {}), '()\n', (5364, 5366), True, 'import oneflow as flow\n'), ((1722, 1801), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(args.batch_size, args.sequence_length)'], {'dtype': 'flow.int32'}), '((args.batch_size, args.sequence_length), dtype=flow.int32)\n', (1742, 1801), True, 'import oneflow.typing as tp\n'), ((1824, 1882), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(args.batch_size,)'], {'dtype': 'flow.int32'}), '((args.batch_size,), dtype=flow.int32)\n', (1844, 1882), True, 'import oneflow.typing as tp\n'), ((1921, 1955), 'oneflow.scope.placement', 'flow.scope.placement', (['"""gpu"""', '"""0:0"""'], {}), "('gpu', '0:0')\n", (1941, 1955), True, 'import oneflow as flow\n'), ((2027, 2116), 'oneflow.nn.sparse_softmax_cross_entropy_with_logits', 'flow.nn.sparse_softmax_cross_entropy_with_logits', (['label', 'logits'], {'name': '"""softmax_loss"""'}), "(label, logits, name=\n 'softmax_loss')\n", (2075, 2116), True, 'import oneflow as flow\n'), ((2330, 2409), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(args.batch_size, args.sequence_length)'], {'dtype': 'flow.int32'}), '((args.batch_size, args.sequence_length), dtype=flow.int32)\n', (2350, 2409), True, 'import oneflow.typing as tp\n'), ((2431, 2489), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(args.batch_size,)'], {'dtype': 'flow.int32'}), '((args.batch_size,), dtype=flow.int32)\n', (2451, 2489), True, 'import oneflow.typing as tp\n'), ((2544, 2578), 'oneflow.scope.placement', 'flow.scope.placement', (['"""gpu"""', '"""0:0"""'], {}), "('gpu', '0:0')\n", (2564, 2578), True, 'import oneflow as flow\n'), ((2651, 2740), 'oneflow.nn.sparse_softmax_cross_entropy_with_logits', 'flow.nn.sparse_softmax_cross_entropy_with_logits', (['label', 'logits'], {'name': '"""softmax_loss"""'}), "(label, logits, name=\n 'softmax_loss')\n", (2699, 2740), True, 'import oneflow as flow\n'), ((3586, 3598), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3595, 3598), False, 'import json\n'), ((2192, 2225), 'oneflow.optimizer.Adam', 'flow.optimizer.Adam', (['lr_scheduler'], {}), '(lr_scheduler)\n', (2211, 2225), True, 'import oneflow as flow\n'), ((3520, 3557), 'os.path.join', 'os.path.join', (['path', '"""word_index.json"""'], {}), "(path, 'word_index.json')\n", (3532, 3557), False, 'import os\n'), ((4843, 4878), 'os.path.exists', 'os.path.exists', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (4857, 4878), False, 'import os\n'), ((4896, 4925), 'os.mkdir', 'os.mkdir', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (4904, 4925), False, 'import os\n'), ((4960, 4994), 'shutil.rmtree', 'shutil.rmtree', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (4973, 4994), False, 'import shutil\n'), ((5074, 5103), 'os.mkdir', 'os.mkdir', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (5082, 5103), False, 'import os\n'), ((5022, 5057), 'os.path.exists', 'os.path.exists', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (5036, 5057), False, 'import os\n')]
""" @author: <NAME> <<EMAIL>> """ import os import argparse import pickle import oneflow as flow from Wav2Letter.model import Wav2Letter from Wav2Letter.data import GoogleSpeechCommand from Wav2Letter.decoder import GreedyDecoder def get_args(): parser = argparse.ArgumentParser("""Wav2Letter train""") parser.add_argument("--mfcc_features", type=int, default=13) parser.add_argument("--datasets_path", type=str, default="speech_data") parser.add_argument("--output_path", type=str, default="save_models") parser.add_argument( "--int_encoder", type=str, default="./speech_data/int_encoder.pkl" ) args = parser.parse_args() return args def infer(opt): mfcc_features = opt.mfcc_features datasets_path = opt.datasets_path models_path = opt.output_path # load saved numpy arrays for google speech command gs = GoogleSpeechCommand() _inputs, _targets = gs.load_vectors(datasets_path) grapheme_count = gs.intencode.grapheme_count inputs = flow.Tensor(_inputs).to("cuda") targets = flow.tensor(_targets, dtype=flow.int).to("cuda") model = Wav2Letter(mfcc_features, grapheme_count) model.to("cuda") model.load_state_dict(flow.load(os.path.join(models_path, "model.pth"))) int_encoder = opt.int_encoder with open(int_encoder, "rb") as f: int_to_char = pickle.load(f)["index2char"] decoder = GreedyDecoder(int_to_char) inputs = inputs.transpose(1, 2) sample = inputs[-1000:] sample_target = targets[-1000:] log_probs = model(sample) output = decoder.decode(log_probs) pred_strings, output = decoder.convert_to_strings(output) sample_target_strings = decoder.convert_to_strings( sample_target, remove_repetitions=False, return_offsets=False ) wer = decoder.wer(sample_target_strings, pred_strings) print("wer", wer) if __name__ == "__main__": opt = get_args() infer(opt)
[ "oneflow.Tensor", "oneflow.tensor" ]
[((263, 306), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""Wav2Letter train"""'], {}), "('Wav2Letter train')\n", (286, 306), False, 'import argparse\n'), ((874, 895), 'Wav2Letter.data.GoogleSpeechCommand', 'GoogleSpeechCommand', ([], {}), '()\n', (893, 895), False, 'from Wav2Letter.data import GoogleSpeechCommand\n'), ((1122, 1163), 'Wav2Letter.model.Wav2Letter', 'Wav2Letter', (['mfcc_features', 'grapheme_count'], {}), '(mfcc_features, grapheme_count)\n', (1132, 1163), False, 'from Wav2Letter.model import Wav2Letter\n'), ((1402, 1428), 'Wav2Letter.decoder.GreedyDecoder', 'GreedyDecoder', (['int_to_char'], {}), '(int_to_char)\n', (1415, 1428), False, 'from Wav2Letter.decoder import GreedyDecoder\n'), ((1014, 1034), 'oneflow.Tensor', 'flow.Tensor', (['_inputs'], {}), '(_inputs)\n', (1025, 1034), True, 'import oneflow as flow\n'), ((1060, 1097), 'oneflow.tensor', 'flow.tensor', (['_targets'], {'dtype': 'flow.int'}), '(_targets, dtype=flow.int)\n', (1071, 1097), True, 'import oneflow as flow\n'), ((1221, 1259), 'os.path.join', 'os.path.join', (['models_path', '"""model.pth"""'], {}), "(models_path, 'model.pth')\n", (1233, 1259), False, 'import os\n'), ((1358, 1372), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1369, 1372), False, 'import pickle\n')]
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import oneflow from oneflow.framework.docstr.utils import add_docstr add_docstr( oneflow.expand, """ oneflow.expand(input, *sizes) -> Tensor, This operator expand the input tensor to a larger size. Passing -1 as the size for a dimension means not changing the size of that dimension. Tensor can be also expanded to a larger number of dimensions and the new ones will be appended at the front. For the new dimensions, the size cannot be set to -1. Args: input (oneflow.Tensor): The input Tensor. *sizes (oneflow.Size or int): The desired expanded size. Returns: oneflow.Tensor: The result Tensor. For example: .. code-block:: python >>> import oneflow as flow >>> import numpy as np >>> x = np.array([[[[0, 1]], ... [[2, 3]], ... [[4, 5]]]]).astype(np.int32) >>> input = flow.Tensor(x) >>> input.shape oneflow.Size([1, 3, 1, 2]) >>> out = input.expand(1, 3, 2, 2) >>> out.shape oneflow.Size([1, 3, 2, 2]) """, )
[ "oneflow.framework.docstr.utils.add_docstr" ]
[((660, 1698), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.expand', '"""\n oneflow.expand(input, *sizes) -> Tensor,\n\n This operator expand the input tensor to a larger size.\n\n Passing -1 as the size for a dimension means not changing the size of that dimension.\n\n Tensor can be also expanded to a larger number of dimensions and the new ones will be appended at the front.\n\n For the new dimensions, the size cannot be set to -1.\n\n Args:\n input (oneflow.Tensor): The input Tensor.\n *sizes (oneflow.Size or int): The desired expanded size.\n\n Returns:\n oneflow.Tensor: The result Tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n >>> x = np.array([[[[0, 1]],\n ... [[2, 3]],\n ... [[4, 5]]]]).astype(np.int32)\n >>> input = flow.Tensor(x)\n >>> input.shape\n oneflow.Size([1, 3, 1, 2])\n >>> out = input.expand(1, 3, 2, 2)\n >>> out.shape\n oneflow.Size([1, 3, 2, 2])\n\n """'], {}), '(oneflow.expand,\n """\n oneflow.expand(input, *sizes) -> Tensor,\n\n This operator expand the input tensor to a larger size.\n\n Passing -1 as the size for a dimension means not changing the size of that dimension.\n\n Tensor can be also expanded to a larger number of dimensions and the new ones will be appended at the front.\n\n For the new dimensions, the size cannot be set to -1.\n\n Args:\n input (oneflow.Tensor): The input Tensor.\n *sizes (oneflow.Size or int): The desired expanded size.\n\n Returns:\n oneflow.Tensor: The result Tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n >>> x = np.array([[[[0, 1]],\n ... [[2, 3]],\n ... [[4, 5]]]]).astype(np.int32)\n >>> input = flow.Tensor(x)\n >>> input.shape\n oneflow.Size([1, 3, 1, 2])\n >>> out = input.expand(1, 3, 2, 2)\n >>> out.shape\n oneflow.Size([1, 3, 2, 2])\n\n """\n )\n', (670, 1698), False, 'from oneflow.framework.docstr.utils import add_docstr\n')]
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import oneflow from oneflow.framework.docstr.utils import add_docstr add_docstr( oneflow.diag, """ If input is a vector (1-D tensor), then returns a 2-D square tensor with the elements of input as the diagonal. If input is a matrix (2-D tensor), then returns a 1-D tensor with diagonal elements of input. Args: input (Tensor): the input tensor. diagonal (Optional[int], 0): The diagonal to consider. If diagonal = 0, it is the main diagonal. If diagonal > 0, it is above the main diagonal. If diagonal < 0, it is below the main diagonal. Defaults to 0. Returns: oneflow.Tensor: the output Tensor. For example: .. code-block:: python >>> import oneflow as flow >>> import numpy as np >>> arr = np.array( ... [ ... [1.0, 2.0, 3.0], ... [4.0, 5.0, 6.0], ... [7.0, 8.0, 9.0], ... ] ... ) >>> input = flow.tensor(arr, dtype=flow.float32) >>> flow.diag(input) tensor([1., 5., 9.], dtype=oneflow.float32) """, ) add_docstr( oneflow.tril, """Returns the lower triangular part of a matrix (2-D tensor) or batch of matrices input along the specified diagonal, the other elements of the result tensor out are set to 0. .. note:: if diagonal = 0, the diagonal of the returned tensor will be the main diagonal, if diagonal > 0, the diagonal of the returned tensor will be above the main diagonal, if diagonal < 0, the diagonal of the returned tensor will be below the main diagonal. Args: input (Tensor): the input tensor. diagonal (int, optional): the diagonal to specify. For example: .. code-block:: python >>> import oneflow as flow >>> import numpy as np >>> x = flow.tensor(np.ones(shape=(3, 3)).astype(np.float32)) >>> flow.tril(x) tensor([[1., 0., 0.], [1., 1., 0.], [1., 1., 1.]], dtype=oneflow.float32) """, ) add_docstr( oneflow.triu, """Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices input, the other elements of the result tensor out are set to 0. Args: input (Tensor): the input tensor. diagonal (int, optional): the diagonal to consider For example: .. code-block:: python >>> import oneflow as flow >>> import numpy as np >>> x = flow.tensor(np.ones(shape=(3, 3)).astype(np.float32)) >>> flow.triu(x) tensor([[1., 1., 1.], [0., 1., 1.], [0., 0., 1.]], dtype=oneflow.float32) """, ) add_docstr( oneflow.argmax, """The op computes the index with the largest value of a Tensor at specified axis. Args: input (oneflow.Tensor): Input Tensor dim (int, optional): dimension to be calculated. Defaults to the last dim (-1) keepdim (bool optional): whether the output tensor has dim retained or not. Ignored if dim=None. Returns: oneflow.Tensor: A Tensor(dtype=int64) contains the index with the largest value of `input` For example: .. code-block:: python >>> import oneflow as flow >>> input = flow.tensor([[1, 3, 8, 7, 2], ... [1, 9, 4, 3, 2]], dtype=flow.float32) >>> output = flow.argmax(input) >>> output tensor(6, dtype=oneflow.int64) >>> output = flow.argmax(input, dim=1) >>> output tensor([2, 1], dtype=oneflow.int64) """, ) add_docstr( oneflow.argmin, """The op computes the index with the largest value of a Tensor at specified axis. Args: input (oneflow.Tensor): Input Tensor dim (int, optional): dimension to be calculated. Defaults to the last dim (-1) keepdim (bool optional): whether the output tensor has dim retained or not. Ignored if dim=None. Returns: oneflow.Tensor: A Tensor(dtype=int64) contains the index with the largest value of `input` For example: .. code-block:: python >>> import oneflow as flow >>> input = flow.tensor([[4, 3, 1, 0, 2], ... [5, 9, 7, 6, 8]], dtype=flow.float32) >>> output = flow.argmin(input) >>> output tensor(3, dtype=oneflow.int64) >>> output = flow.argmin(input, dim=1) >>> output tensor([3, 0], dtype=oneflow.int64) """, ) add_docstr( oneflow.batch_gather, """Gather the element in batch dims. Args: in (Tensor): the input tensor. indices (Tensor): the indices tensor, its dtype must be int32/64. For example: Example 1: .. code-block:: python >>> import oneflow as flow >>> import numpy as np >>> x = flow.Tensor(np.array([[1, 2, 3], ... [4, 5, 6]])) >>> indices = flow.tensor(np.array([1, 0]).astype(np.int64)) >>> out = flow.batch_gather(x, indices) tensor([[4., 5., 6.], [1., 2., 3.]], dtype=oneflow.float32) Example 2: .. code-block:: python >>> import oneflow as flow >>> import numpy as np >>> x = flow.Tensor(np.array([[[1, 2, 3], [4, 5, 6]], ... [[1, 2, 3], [4, 5, 6]]])) >>> indices = flow.tensor(np.array([[1, 0], ... [0, 1]]).astype(np.int64)) >>> out = flow.batch_gather(x, indices) tensor([[[4., 5., 6.], [1., 2., 3.]], [[1., 2., 3.], [4., 5., 6.]]], dtype=oneflow.float32) """, ) add_docstr( oneflow._C.transpose, """Returns a tensor that is a transposed version of input. The given dimensions dim0 and dim1 are swapped. The resulting out tensor shares its underlying storage with the input tensor, so changing the content of one would change the content of the other. Args: input (oneflow.Tensor): The input tensor. dim0 (int): the first dimension to be transposed. dim1 (int): the second dimension to be transposed. Returns: Tensor: A transposed tensor. For example: .. code-block:: python >>> import numpy as np >>> import oneflow as flow >>> input = flow.tensor(np.random.randn(2, 6, 5, 3), dtype=flow.float32) >>> out = flow.transpose(input, 0, 1).shape >>> out oneflow.Size([6, 2, 5, 3]) """, )
[ "oneflow.framework.docstr.utils.add_docstr" ]
[((660, 1701), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.diag', '"""\n If input is a vector (1-D tensor), then returns a 2-D square tensor with the elements of input as the diagonal.\n If input is a matrix (2-D tensor), then returns a 1-D tensor with diagonal elements of input.\n\n Args:\n input (Tensor): the input tensor.\n diagonal (Optional[int], 0): The diagonal to consider. \n If diagonal = 0, it is the main diagonal. If diagonal > 0, it is above the main diagonal. If diagonal < 0, it is below the main diagonal. Defaults to 0.\n \n Returns:\n oneflow.Tensor: the output Tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n >>> arr = np.array(\n ... [\n ... [1.0, 2.0, 3.0],\n ... [4.0, 5.0, 6.0],\n ... [7.0, 8.0, 9.0],\n ... ]\n ... )\n\n >>> input = flow.tensor(arr, dtype=flow.float32)\n >>> flow.diag(input)\n tensor([1., 5., 9.], dtype=oneflow.float32)\n """'], {}), '(oneflow.diag,\n """\n If input is a vector (1-D tensor), then returns a 2-D square tensor with the elements of input as the diagonal.\n If input is a matrix (2-D tensor), then returns a 1-D tensor with diagonal elements of input.\n\n Args:\n input (Tensor): the input tensor.\n diagonal (Optional[int], 0): The diagonal to consider. \n If diagonal = 0, it is the main diagonal. If diagonal > 0, it is above the main diagonal. If diagonal < 0, it is below the main diagonal. Defaults to 0.\n \n Returns:\n oneflow.Tensor: the output Tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n >>> arr = np.array(\n ... [\n ... [1.0, 2.0, 3.0],\n ... [4.0, 5.0, 6.0],\n ... [7.0, 8.0, 9.0],\n ... ]\n ... )\n\n >>> input = flow.tensor(arr, dtype=flow.float32)\n >>> flow.diag(input)\n tensor([1., 5., 9.], dtype=oneflow.float32)\n """\n )\n', (670, 1701), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((1705, 2663), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.tril', '"""Returns the lower triangular part of a matrix (2-D tensor) or batch of matrices input along the specified diagonal, \n the other elements of the result tensor out are set to 0.\n \n .. note::\n if diagonal = 0, the diagonal of the returned tensor will be the main diagonal,\n if diagonal > 0, the diagonal of the returned tensor will be above the main diagonal, \n if diagonal < 0, the diagonal of the returned tensor will be below the main diagonal.\n\n Args:\n input (Tensor): the input tensor. \n diagonal (int, optional): the diagonal to specify. \n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n\n >>> x = flow.tensor(np.ones(shape=(3, 3)).astype(np.float32))\n >>> flow.tril(x)\n tensor([[1., 0., 0.],\n [1., 1., 0.],\n [1., 1., 1.]], dtype=oneflow.float32)\n\n """'], {}), '(oneflow.tril,\n """Returns the lower triangular part of a matrix (2-D tensor) or batch of matrices input along the specified diagonal, \n the other elements of the result tensor out are set to 0.\n \n .. note::\n if diagonal = 0, the diagonal of the returned tensor will be the main diagonal,\n if diagonal > 0, the diagonal of the returned tensor will be above the main diagonal, \n if diagonal < 0, the diagonal of the returned tensor will be below the main diagonal.\n\n Args:\n input (Tensor): the input tensor. \n diagonal (int, optional): the diagonal to specify. \n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n\n >>> x = flow.tensor(np.ones(shape=(3, 3)).astype(np.float32))\n >>> flow.tril(x)\n tensor([[1., 0., 0.],\n [1., 1., 0.],\n [1., 1., 1.]], dtype=oneflow.float32)\n\n """\n )\n', (1715, 2663), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((2667, 3311), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.triu', '"""Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices input, \n the other elements of the result tensor out are set to 0.\n \n Args:\n input (Tensor): the input tensor. \n diagonal (int, optional): the diagonal to consider\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n \n >>> x = flow.tensor(np.ones(shape=(3, 3)).astype(np.float32))\n >>> flow.triu(x)\n tensor([[1., 1., 1.],\n [0., 1., 1.],\n [0., 0., 1.]], dtype=oneflow.float32)\n\n """'], {}), '(oneflow.triu,\n """Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices input, \n the other elements of the result tensor out are set to 0.\n \n Args:\n input (Tensor): the input tensor. \n diagonal (int, optional): the diagonal to consider\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n \n >>> x = flow.tensor(np.ones(shape=(3, 3)).astype(np.float32))\n >>> flow.triu(x)\n tensor([[1., 1., 1.],\n [0., 1., 1.],\n [0., 0., 1.]], dtype=oneflow.float32)\n\n """\n )\n', (2677, 3311), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((3315, 4215), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.argmax', '"""The op computes the index with the largest value of a Tensor at specified axis.\n\n Args:\n input (oneflow.Tensor): Input Tensor\n dim (int, optional): dimension to be calculated. Defaults to the last dim (-1)\n keepdim (bool optional): whether the output tensor has dim retained or not. Ignored if dim=None.\n\n Returns:\n oneflow.Tensor: A Tensor(dtype=int64) contains the index with the largest value of `input`\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n \n >>> input = flow.tensor([[1, 3, 8, 7, 2],\n ... [1, 9, 4, 3, 2]], dtype=flow.float32)\n >>> output = flow.argmax(input)\n >>> output\n tensor(6, dtype=oneflow.int64)\n >>> output = flow.argmax(input, dim=1)\n >>> output\n tensor([2, 1], dtype=oneflow.int64)\n\n """'], {}), '(oneflow.argmax,\n """The op computes the index with the largest value of a Tensor at specified axis.\n\n Args:\n input (oneflow.Tensor): Input Tensor\n dim (int, optional): dimension to be calculated. Defaults to the last dim (-1)\n keepdim (bool optional): whether the output tensor has dim retained or not. Ignored if dim=None.\n\n Returns:\n oneflow.Tensor: A Tensor(dtype=int64) contains the index with the largest value of `input`\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n \n >>> input = flow.tensor([[1, 3, 8, 7, 2],\n ... [1, 9, 4, 3, 2]], dtype=flow.float32)\n >>> output = flow.argmax(input)\n >>> output\n tensor(6, dtype=oneflow.int64)\n >>> output = flow.argmax(input, dim=1)\n >>> output\n tensor([2, 1], dtype=oneflow.int64)\n\n """\n )\n', (3325, 4215), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4219, 5119), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.argmin', '"""The op computes the index with the largest value of a Tensor at specified axis.\n\n Args:\n input (oneflow.Tensor): Input Tensor\n dim (int, optional): dimension to be calculated. Defaults to the last dim (-1)\n keepdim (bool optional): whether the output tensor has dim retained or not. Ignored if dim=None.\n\n Returns:\n oneflow.Tensor: A Tensor(dtype=int64) contains the index with the largest value of `input`\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n \n >>> input = flow.tensor([[4, 3, 1, 0, 2],\n ... [5, 9, 7, 6, 8]], dtype=flow.float32)\n >>> output = flow.argmin(input)\n >>> output\n tensor(3, dtype=oneflow.int64)\n >>> output = flow.argmin(input, dim=1)\n >>> output\n tensor([3, 0], dtype=oneflow.int64)\n\n """'], {}), '(oneflow.argmin,\n """The op computes the index with the largest value of a Tensor at specified axis.\n\n Args:\n input (oneflow.Tensor): Input Tensor\n dim (int, optional): dimension to be calculated. Defaults to the last dim (-1)\n keepdim (bool optional): whether the output tensor has dim retained or not. Ignored if dim=None.\n\n Returns:\n oneflow.Tensor: A Tensor(dtype=int64) contains the index with the largest value of `input`\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n \n >>> input = flow.tensor([[4, 3, 1, 0, 2],\n ... [5, 9, 7, 6, 8]], dtype=flow.float32)\n >>> output = flow.argmin(input)\n >>> output\n tensor(3, dtype=oneflow.int64)\n >>> output = flow.argmin(input, dim=1)\n >>> output\n tensor([3, 0], dtype=oneflow.int64)\n\n """\n )\n', (4229, 5119), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((5123, 6343), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.batch_gather', '"""Gather the element in batch dims. \n \n Args:\n in (Tensor): the input tensor. \n indices (Tensor): the indices tensor, its dtype must be int32/64. \n\n For example:\n\n Example 1: \n\n .. code-block:: python\n\n >>> import oneflow as flow \n >>> import numpy as np \n\n >>> x = flow.Tensor(np.array([[1, 2, 3], \n ... [4, 5, 6]]))\n >>> indices = flow.tensor(np.array([1, 0]).astype(np.int64))\n >>> out = flow.batch_gather(x, indices)\n\n tensor([[4., 5., 6.],\n [1., 2., 3.]], dtype=oneflow.float32)\n\n Example 2: \n\n .. code-block:: python\n\n >>> import oneflow as flow \n >>> import numpy as np \n\n >>> x = flow.Tensor(np.array([[[1, 2, 3], [4, 5, 6]], \n ... [[1, 2, 3], [4, 5, 6]]]))\n >>> indices = flow.tensor(np.array([[1, 0], \n ... [0, 1]]).astype(np.int64))\n >>> out = flow.batch_gather(x, indices)\n\n tensor([[[4., 5., 6.],\n [1., 2., 3.]],\n [[1., 2., 3.],\n [4., 5., 6.]]], dtype=oneflow.float32)\n\n """'], {}), '(oneflow.batch_gather,\n """Gather the element in batch dims. \n \n Args:\n in (Tensor): the input tensor. \n indices (Tensor): the indices tensor, its dtype must be int32/64. \n\n For example:\n\n Example 1: \n\n .. code-block:: python\n\n >>> import oneflow as flow \n >>> import numpy as np \n\n >>> x = flow.Tensor(np.array([[1, 2, 3], \n ... [4, 5, 6]]))\n >>> indices = flow.tensor(np.array([1, 0]).astype(np.int64))\n >>> out = flow.batch_gather(x, indices)\n\n tensor([[4., 5., 6.],\n [1., 2., 3.]], dtype=oneflow.float32)\n\n Example 2: \n\n .. code-block:: python\n\n >>> import oneflow as flow \n >>> import numpy as np \n\n >>> x = flow.Tensor(np.array([[[1, 2, 3], [4, 5, 6]], \n ... [[1, 2, 3], [4, 5, 6]]]))\n >>> indices = flow.tensor(np.array([[1, 0], \n ... [0, 1]]).astype(np.int64))\n >>> out = flow.batch_gather(x, indices)\n\n tensor([[[4., 5., 6.],\n [1., 2., 3.]],\n [[1., 2., 3.],\n [4., 5., 6.]]], dtype=oneflow.float32)\n\n """\n )\n', (5133, 6343), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((6347, 7183), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow._C.transpose', '"""Returns a tensor that is a transposed version of input. The given dimensions dim0 and dim1 are swapped.\n\n The resulting out tensor shares its underlying storage with the input tensor, so changing the content of one would change the content of the other.\n\n Args:\n input (oneflow.Tensor): The input tensor.\n dim0 (int): the first dimension to be transposed.\n dim1 (int): the second dimension to be transposed.\n Returns:\n Tensor: A transposed tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import numpy as np\n >>> import oneflow as flow\n >>> input = flow.tensor(np.random.randn(2, 6, 5, 3), dtype=flow.float32)\n >>> out = flow.transpose(input, 0, 1).shape\n >>> out\n oneflow.Size([6, 2, 5, 3])\n\n """'], {}), '(oneflow._C.transpose,\n """Returns a tensor that is a transposed version of input. The given dimensions dim0 and dim1 are swapped.\n\n The resulting out tensor shares its underlying storage with the input tensor, so changing the content of one would change the content of the other.\n\n Args:\n input (oneflow.Tensor): The input tensor.\n dim0 (int): the first dimension to be transposed.\n dim1 (int): the second dimension to be transposed.\n Returns:\n Tensor: A transposed tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import numpy as np\n >>> import oneflow as flow\n >>> input = flow.tensor(np.random.randn(2, 6, 5, 3), dtype=flow.float32)\n >>> out = flow.transpose(input, 0, 1).shape\n >>> out\n oneflow.Size([6, 2, 5, 3])\n\n """\n )\n', (6357, 7183), False, 'from oneflow.framework.docstr.utils import add_docstr\n')]
import oneflow as flow from utils.dataset import * import random # Find letter index from all_letters, e.g. "a" = 0 def letterToIndex(letter): return all_letters.find(letter) # Just for demonstration, turn a letter into a <1 x n_letters> Tensor def letterToTensor(letter): # NOTE(<NAME>): oneflow does not provide `flow.zeros` # tensor = torch.zeros(1, n_letters) # tensor[0][letterToIndex(letter)] = 1 tensor = flow.Tensor(n_letters) flow.nn.init.zeros_(tensor) tensor[letterToIndex(letter)] = 1 return tensor.to("cuda") # Turn a line into a <line_length x 1 x n_letters>, # or an array of one-hot letter vectors def lineToTensor(line): # NOTE(<NAME>): oneflow does not provide `flow.zeros` # tensor = torch.zeros(len(line), 1, n_letters) # for li, letter in enumerate(line): # tensor[li][0][letterToIndex(letter)] = 1 tensor = flow.Tensor(len(line), 1, n_letters) flow.nn.init.zeros_(tensor) for li, letter in enumerate(line): # NOTE(<NAME>): oneflow Tensor does not support tensor[li][letterToIndex(letter)] = 1 tensor[li, 0, letterToIndex(letter)] = 1 return tensor.to("cuda") def randomChoice(l): return l[random.randint(0, len(l) - 1)] def randomTrainingExample(): category = randomChoice(all_categories) line = randomChoice(category_lines[category]) # category_tensor = torch.tensor([all_categories.index(category)], dtype=torch.long) category_tensor = flow.Tensor([all_categories.index(category)], dtype=flow.int64) line_tensor = lineToTensor(line) return category, line, category_tensor.to("cuda"), line_tensor.to("cuda")
[ "oneflow.nn.init.zeros_", "oneflow.Tensor" ]
[((437, 459), 'oneflow.Tensor', 'flow.Tensor', (['n_letters'], {}), '(n_letters)\n', (448, 459), True, 'import oneflow as flow\n'), ((464, 491), 'oneflow.nn.init.zeros_', 'flow.nn.init.zeros_', (['tensor'], {}), '(tensor)\n', (483, 491), True, 'import oneflow as flow\n'), ((933, 960), 'oneflow.nn.init.zeros_', 'flow.nn.init.zeros_', (['tensor'], {}), '(tensor)\n', (952, 960), True, 'import oneflow as flow\n')]
import argparse import os import numpy as np import time import pickle import oneflow as flow import oneflow.optim as optim from tqdm import tqdm from skimage.metrics import peak_signal_noise_ratio from skimage.metrics import structural_similarity from utils.of_data_utils import NumpyDataLoader, ValDatasetFromFolder from utils.of_loss import GeneratorLoss from models.of_model import Generator, Discriminator parser = argparse.ArgumentParser(description="Train Super Resolution Models") parser.add_argument("--data_dir", default="./data/VOC", type=str, help="data root") parser.add_argument("--hr_size", default=88, type=int, help="training images crop size") parser.add_argument("--gpu_ids", type=str, default="0") parser.add_argument( "--upscale_factor", default=4, type=int, choices=[2, 4, 8], help="super resolution upscale factor", ) parser.add_argument("--num_epochs", default=1, type=int, help="train epoch number") parser.add_argument( "--train_mode", default="GPU", type=str, choices=["GPU", "CPU"], help="using GPU or CPU", ) parser.add_argument("--batch_size", type=int, default=256, required=False) parser.add_argument("--load_checkpoint_G", type=str, default="", help="load checkpoint") parser.add_argument("--load_checkpoint_D", type=str, default="", help="load checkpoint") parser.add_argument( "--save_path", type=str, default="./srgan", help="save results root dir" ) parser.add_argument( "--vgg_path", type=str, default="./vgg_imagenet_pretrain_model/vgg16_oneflow_model", help="vgg pretrained weight path", ) parser.add_argument("--lr", type=float, default=0.0002, help="adam: learning rate") parser.add_argument( "--b1", type=float, default=0.5, help="adam: decay of first order momentum of gradient", ) parser.add_argument( "--b2", type=float, default=0.999, help="adam: decay of first order momentum of gradient", ) def to_numpy(x, mean=True): if mean: x = flow.mean(x) return x.numpy() def to_tensor(x, grad=True, dtype=flow.float32): if not isinstance(x, np.ndarray): x = np.array(x) return flow.Tensor(x, requires_grad=grad, dtype=dtype) def save_obj(obj, name): with open(name + ".pkl", "wb") as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) print("Save {} done.".format(name + ".pkl")) if __name__ == "__main__": opt = parser.parse_args() os.environ["CUDA_VISIBLE_DEVICES"] = opt.gpu_ids HR_SIZE = opt.hr_size UPSCALE_FACTOR = opt.upscale_factor NUM_EPOCHS = opt.num_epochs TRAIN_MODE = True if opt.train_mode == "GPU" else False lr_size = opt.hr_size // opt.upscale_factor modes = ["val", "train", "test"] train_data = NumpyDataLoader( dataset_root=opt.data_dir, mode=modes[1], hr_size=HR_SIZE, lr_size=lr_size, batch_size=opt.batch_size, ) val_data = ValDatasetFromFolder(opt.data_dir, mode=modes[0], upscale_factor=4) start_t = time.time() netG = Generator(UPSCALE_FACTOR) print("# generator parameters:", sum(param.numel() for param in netG.parameters())) netD = Discriminator() print( "# discriminator parameters:", sum(param.numel() for param in netD.parameters()) ) generator_criterion = GeneratorLoss(opt.vgg_path) bce = flow.nn.BCEWithLogitsLoss() end_t = time.time() print("init time : {}".format(end_t - start_t)) if TRAIN_MODE: netG.to("cuda") netD.to("cuda") generator_criterion.to("cuda") bce.to("cuda") if opt.load_checkpoint_G != "": netG.load_state_dict(flow.load(opt.load_checkpoint_G)) print("netG") if opt.load_checkpoint_D != "": netD.load_state_dict(flow.load(opt.load_checkpoint_D)) optimizerG = optim.Adam(netG.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) optimizerD = optim.Adam(netD.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) results = { "d_loss": [], "g_loss": [], "d_score": [], "g_score": [], "psnr": [], "ssim": [], } for epoch in range(0, NUM_EPOCHS): train_bar = tqdm(train_data) running_results = { "batch_sizes": 0, "d_loss": 0, "g_loss": 0, "d_score": 0, "g_score": 0, } netG.train() netD.train() for idx in range(len(train_data)): target, data = train_data[idx] batch_size = data.shape[0] running_results["batch_sizes"] += batch_size z = to_tensor(data, False) real_img = to_tensor(target, False) ############################ # (1) Update D network: maximize D(x)-1-D(G(z)) ########################### real_img = real_img.to("cuda") z = z.to("cuda") fake_img = netG(z) real_out = netD(real_img) fake_out = netD(fake_img.detach()) label1 = to_tensor( np.random.rand(batch_size, 1) * 0.25 + 0.85, False, dtype=flow.float32 ).to("cuda") label0 = to_tensor( np.random.rand(batch_size, 1) * 0.15, False, dtype=flow.float32 ).to("cuda") d_loss = bce(fake_out, label0) + bce(real_out, label1) d_loss.backward() optimizerD.step() optimizerD.zero_grad() ############################ # (2) Update G network: minimize 1-D(G(z)) + Perception Loss + Image Loss + TV Loss ########################### fake_img_0 = netG(z) fake_out_0 = netD(fake_img_0) g_loss = generator_criterion(fake_out_0, fake_img_0, real_img) g_loss.backward() optimizerG.step() optimizerG.zero_grad() fake_out = flow.mean(fake_out) real_out = flow.mean(fake_out) # loss for current batch before optimization running_results["g_loss"] += g_loss.numpy() * batch_size running_results["d_loss"] += d_loss.numpy() * batch_size running_results["d_score"] += real_out.numpy() * batch_size running_results["g_score"] += fake_out.numpy() * batch_size train_bar.set_description( desc="[%d/%d] Loss_D: %.4f Loss_G: %.4f D(x): %.4f D(G(z)): %.4f" % ( epoch, NUM_EPOCHS, running_results["d_loss"] / running_results["batch_sizes"], running_results["g_loss"] / running_results["batch_sizes"], running_results["d_score"] / running_results["batch_sizes"], running_results["g_score"] / running_results["batch_sizes"], ) ) netG.eval() out_path = os.path.join(opt.save_path, "SRF_" + str(UPSCALE_FACTOR)) if not os.path.exists(out_path): os.makedirs(out_path) with flow.no_grad(): val_bar = tqdm(val_data) valing_results = { "psnrs": 0, "ssims": 0, "psnr": 0, "ssim": 0, "batch_sizes": 0, } val_images = [] print("val data", len(val_data)) for idx in range(len(val_data)): val_hr, val_lr = val_data[idx] batch_size = val_lr.shape[0] valing_results["batch_sizes"] += batch_size lr = to_tensor(val_lr) hr = to_tensor(val_hr) lr = lr.to("cuda") hr = hr.to("cuda") sr = netG(lr) fake = sr[0].data * 255.0 fake = fake.squeeze(0).permute(1, 2, 0) fake = fake.numpy().astype(np.uint8) _img = hr[0].data * 255 _img = _img.squeeze(0).permute(1, 2, 0) _img = _img.numpy().astype(np.uint8) batch_psnr = peak_signal_noise_ratio(_img, fake) valing_results["psnrs"] += batch_psnr * batch_size valing_results["psnr"] = ( valing_results["psnrs"] / valing_results["batch_sizes"] ) batch_ssim = structural_similarity(_img, fake, multichannel=True) valing_results["ssims"] += batch_ssim * batch_size valing_results["ssim"] = ( valing_results["ssims"] / valing_results["batch_sizes"] ) val_bar.set_description( desc="[converting LR images to SR images] PSNR: %.4f dB SSIM: %.4f" % (valing_results["psnr"], valing_results["ssim"]) ) # save loss\scores\psnr\ssim results["d_loss"].append( running_results["d_loss"] / running_results["batch_sizes"] ) results["g_loss"].append( running_results["g_loss"] / running_results["batch_sizes"] ) results["d_score"].append( running_results["d_score"] / running_results["batch_sizes"] ) results["g_score"].append( running_results["g_score"] / running_results["batch_sizes"] ) results["psnr"].append(valing_results["psnr"]) results["ssim"].append(valing_results["ssim"]) # save model parameters flow.save( netG.state_dict(), os.path.join(opt.save_path, "netG_epoch_%d_%d" % (UPSCALE_FACTOR, epoch)), ) flow.save( netD.state_dict(), os.path.join(opt.save_path, "netD_epoch_%d_%d" % (UPSCALE_FACTOR, epoch)), ) save_obj(results, os.path.join(opt.save_path, "results"))
[ "oneflow.mean", "oneflow.no_grad", "oneflow.load", "oneflow.Tensor", "oneflow.nn.BCEWithLogitsLoss" ]
[((422, 490), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train Super Resolution Models"""'}), "(description='Train Super Resolution Models')\n", (445, 490), False, 'import argparse\n'), ((2149, 2196), 'oneflow.Tensor', 'flow.Tensor', (['x'], {'requires_grad': 'grad', 'dtype': 'dtype'}), '(x, requires_grad=grad, dtype=dtype)\n', (2160, 2196), True, 'import oneflow as flow\n'), ((2741, 2863), 'utils.of_data_utils.NumpyDataLoader', 'NumpyDataLoader', ([], {'dataset_root': 'opt.data_dir', 'mode': 'modes[1]', 'hr_size': 'HR_SIZE', 'lr_size': 'lr_size', 'batch_size': 'opt.batch_size'}), '(dataset_root=opt.data_dir, mode=modes[1], hr_size=HR_SIZE,\n lr_size=lr_size, batch_size=opt.batch_size)\n', (2756, 2863), False, 'from utils.of_data_utils import NumpyDataLoader, ValDatasetFromFolder\n'), ((2922, 2989), 'utils.of_data_utils.ValDatasetFromFolder', 'ValDatasetFromFolder', (['opt.data_dir'], {'mode': 'modes[0]', 'upscale_factor': '(4)'}), '(opt.data_dir, mode=modes[0], upscale_factor=4)\n', (2942, 2989), False, 'from utils.of_data_utils import NumpyDataLoader, ValDatasetFromFolder\n'), ((3004, 3015), 'time.time', 'time.time', ([], {}), '()\n', (3013, 3015), False, 'import time\n'), ((3028, 3053), 'models.of_model.Generator', 'Generator', (['UPSCALE_FACTOR'], {}), '(UPSCALE_FACTOR)\n', (3037, 3053), False, 'from models.of_model import Generator, Discriminator\n'), ((3153, 3168), 'models.of_model.Discriminator', 'Discriminator', ([], {}), '()\n', (3166, 3168), False, 'from models.of_model import Generator, Discriminator\n'), ((3302, 3329), 'utils.of_loss.GeneratorLoss', 'GeneratorLoss', (['opt.vgg_path'], {}), '(opt.vgg_path)\n', (3315, 3329), False, 'from utils.of_loss import GeneratorLoss\n'), ((3340, 3367), 'oneflow.nn.BCEWithLogitsLoss', 'flow.nn.BCEWithLogitsLoss', ([], {}), '()\n', (3365, 3367), True, 'import oneflow as flow\n'), ((3380, 3391), 'time.time', 'time.time', ([], {}), '()\n', (3389, 3391), False, 'import time\n'), ((1990, 2002), 'oneflow.mean', 'flow.mean', (['x'], {}), '(x)\n', (1999, 2002), True, 'import oneflow as flow\n'), ((2126, 2137), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2134, 2137), True, 'import numpy as np\n'), ((2273, 2317), 'pickle.dump', 'pickle.dump', (['obj', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(obj, f, pickle.HIGHEST_PROTOCOL)\n', (2284, 2317), False, 'import pickle\n'), ((4173, 4189), 'tqdm.tqdm', 'tqdm', (['train_data'], {}), '(train_data)\n', (4177, 4189), False, 'from tqdm import tqdm\n'), ((9496, 9569), 'os.path.join', 'os.path.join', (['opt.save_path', "('netG_epoch_%d_%d' % (UPSCALE_FACTOR, epoch))"], {}), "(opt.save_path, 'netG_epoch_%d_%d' % (UPSCALE_FACTOR, epoch))\n", (9508, 9569), False, 'import os\n'), ((9627, 9700), 'os.path.join', 'os.path.join', (['opt.save_path', "('netD_epoch_%d_%d' % (UPSCALE_FACTOR, epoch))"], {}), "(opt.save_path, 'netD_epoch_%d_%d' % (UPSCALE_FACTOR, epoch))\n", (9639, 9700), False, 'import os\n'), ((9730, 9768), 'os.path.join', 'os.path.join', (['opt.save_path', '"""results"""'], {}), "(opt.save_path, 'results')\n", (9742, 9768), False, 'import os\n'), ((3640, 3672), 'oneflow.load', 'flow.load', (['opt.load_checkpoint_G'], {}), '(opt.load_checkpoint_G)\n', (3649, 3672), True, 'import oneflow as flow\n'), ((3761, 3793), 'oneflow.load', 'flow.load', (['opt.load_checkpoint_D'], {}), '(opt.load_checkpoint_D)\n', (3770, 3793), True, 'import oneflow as flow\n'), ((5894, 5913), 'oneflow.mean', 'flow.mean', (['fake_out'], {}), '(fake_out)\n', (5903, 5913), True, 'import oneflow as flow\n'), ((5937, 5956), 'oneflow.mean', 'flow.mean', (['fake_out'], {}), '(fake_out)\n', (5946, 5956), True, 'import oneflow as flow\n'), ((6964, 6988), 'os.path.exists', 'os.path.exists', (['out_path'], {}), '(out_path)\n', (6978, 6988), False, 'import os\n'), ((7002, 7023), 'os.makedirs', 'os.makedirs', (['out_path'], {}), '(out_path)\n', (7013, 7023), False, 'import os\n'), ((7038, 7052), 'oneflow.no_grad', 'flow.no_grad', ([], {}), '()\n', (7050, 7052), True, 'import oneflow as flow\n'), ((7076, 7090), 'tqdm.tqdm', 'tqdm', (['val_data'], {}), '(val_data)\n', (7080, 7090), False, 'from tqdm import tqdm\n'), ((8060, 8095), 'skimage.metrics.peak_signal_noise_ratio', 'peak_signal_noise_ratio', (['_img', 'fake'], {}), '(_img, fake)\n', (8083, 8095), False, 'from skimage.metrics import peak_signal_noise_ratio\n'), ((8330, 8382), 'skimage.metrics.structural_similarity', 'structural_similarity', (['_img', 'fake'], {'multichannel': '(True)'}), '(_img, fake, multichannel=True)\n', (8351, 8382), False, 'from skimage.metrics import structural_similarity\n'), ((5194, 5223), 'numpy.random.rand', 'np.random.rand', (['batch_size', '(1)'], {}), '(batch_size, 1)\n', (5208, 5223), True, 'import numpy as np\n'), ((5050, 5079), 'numpy.random.rand', 'np.random.rand', (['batch_size', '(1)'], {}), '(batch_size, 1)\n', (5064, 5079), True, 'import numpy as np\n')]
README.md exists but content is empty.
Downloads last month
43