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')] |
"""
Copyright 2020 Tianshu AI Platform. 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 os
import math
import numpy as np
import sys
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(os.path.abspath(os.path.join(os.getcwd(), "./src")))
import oneflow as flow
import oneflow.typing as tp
from typing import Tuple, Any
from classifier import GlueBERT
from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig, getdirsize, \
remove_optimizer_params, remove_teacher_params
import config as configs
from sklearn.metrics import accuracy_score, matthews_corrcoef, precision_score, recall_score, f1_score
import argparse
import shutil
import tempfile
from knowledge_distill_util import BertForSequenceClassification, BertStudentForSequenceClassification, \
soft_cross_entropy, mseloss, layer_distill, att_distill, pred_distill
import time
import json
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Unsupported value encountered.')
parser = configs.get_parser()
parser.add_argument("--task_name", type=str, default='CoLA')
parser.add_argument("--teacher_model", default=None, type=str, help="The teacher model dir.")
parser.add_argument("--student_model", default=None, type=str, help="The student model dir.")
parser.add_argument("--total_model", default=None, type=str, help="The student model dir.")
parser.add_argument('--num_epochs', type=int, default=3, help='number of epochs')
parser.add_argument("--train_data_dir", type=str, default=None)
parser.add_argument("--train_data_prefix", type=str, default='train.of_record-')
parser.add_argument("--train_example_num", type=int, default=88614,
help="example number in dataset")
parser.add_argument("--batch_size_per_device", type=int, default=32)
parser.add_argument("--train_data_part_num", type=int, default=1,
help="data part number in dataset")
parser.add_argument("--eval_data_dir", type=str, default=None)
parser.add_argument("--eval_data_prefix", type=str, default='eval.of_record-')
parser.add_argument("--eval_example_num", type=int, default=10833,
help="example number in dataset")
parser.add_argument("--eval_batch_size_per_device", type=int, default=64)
parser.add_argument("--eval_data_part_num", type=int, default=1,
help="data part number in dataset")
parser.add_argument("--result_dir", type=str, default="", help="the save directory of results")
#
parser.add_argument("--student_num_hidden_layers", type=int, default=24)
parser.add_argument("--student_num_attention_heads", type=int, default=16)
parser.add_argument("--student_max_position_embeddings", type=int, default=512)
parser.add_argument("--student_type_vocab_size", type=int, default=2)
parser.add_argument("--student_vocab_size", type=int, default=30522)
parser.add_argument("--student_attention_probs_dropout_prob", type=float, default=0.1)
parser.add_argument("--student_hidden_dropout_prob", type=float, default=0.1)
parser.add_argument("--student_hidden_size_per_head", type=int, default=64)
parser.add_argument("--student_hidden_size", type=int, default=768)
parser.add_argument("--teacher_num_hidden_layers", type=int, default=24)
parser.add_argument("--teacher_num_attention_heads", type=int, default=16)
parser.add_argument("--teacher_max_position_embeddings", type=int, default=512)
parser.add_argument("--teacher_type_vocab_size", type=int, default=2)
parser.add_argument("--teacher_vocab_size", type=int, default=30522)
parser.add_argument("--teacher_attention_probs_dropout_prob", type=float, default=0.1)
parser.add_argument("--teacher_hidden_dropout_prob", type=float, default=0.1)
parser.add_argument("--teacher_hidden_size_per_head", type=int, default=64)
parser.add_argument("--teacher_hidden_size", type=int, default=768)
parser.add_argument("--kd_alpha", type=float, default=0.9)
parser.add_argument('--temperature', type=float, default=1.)
parser.add_argument('--aug_train', type=str2bool, nargs='?', const=False, help='using augmented training set?')
parser.add_argument('--serve_for_online', type=str2bool, nargs='?', const=False,
help='if serve for online, then after training, will delete the teacher params and optimizer parmas from model_save_dir')
args = parser.parse_args()
task_name = args.task_name.lower()
if args.aug_train:
args.train_data_dir = args.train_data_dir.replace('train', 'train_aug')
batch_size = args.num_nodes * args.gpu_num_per_node * args.batch_size_per_device
eval_batch_size = args.num_nodes * args.gpu_num_per_node * args.eval_batch_size_per_device
epoch_size = math.ceil(args.train_example_num / batch_size)
num_eval_steps = math.ceil(args.eval_example_num / eval_batch_size)
args.iter_num = epoch_size * args.num_epochs
configs.print_args(args)
glue_output_modes = {
"cola": "classification",
"mnli": "classification",
"mnli-mm": "classification",
"mrpc": "classification",
"sst-2": "classification",
"sts-b": "regression",
"qqp": "classification",
"qnli": "classification",
"rte": "classification",
"wnli": "classification",
}
acc_tasks = ["mnli", "mrpc", "sst-2", "qqp", "qnli", "rte"]
corr_tasks = ["sts-b"]
mcc_tasks = ["cola"]
output_mode = glue_output_modes[args.task_name.lower()]
def BertDecoder(
data_dir, batch_size, data_part_num, seq_length, part_name_prefix, shuffle=True
):
with flow.scope.placement("cpu", "0:0"):
ofrecord = flow.data.ofrecord_reader(data_dir,
batch_size=batch_size,
data_part_num=data_part_num,
part_name_prefix=part_name_prefix,
random_shuffle=shuffle,
shuffle_after_epoch=shuffle)
blob_confs = {}
def _blob_conf(name, shape, dtype=flow.int32):
blob_confs[name] = flow.data.OFRecordRawDecoder(ofrecord, name, shape=shape, dtype=dtype)
_blob_conf("input_ids", [seq_length])
_blob_conf("input_mask", [seq_length])
_blob_conf("segment_ids", [seq_length])
_blob_conf("label_ids", [1])
_blob_conf("is_real_example", [1])
return blob_confs
def get_tensor_data(
batch_size,
data_part_num,
data_dir,
part_name_prefix,
shuffle=True
):
decoders = BertDecoder(
data_dir, batch_size, data_part_num, args.seq_length, part_name_prefix, shuffle=shuffle
)
return decoders
def BuildBert(
batch_size,
data_part_num,
data_dir,
part_name_prefix,
shuffle=True
):
hidden_size = args.hidden_size ##64 * args.num_attention_heads # , H = 64, size per head
args.hidden_size_per_head = hidden_size / args.num_attention_heads
# intermediate_size = hidden_size * 4
intermediate_size = 1200
decoders = BertDecoder(
data_dir, batch_size, data_part_num, args.seq_length, part_name_prefix, shuffle=shuffle
)
# is_real_example = decoders['is_real_example']
loss, logits = GlueBERT(
decoders['input_ids'],
decoders['input_mask'],
decoders['segment_ids'],
decoders['label_ids'],
args.vocab_size,
seq_length=args.seq_length,
hidden_size=hidden_size,
num_hidden_layers=args.num_hidden_layers,
num_attention_heads=args.num_attention_heads,
intermediate_size=intermediate_size,
hidden_act="gelu",
hidden_dropout_prob=args.hidden_dropout_prob,
attention_probs_dropout_prob=args.attention_probs_dropout_prob,
max_position_embeddings=args.max_position_embeddings,
type_vocab_size=args.type_vocab_size,
initializer_range=0.02,
)
return loss, logits, decoders['label_ids']
def student_model(input_ids, input_mask, segment_ids, is_train=True):
hidden_size = args.student_hidden_size ##64 * args.num_attention_heads # , H = 64, size per head
args.student_hidden_size_per_head = hidden_size / args.student_num_attention_heads
# intermediate_size = hidden_size * 4
intermediate_size = 1200
logits, reps, atts = BertStudentForSequenceClassification(
input_ids_blob=input_ids,
input_mask_blob=input_mask,
token_type_ids_blob=segment_ids,
label_blob=None,
vocab_size=args.student_vocab_size,
seq_length=args.seq_length,
hidden_size=hidden_size,
num_hidden_layers=args.student_num_hidden_layers,
num_attention_heads=args.student_num_attention_heads,
intermediate_size=intermediate_size,
hidden_act="gelu",
hidden_dropout_prob=args.student_hidden_dropout_prob,
attention_probs_dropout_prob=args.student_attention_probs_dropout_prob,
max_position_embeddings=args.student_max_position_embeddings,
type_vocab_size=args.student_type_vocab_size,
initializer_range=0.02,
is_student=True,
fit_size=args.teacher_hidden_size,
is_train=is_train
)
return logits, reps, atts
def teacher_model(input_ids, input_mask, segment_ids, is_train):
teacher_hidden_size = args.teacher_hidden_size ##64 * args.num_attention_heads # , H = 64, size per head
args.teacher_hidden_size_per_head = teacher_hidden_size / args.teacher_num_attention_heads
intermediate_size = teacher_hidden_size * 4
logits, reps, atts = BertForSequenceClassification(
input_ids_blob=input_ids,
input_mask_blob=input_mask,
token_type_ids_blob=segment_ids,
label_blob=None,
vocab_size=args.vocab_size,
seq_length=args.seq_length,
hidden_size=teacher_hidden_size,
num_hidden_layers=args.teacher_num_hidden_layers,
num_attention_heads=args.teacher_num_attention_heads,
intermediate_size=intermediate_size,
hidden_act="gelu",
hidden_dropout_prob=args.teacher_hidden_dropout_prob,
attention_probs_dropout_prob=args.teacher_attention_probs_dropout_prob,
max_position_embeddings=args.teacher_max_position_embeddings,
type_vocab_size=args.teacher_type_vocab_size,
initializer_range=0.02,
is_student=False,
is_train=is_train
)
return logits, reps, atts
def watch_handler(y: tp.Numpy):
print("out:", y)
@flow.global_function(type='train', function_config=GetFunctionConfig(args))
def DistilJob():
train_dataset = get_tensor_data(
batch_size,
args.train_data_part_num,
args.train_data_dir,
args.train_data_prefix,
)
student_logits, student_reps, student_atts = student_model(train_dataset['input_ids'], train_dataset['input_mask'],
train_dataset['segment_ids'], is_train=True)
teacher_logits, teacher_reps, teacher_atts = teacher_model(train_dataset['input_ids'], train_dataset['input_mask'],
train_dataset['segment_ids'], is_train=False)
if output_mode == "classification":
cls_loss = pred_distill(args, student_logits, teacher_logits)
elif output_mode == "regression":
"""
todo
loss_mse = MSELoss()
cls_loss = loss_mse(student_logits.view(-1), label_ids.view(-1))
"""
pass
loss_ce = flow.nn.sparse_softmax_cross_entropy_with_logits(
logits=student_logits, labels=train_dataset['label_ids']
)
# flow.watch(student_logits, watch_handler)
# flow.watch(train_dataset['label_ids'], watch_handler)
loss = loss_ce * args.kd_alpha + cls_loss * (1 - args.kd_alpha)
flow.losses.add_loss(loss)
opt = CreateOptimizer(args)
opt.minimize(loss)
return {'loss': loss}
#
@flow.global_function(type='predict', function_config=GetFunctionConfig(args))
def StudentBertGlueEvalTrainJob():
train_dataset = get_tensor_data(
batch_size,
args.train_data_part_num,
args.train_data_dir,
args.train_data_prefix,
shuffle=False
)
student_logits, student_reps, student_atts = student_model(train_dataset['input_ids'], train_dataset['input_mask'],
train_dataset['segment_ids'], is_train=False)
return student_logits, train_dataset['label_ids']
@flow.global_function(type='predict', function_config=GetFunctionConfig(args))
def StudentBertGlueEvalValJob():
# 8551 or 1042
dev_dataset = get_tensor_data(
eval_batch_size,
args.eval_data_part_num,
args.eval_data_dir,
args.eval_data_prefix,
shuffle=False
)
student_logits, student_reps, student_atts = student_model(dev_dataset['input_ids'], dev_dataset['input_mask'],
dev_dataset['segment_ids'], is_train=False)
return student_logits, dev_dataset['label_ids']
def run_eval_job(eval_job_func, num_steps, desc='train'):
labels = []
predictions = []
start_time = time.time()
for index in range(num_steps):
logits, label = eval_job_func().get()
predictions.extend(list(logits.numpy().argmax(axis=1)))
labels.extend(list(label))
end_time = time.time()
cost_time = end_time - start_time
print('cost time: {} s'.format(cost_time))
model_size = getdirsize(args.model_save_dir)
print('model_size: %d Mbytes' % (model_size / 1024 / 1024)) # Mbytes
accuracy = accuracy_score(labels, predictions)
mcc = matthews_corrcoef(labels, predictions)
precision = precision_score(labels, predictions)
recall = recall_score(labels, predictions)
f_1 = f1_score(labels, predictions)
save_dict = {"accuracy": "%.2f" % accuracy,
"MCC": "%.2f" % mcc,
"precision": "%.2f" % precision,
"recall": "%.2f" % recall,
"f_1": "%.2f" % f_1,
"modelSize": "%d" % (model_size / 1024 / 1024),
"reasoningTime": "%.2f" % (args.eval_example_num / cost_time)} # sample/second
if args.result_dir == "":
args.result_dir = args.model_save_dir
if not os.path.exists(args.result_dir):
os.makedirs(args.result_dir)
with open(os.path.join(args.result_dir, 'results_{}.json'.format(desc)), "w") as f:
json.dump(save_dict, f)
def metric_fn(predictions, labels):
return {
"accuracy": accuracy,
"matthews_corrcoef": mcc,
"precision": precision,
"recall": recall,
"f1": f_1,
}
metric_dict = metric_fn(predictions, labels)
print(desc, ', '.join('{}: {:.3f}'.format(k, v) for k, v in metric_dict.items()))
return metric_dict
def CopyFile(filepath, newPath):
fileNames = os.listdir(filepath)
for file in fileNames:
newDir = os.path.join(filepath, file)
if os.path.isfile(newDir):
# print(newDir)
newFile = os.path.join(newPath, file)
shutil.copyfile(newDir, newFile)
else:
if not os.path.exists(os.path.join(newPath, file)):
os.makedirs(os.path.join(newPath, file))
CopyFile(newDir, os.path.join(newPath, file))
def main():
flow.config.gpu_device_num(args.gpu_num_per_node)
flow.env.log_dir(args.log_dir)
InitNodes(args)
check_point = flow.train.CheckPoint()
summary = Summary(args.log_dir, args)
if not os.path.exists(args.model_save_dir):
os.makedirs(args.model_save_dir)
if args.do_train:
print('Loading model...')
check_point.load(args.teacher_model)
print('Start training...')
global_step = 0
best_dev_acc = 0.0
for epoch in range(args.num_epochs):
metric = Metric(desc='finetune', print_steps=args.loss_print_every_n_iter, summary=summary,
batch_size=batch_size, keys=['loss'])
for step in range(epoch_size):
DistilJob().async_get(metric.metric_cb(step, epoch=epoch))
global_step += 1
# if (global_step + 1) % args.model_save_every_n_iter == 0:
# if not os.path.exists(args.model_save_dir):
# os.makedirs(args.model_save_dir)
# snapshot_save_path = os.path.join(
# args.model_save_dir, "snapshot_%d" % (global_step + 1)
# )
# print("Saving model to {}.".format(snapshot_save_path))
# check_point.save(snapshot_save_path)
print('EvalTrainJob...')
run_eval_job(StudentBertGlueEvalTrainJob, epoch_size, desc='train')
print('EvalValJob...')
result = run_eval_job(StudentBertGlueEvalValJob, num_eval_steps, desc='eval')
save_model = False
if task_name in acc_tasks and result['accuracy'] > best_dev_acc:
best_dev_acc = result['accuracy']
save_model = True
# if task_name in corr_tasks and result['corr'] > best_dev_acc:
# best_dev_acc = result['corr']
# save_model = True
if task_name in mcc_tasks and result['matthews_corrcoef'] > best_dev_acc:
best_dev_acc = result['matthews_corrcoef']
save_model = True
print('Best result:', result)
if save_model:
if os.path.exists(args.model_save_dir):
import shutil
shutil.rmtree(args.model_save_dir)
if not os.path.exists(args.model_save_dir):
os.makedirs(args.model_save_dir)
snapshot_save_path = os.path.join(args.model_save_dir)
print("Saving best model to {}".format(snapshot_save_path))
check_point.save(snapshot_save_path)
flow.sync_default_session()
if args.save_last_snapshot:
snapshot_save_path = args.model_save_dir
if os.path.exists(args.model_save_dir):
import shutil
shutil.rmtree(args.model_save_dir)
print("Saving model to {}".format(snapshot_save_path))
check_point.save(snapshot_save_path)
flow.sync_default_session()
if args.serve_for_online:
print('Deleting the teacher params and the optimizer parmas from model_save_dir...')
remove_teacher_params(args.model_save_dir)
if args.do_eval:
print('Loading model...')
print(args.model_save_dir)
if not args.do_train:
check_point.load(args.model_save_dir)
print('Evaluation...')
run_eval_job(StudentBertGlueEvalValJob, num_eval_steps, desc='eval')
# if args.save_last_snapshot:
# snapshot.save("last_snapshot")
if __name__ == "__main__":
main()
| [
"oneflow.data.OFRecordRawDecoder",
"oneflow.sync_default_session",
"oneflow.env.log_dir",
"oneflow.nn.sparse_softmax_cross_entropy_with_logits",
"oneflow.losses.add_loss",
"oneflow.train.CheckPoint",
"oneflow.scope.placement",
"oneflow.config.gpu_device_num",
"oneflow.data.ofrecord_reader"
] | [((1712, 1732), 'config.get_parser', 'configs.get_parser', ([], {}), '()\n', (1730, 1732), True, 'import config as configs\n'), ((5330, 5376), 'math.ceil', 'math.ceil', (['(args.train_example_num / batch_size)'], {}), '(args.train_example_num / batch_size)\n', (5339, 5376), False, 'import math\n'), ((5394, 5444), 'math.ceil', 'math.ceil', (['(args.eval_example_num / eval_batch_size)'], {}), '(args.eval_example_num / eval_batch_size)\n', (5403, 5444), False, 'import math\n'), ((5490, 5514), 'config.print_args', 'configs.print_args', (['args'], {}), '(args)\n', (5508, 5514), True, 'import config as configs\n'), ((667, 692), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (682, 692), False, 'import os\n'), ((705, 727), 'os.path.split', 'os.path.split', (['curPath'], {}), '(curPath)\n', (718, 727), False, 'import os\n'), ((7859, 8438), 'classifier.GlueBERT', 'GlueBERT', (["decoders['input_ids']", "decoders['input_mask']", "decoders['segment_ids']", "decoders['label_ids']", 'args.vocab_size'], {'seq_length': 'args.seq_length', 'hidden_size': 'hidden_size', 'num_hidden_layers': 'args.num_hidden_layers', 'num_attention_heads': 'args.num_attention_heads', 'intermediate_size': 'intermediate_size', 'hidden_act': '"""gelu"""', 'hidden_dropout_prob': 'args.hidden_dropout_prob', 'attention_probs_dropout_prob': 'args.attention_probs_dropout_prob', 'max_position_embeddings': 'args.max_position_embeddings', 'type_vocab_size': 'args.type_vocab_size', 'initializer_range': '(0.02)'}), "(decoders['input_ids'], decoders['input_mask'], decoders[\n 'segment_ids'], decoders['label_ids'], args.vocab_size, seq_length=args\n .seq_length, hidden_size=hidden_size, num_hidden_layers=args.\n num_hidden_layers, num_attention_heads=args.num_attention_heads,\n intermediate_size=intermediate_size, hidden_act='gelu',\n hidden_dropout_prob=args.hidden_dropout_prob,\n attention_probs_dropout_prob=args.attention_probs_dropout_prob,\n max_position_embeddings=args.max_position_embeddings, type_vocab_size=\n args.type_vocab_size, initializer_range=0.02)\n", (7867, 8438), False, 'from classifier import GlueBERT\n'), ((8944, 9705), 'knowledge_distill_util.BertStudentForSequenceClassification', 'BertStudentForSequenceClassification', ([], {'input_ids_blob': 'input_ids', 'input_mask_blob': 'input_mask', 'token_type_ids_blob': 'segment_ids', 'label_blob': 'None', 'vocab_size': 'args.student_vocab_size', 'seq_length': 'args.seq_length', 'hidden_size': 'hidden_size', 'num_hidden_layers': 'args.student_num_hidden_layers', 'num_attention_heads': 'args.student_num_attention_heads', 'intermediate_size': 'intermediate_size', 'hidden_act': '"""gelu"""', 'hidden_dropout_prob': 'args.student_hidden_dropout_prob', 'attention_probs_dropout_prob': 'args.student_attention_probs_dropout_prob', 'max_position_embeddings': 'args.student_max_position_embeddings', 'type_vocab_size': 'args.student_type_vocab_size', 'initializer_range': '(0.02)', 'is_student': '(True)', 'fit_size': 'args.teacher_hidden_size', 'is_train': 'is_train'}), "(input_ids_blob=input_ids,\n input_mask_blob=input_mask, token_type_ids_blob=segment_ids, label_blob\n =None, vocab_size=args.student_vocab_size, seq_length=args.seq_length,\n hidden_size=hidden_size, num_hidden_layers=args.\n student_num_hidden_layers, num_attention_heads=args.\n student_num_attention_heads, intermediate_size=intermediate_size,\n hidden_act='gelu', hidden_dropout_prob=args.student_hidden_dropout_prob,\n attention_probs_dropout_prob=args.student_attention_probs_dropout_prob,\n max_position_embeddings=args.student_max_position_embeddings,\n type_vocab_size=args.student_type_vocab_size, initializer_range=0.02,\n is_student=True, fit_size=args.teacher_hidden_size, is_train=is_train)\n", (8980, 9705), False, 'from knowledge_distill_util import BertForSequenceClassification, BertStudentForSequenceClassification, soft_cross_entropy, mseloss, layer_distill, att_distill, pred_distill\n'), ((10197, 10921), 'knowledge_distill_util.BertForSequenceClassification', 'BertForSequenceClassification', ([], {'input_ids_blob': 'input_ids', 'input_mask_blob': 'input_mask', 'token_type_ids_blob': 'segment_ids', 'label_blob': 'None', 'vocab_size': 'args.vocab_size', 'seq_length': 'args.seq_length', 'hidden_size': 'teacher_hidden_size', 'num_hidden_layers': 'args.teacher_num_hidden_layers', 'num_attention_heads': 'args.teacher_num_attention_heads', 'intermediate_size': 'intermediate_size', 'hidden_act': '"""gelu"""', 'hidden_dropout_prob': 'args.teacher_hidden_dropout_prob', 'attention_probs_dropout_prob': 'args.teacher_attention_probs_dropout_prob', 'max_position_embeddings': 'args.teacher_max_position_embeddings', 'type_vocab_size': 'args.teacher_type_vocab_size', 'initializer_range': '(0.02)', 'is_student': '(False)', 'is_train': 'is_train'}), "(input_ids_blob=input_ids, input_mask_blob=\n input_mask, token_type_ids_blob=segment_ids, label_blob=None,\n vocab_size=args.vocab_size, seq_length=args.seq_length, hidden_size=\n teacher_hidden_size, num_hidden_layers=args.teacher_num_hidden_layers,\n num_attention_heads=args.teacher_num_attention_heads, intermediate_size\n =intermediate_size, hidden_act='gelu', hidden_dropout_prob=args.\n teacher_hidden_dropout_prob, attention_probs_dropout_prob=args.\n teacher_attention_probs_dropout_prob, max_position_embeddings=args.\n teacher_max_position_embeddings, type_vocab_size=args.\n teacher_type_vocab_size, initializer_range=0.02, is_student=False,\n is_train=is_train)\n", (10226, 10921), False, 'from knowledge_distill_util import BertForSequenceClassification, BertStudentForSequenceClassification, soft_cross_entropy, mseloss, layer_distill, att_distill, pred_distill\n'), ((12138, 12248), 'oneflow.nn.sparse_softmax_cross_entropy_with_logits', 'flow.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'student_logits', 'labels': "train_dataset['label_ids']"}), "(logits=student_logits,\n labels=train_dataset['label_ids'])\n", (12186, 12248), True, 'import oneflow as flow\n'), ((12440, 12466), 'oneflow.losses.add_loss', 'flow.losses.add_loss', (['loss'], {}), '(loss)\n', (12460, 12466), True, 'import oneflow as flow\n'), ((12478, 12499), 'util.CreateOptimizer', 'CreateOptimizer', (['args'], {}), '(args)\n', (12493, 12499), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig, getdirsize, remove_optimizer_params, remove_teacher_params\n'), ((13835, 13846), 'time.time', 'time.time', ([], {}), '()\n', (13844, 13846), False, 'import time\n'), ((14042, 14053), 'time.time', 'time.time', ([], {}), '()\n', (14051, 14053), False, 'import time\n'), ((14157, 14188), 'util.getdirsize', 'getdirsize', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (14167, 14188), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig, getdirsize, remove_optimizer_params, remove_teacher_params\n'), ((14279, 14314), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['labels', 'predictions'], {}), '(labels, predictions)\n', (14293, 14314), False, 'from sklearn.metrics import accuracy_score, matthews_corrcoef, precision_score, recall_score, f1_score\n'), ((14325, 14363), 'sklearn.metrics.matthews_corrcoef', 'matthews_corrcoef', (['labels', 'predictions'], {}), '(labels, predictions)\n', (14342, 14363), False, 'from sklearn.metrics import accuracy_score, matthews_corrcoef, precision_score, recall_score, f1_score\n'), ((14380, 14416), 'sklearn.metrics.precision_score', 'precision_score', (['labels', 'predictions'], {}), '(labels, predictions)\n', (14395, 14416), False, 'from sklearn.metrics import accuracy_score, matthews_corrcoef, precision_score, recall_score, f1_score\n'), ((14430, 14463), 'sklearn.metrics.recall_score', 'recall_score', (['labels', 'predictions'], {}), '(labels, predictions)\n', (14442, 14463), False, 'from sklearn.metrics import accuracy_score, matthews_corrcoef, precision_score, recall_score, f1_score\n'), ((14474, 14503), 'sklearn.metrics.f1_score', 'f1_score', (['labels', 'predictions'], {}), '(labels, predictions)\n', (14482, 14503), False, 'from sklearn.metrics import accuracy_score, matthews_corrcoef, precision_score, recall_score, f1_score\n'), ((15601, 15621), 'os.listdir', 'os.listdir', (['filepath'], {}), '(filepath)\n', (15611, 15621), False, 'import os\n'), ((16064, 16113), 'oneflow.config.gpu_device_num', 'flow.config.gpu_device_num', (['args.gpu_num_per_node'], {}), '(args.gpu_num_per_node)\n', (16090, 16113), True, 'import oneflow as flow\n'), ((16118, 16148), 'oneflow.env.log_dir', 'flow.env.log_dir', (['args.log_dir'], {}), '(args.log_dir)\n', (16134, 16148), True, 'import oneflow as flow\n'), ((16154, 16169), 'util.InitNodes', 'InitNodes', (['args'], {}), '(args)\n', (16163, 16169), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig, getdirsize, remove_optimizer_params, remove_teacher_params\n'), ((16189, 16212), 'oneflow.train.CheckPoint', 'flow.train.CheckPoint', ([], {}), '()\n', (16210, 16212), True, 'import oneflow as flow\n'), ((16228, 16255), 'util.Summary', 'Summary', (['args.log_dir', 'args'], {}), '(args.log_dir, args)\n', (16235, 16255), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig, getdirsize, remove_optimizer_params, remove_teacher_params\n'), ((6120, 6154), 'oneflow.scope.placement', 'flow.scope.placement', (['"""cpu"""', '"""0:0"""'], {}), "('cpu', '0:0')\n", (6140, 6154), True, 'import oneflow as flow\n'), ((6175, 6360), 'oneflow.data.ofrecord_reader', 'flow.data.ofrecord_reader', (['data_dir'], {'batch_size': 'batch_size', 'data_part_num': 'data_part_num', 'part_name_prefix': 'part_name_prefix', 'random_shuffle': 'shuffle', 'shuffle_after_epoch': 'shuffle'}), '(data_dir, batch_size=batch_size, data_part_num=\n data_part_num, part_name_prefix=part_name_prefix, random_shuffle=\n shuffle, shuffle_after_epoch=shuffle)\n', (6200, 6360), True, 'import oneflow as flow\n'), ((11882, 11932), 'knowledge_distill_util.pred_distill', 'pred_distill', (['args', 'student_logits', 'teacher_logits'], {}), '(args, student_logits, teacher_logits)\n', (11894, 11932), False, 'from knowledge_distill_util import BertForSequenceClassification, BertStudentForSequenceClassification, soft_cross_entropy, mseloss, layer_distill, att_distill, pred_distill\n'), ((11164, 11187), 'util.GetFunctionConfig', 'GetFunctionConfig', (['args'], {}), '(args)\n', (11181, 11187), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig, getdirsize, remove_optimizer_params, remove_teacher_params\n'), ((12608, 12631), 'util.GetFunctionConfig', 'GetFunctionConfig', (['args'], {}), '(args)\n', (12625, 12631), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig, getdirsize, remove_optimizer_params, remove_teacher_params\n'), ((13188, 13211), 'util.GetFunctionConfig', 'GetFunctionConfig', (['args'], {}), '(args)\n', (13205, 13211), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig, getdirsize, remove_optimizer_params, remove_teacher_params\n'), ((14972, 15003), 'os.path.exists', 'os.path.exists', (['args.result_dir'], {}), '(args.result_dir)\n', (14986, 15003), False, 'import os\n'), ((15013, 15041), 'os.makedirs', 'os.makedirs', (['args.result_dir'], {}), '(args.result_dir)\n', (15024, 15041), False, 'import os\n'), ((15138, 15161), 'json.dump', 'json.dump', (['save_dict', 'f'], {}), '(save_dict, f)\n', (15147, 15161), False, 'import json\n'), ((15666, 15694), 'os.path.join', 'os.path.join', (['filepath', 'file'], {}), '(filepath, file)\n', (15678, 15694), False, 'import os\n'), ((15706, 15728), 'os.path.isfile', 'os.path.isfile', (['newDir'], {}), '(newDir)\n', (15720, 15728), False, 'import os\n'), ((16267, 16302), 'os.path.exists', 'os.path.exists', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (16281, 16302), False, 'import os\n'), ((16312, 16344), 'os.makedirs', 'os.makedirs', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (16323, 16344), False, 'import os\n'), ((776, 787), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (785, 787), False, 'import os\n'), ((1640, 1700), 'argparse.ArgumentTypeError', 'argparse.ArgumentTypeError', (['"""Unsupported value encountered."""'], {}), "('Unsupported value encountered.')\n", (1666, 1700), False, 'import argparse\n'), ((6687, 6757), 'oneflow.data.OFRecordRawDecoder', 'flow.data.OFRecordRawDecoder', (['ofrecord', 'name'], {'shape': 'shape', 'dtype': 'dtype'}), '(ofrecord, name, shape=shape, dtype=dtype)\n', (6715, 6757), True, 'import oneflow as flow\n'), ((15780, 15807), 'os.path.join', 'os.path.join', (['newPath', 'file'], {}), '(newPath, file)\n', (15792, 15807), False, 'import os\n'), ((15820, 15852), 'shutil.copyfile', 'shutil.copyfile', (['newDir', 'newFile'], {}), '(newDir, newFile)\n', (15835, 15852), False, 'import shutil\n'), ((16599, 16724), 'util.Metric', 'Metric', ([], {'desc': '"""finetune"""', 'print_steps': 'args.loss_print_every_n_iter', 'summary': 'summary', 'batch_size': 'batch_size', 'keys': "['loss']"}), "(desc='finetune', print_steps=args.loss_print_every_n_iter, summary=\n summary, batch_size=batch_size, keys=['loss'])\n", (16605, 16724), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig, getdirsize, remove_optimizer_params, remove_teacher_params\n'), ((18858, 18893), 'os.path.exists', 'os.path.exists', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (18872, 18893), False, 'import os\n'), ((19104, 19131), 'oneflow.sync_default_session', 'flow.sync_default_session', ([], {}), '()\n', (19129, 19131), True, 'import oneflow as flow\n'), ((19276, 19318), 'util.remove_teacher_params', 'remove_teacher_params', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (19297, 19318), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig, getdirsize, remove_optimizer_params, remove_teacher_params\n'), ((16017, 16044), 'os.path.join', 'os.path.join', (['newPath', 'file'], {}), '(newPath, file)\n', (16029, 16044), False, 'import os\n'), ((18270, 18305), 'os.path.exists', 'os.path.exists', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (18284, 18305), False, 'import os\n'), ((18546, 18579), 'os.path.join', 'os.path.join', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (18558, 18579), False, 'import os\n'), ((18725, 18752), 'oneflow.sync_default_session', 'flow.sync_default_session', ([], {}), '()\n', (18750, 18752), True, 'import oneflow as flow\n'), ((18941, 18975), 'shutil.rmtree', 'shutil.rmtree', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (18954, 18975), False, 'import shutil\n'), ((15901, 15928), 'os.path.join', 'os.path.join', (['newPath', 'file'], {}), '(newPath, file)\n', (15913, 15928), False, 'import os\n'), ((15959, 15986), 'os.path.join', 'os.path.join', (['newPath', 'file'], {}), '(newPath, file)\n', (15971, 15986), False, 'import os\n'), ((18361, 18395), 'shutil.rmtree', 'shutil.rmtree', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (18374, 18395), False, 'import shutil\n'), ((18419, 18454), 'os.path.exists', 'os.path.exists', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (18433, 18454), False, 'import os\n'), ((18476, 18508), 'os.makedirs', 'os.makedirs', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (18487, 18508), False, 'import os\n')] |
import errno
import hashlib
import os
import re
import shutil
import sys
import tempfile
import zipfile
import tarfile
import warnings
import logging
from urllib.parse import urlparse
from urllib.request import Request, urlopen
from tqdm import tqdm
from typing import Optional
import oneflow as flow
HASH_REGEX = re.compile(r"([a-f0-9]*)_")
def get_cache_dir(cache_dir: Optional[str] = None) -> str:
"""
Modified from https://github.com/facebookresearch/iopath/blob/main/iopath/common/file_io.py
Returns a default directory to cache static files
(usually downloaded from Internet), if None is provided.
Args:
cache_dir (None or str): if not None, will be returned as is.
If None, returns the default cache directory as:
1) $FLOWVISION_CACHE, if set
2) otherwise ~/.oneflow/flowvision_cache
"""
if cache_dir is None:
cache_dir = os.path.expanduser(
os.getenv("FLOWVISION_CACHE", "~/.oneflow/flowvision_cache")
)
try:
os.makedirs(cache_dir, exist_ok=True)
assert os.access(cache_dir, os.W_OK)
except (OSError, AssertionError):
tmp_dir = os.path.join(tempfile.gettempdir(), "flowvision_cache")
logger = logging.getLogger(__name__)
logger.warning(f"{cache_dir} is not accessible! Using {tmp_dir} instead!")
cache_dir = tmp_dir
return cache_dir
def _is_legacy_tar_format(filename):
return tarfile.is_tarfile(filename)
def _legacy_tar_load(filename, model_dir, map_location, delete_tar_file=True):
with tarfile.open(filename) as f:
members = f.getnames()
extracted_name = members[0]
extracted_file = os.path.join(model_dir, extracted_name)
if not os.path.exists(model_dir):
os.mkdir(model_dir)
f.extractall(model_dir)
if delete_tar_file:
os.remove(filename)
return flow.load(extracted_file)
def _is_legacy_zip_format(filename):
return zipfile.is_zipfile(filename)
def _legacy_zip_load(filename, model_dir, map_location, delete_zip_file=True):
# Note: extractall() defaults to overwrite file if exists. No need to clean up beforehand.
# We deliberately don't handle tarfile here since our legacy serialization format was in tar.
with zipfile.ZipFile(filename) as f:
members = f.infolist()
extracted_name = members[0].filename
extracted_file = os.path.join(model_dir, extracted_name)
if not os.path.exists(extracted_file):
os.mkdir(extracted_file)
f.extractall(model_dir)
if delete_zip_file and os.path.exists(filename):
os.remove(filename)
return flow.load(extracted_file, map_location)
def load_state_dict_from_url(
url,
model_dir=None,
map_location=None,
progress=True,
check_hash=False,
file_name=None,
delete_file=True,
):
r"""Loads the OneFlow serialized object at the given URL.
If downloaded file is a zip file, it will be automatically
decompressed.
If the object is already present in `model_dir`, it's deserialized and
returned.
Args:
url (string): URL of the object to download
model_dir (string, optional): directory in which to save the object
map_location (optional): a function or a dict specifying how to remap storage locations (see flow.load)
progress (bool, optional): whether or not to display a progress bar to stderr.
Default: ``True``
check_hash(bool, optional): If True, the filename part of the URL should follow the naming convention
``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more
digits of the SHA256 hash of the contents of the file. The hash is used to
ensure unique names and to verify the contents of the file.
Default: ``False``
file_name (string, optional): name for the downloaded file. Filename from `url` will be used if not set
delete_file (bool, optional): delete downloaded `.zip` file or `.tar.gz` file after unzipping them.
"""
try:
model_dir = get_cache_dir(model_dir)
except OSError as e:
if e.errno == errno.EEXIST:
# Directory already exists, ignore.
pass
else:
# Unexpected OSError, re-raise.
raise
parts = urlparse(url)
filename = os.path.basename(parts.path)
if file_name is not None:
filename = file_name
# if already download the weight, directly return loaded state_dict
pretrained_weight_dir = os.path.join(model_dir, filename.split(".")[0])
if os.path.exists(pretrained_weight_dir):
state_dict = flow.load(pretrained_weight_dir)
return state_dict
cached_file = os.path.join(model_dir, filename)
if not os.path.exists(cached_file):
sys.stderr.write('Downloading: "{}" to {}\n'.format(url, cached_file))
hash_prefix = None
if check_hash:
r = HASH_REGEX.search(filename) # r is Optional[Match[str]]
hash_prefix = r.group(1) if r else None
download_url_to_file(url, cached_file, hash_prefix, progress=progress)
if _is_legacy_zip_format(cached_file):
return _legacy_zip_load(cached_file, model_dir, map_location, delete_file)
elif _is_legacy_tar_format(cached_file):
return _legacy_tar_load(cached_file, model_dir, map_location, delete_file)
else:
state_dict = flow.load(cached_file)
return state_dict
def download_url_to_file(url, dst, hash_prefix=None, progress=True):
r"""Download object at the given URL to a local path.
Args:
url (string): URL of the object to download
dst (string): Full path where object will be saved, e.g. `/tmp/temporary_file`
hash_prefix (string, optional): If not None, the SHA256 downloaded file should start with `hash_prefix`.
Default: ``None``
progress (bool, optional): whether or not to display a progress bar to stderr
Default: ``True``
"""
file_size = None
# We use a different API for python2 since urllib(2) doesn't recognize the CA
# certificates in older Python
# TODO: if there is a backend requirements, we should add headers in Request module
req = Request(url)
u = urlopen(req)
meta = u.info()
if hasattr(meta, "getheaders"):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
# We deliberately save it in a temp file and move it after
# download is complete. This prevents a local working checkpoint
# being overridden by a broken download.
dst = os.path.expanduser(dst)
dst_dir = os.path.dirname(dst)
f = tempfile.NamedTemporaryFile(delete=False, dir=dst_dir)
try:
if hash_prefix is not None:
sha256 = hashlib.sha256()
with tqdm(
total=file_size,
disable=not progress,
unit="B",
unit_scale=True,
unit_divisor=1024,
) as pbar:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
if hash_prefix is not None:
sha256.update(buffer)
pbar.update(len(buffer))
f.close()
if hash_prefix is not None:
digest = sha256.hexdigest()
if digest[: len(hash_prefix)] != hash_prefix:
raise RuntimeError(
'invalid hash value (expected "{}", got "{}")'.format(
hash_prefix, digest
)
)
shutil.move(f.name, dst)
finally:
f.close()
if os.path.exists(f.name):
os.remove(f.name)
| [
"oneflow.load"
] | [((316, 342), 're.compile', 're.compile', (['"""([a-f0-9]*)_"""'], {}), "('([a-f0-9]*)_')\n", (326, 342), False, 'import re\n'), ((1447, 1475), 'tarfile.is_tarfile', 'tarfile.is_tarfile', (['filename'], {}), '(filename)\n', (1465, 1475), False, 'import tarfile\n'), ((1896, 1921), 'oneflow.load', 'flow.load', (['extracted_file'], {}), '(extracted_file)\n', (1905, 1921), True, 'import oneflow as flow\n'), ((1972, 2000), 'zipfile.is_zipfile', 'zipfile.is_zipfile', (['filename'], {}), '(filename)\n', (1990, 2000), False, 'import zipfile\n'), ((2671, 2710), 'oneflow.load', 'flow.load', (['extracted_file', 'map_location'], {}), '(extracted_file, map_location)\n', (2680, 2710), True, 'import oneflow as flow\n'), ((4365, 4378), 'urllib.parse.urlparse', 'urlparse', (['url'], {}), '(url)\n', (4373, 4378), False, 'from urllib.parse import urlparse\n'), ((4394, 4422), 'os.path.basename', 'os.path.basename', (['parts.path'], {}), '(parts.path)\n', (4410, 4422), False, 'import os\n'), ((4637, 4674), 'os.path.exists', 'os.path.exists', (['pretrained_weight_dir'], {}), '(pretrained_weight_dir)\n', (4651, 4674), False, 'import os\n'), ((4775, 4808), 'os.path.join', 'os.path.join', (['model_dir', 'filename'], {}), '(model_dir, filename)\n', (4787, 4808), False, 'import os\n'), ((6299, 6311), 'urllib.request.Request', 'Request', (['url'], {}), '(url)\n', (6306, 6311), False, 'from urllib.request import Request, urlopen\n'), ((6320, 6332), 'urllib.request.urlopen', 'urlopen', (['req'], {}), '(req)\n', (6327, 6332), False, 'from urllib.request import Request, urlopen\n'), ((6808, 6831), 'os.path.expanduser', 'os.path.expanduser', (['dst'], {}), '(dst)\n', (6826, 6831), False, 'import os\n'), ((6846, 6866), 'os.path.dirname', 'os.path.dirname', (['dst'], {}), '(dst)\n', (6861, 6866), False, 'import os\n'), ((6875, 6929), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'delete': '(False)', 'dir': 'dst_dir'}), '(delete=False, dir=dst_dir)\n', (6902, 6929), False, 'import tempfile\n'), ((1025, 1062), 'os.makedirs', 'os.makedirs', (['cache_dir'], {'exist_ok': '(True)'}), '(cache_dir, exist_ok=True)\n', (1036, 1062), False, 'import os\n'), ((1078, 1107), 'os.access', 'os.access', (['cache_dir', 'os.W_OK'], {}), '(cache_dir, os.W_OK)\n', (1087, 1107), False, 'import os\n'), ((1566, 1588), 'tarfile.open', 'tarfile.open', (['filename'], {}), '(filename)\n', (1578, 1588), False, 'import tarfile\n'), ((1687, 1726), 'os.path.join', 'os.path.join', (['model_dir', 'extracted_name'], {}), '(model_dir, extracted_name)\n', (1699, 1726), False, 'import os\n'), ((1865, 1884), 'os.remove', 'os.remove', (['filename'], {}), '(filename)\n', (1874, 1884), False, 'import os\n'), ((2290, 2315), 'zipfile.ZipFile', 'zipfile.ZipFile', (['filename'], {}), '(filename)\n', (2305, 2315), False, 'import zipfile\n'), ((2423, 2462), 'os.path.join', 'os.path.join', (['model_dir', 'extracted_name'], {}), '(model_dir, extracted_name)\n', (2435, 2462), False, 'import os\n'), ((2606, 2630), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (2620, 2630), False, 'import os\n'), ((2640, 2659), 'os.remove', 'os.remove', (['filename'], {}), '(filename)\n', (2649, 2659), False, 'import os\n'), ((4697, 4729), 'oneflow.load', 'flow.load', (['pretrained_weight_dir'], {}), '(pretrained_weight_dir)\n', (4706, 4729), True, 'import oneflow as flow\n'), ((4820, 4847), 'os.path.exists', 'os.path.exists', (['cached_file'], {}), '(cached_file)\n', (4834, 4847), False, 'import os\n'), ((7837, 7861), 'shutil.move', 'shutil.move', (['f.name', 'dst'], {}), '(f.name, dst)\n', (7848, 7861), False, 'import shutil\n'), ((7904, 7926), 'os.path.exists', 'os.path.exists', (['f.name'], {}), '(f.name)\n', (7918, 7926), False, 'import os\n'), ((937, 997), 'os.getenv', 'os.getenv', (['"""FLOWVISION_CACHE"""', '"""~/.oneflow/flowvision_cache"""'], {}), "('FLOWVISION_CACHE', '~/.oneflow/flowvision_cache')\n", (946, 997), False, 'import os\n'), ((1237, 1264), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1254, 1264), False, 'import logging\n'), ((1742, 1767), 'os.path.exists', 'os.path.exists', (['model_dir'], {}), '(model_dir)\n', (1756, 1767), False, 'import os\n'), ((1781, 1800), 'os.mkdir', 'os.mkdir', (['model_dir'], {}), '(model_dir)\n', (1789, 1800), False, 'import os\n'), ((2478, 2508), 'os.path.exists', 'os.path.exists', (['extracted_file'], {}), '(extracted_file)\n', (2492, 2508), False, 'import os\n'), ((2522, 2546), 'os.mkdir', 'os.mkdir', (['extracted_file'], {}), '(extracted_file)\n', (2530, 2546), False, 'import os\n'), ((5468, 5490), 'oneflow.load', 'flow.load', (['cached_file'], {}), '(cached_file)\n', (5477, 5490), True, 'import oneflow as flow\n'), ((6997, 7013), 'hashlib.sha256', 'hashlib.sha256', ([], {}), '()\n', (7011, 7013), False, 'import hashlib\n'), ((7027, 7120), 'tqdm.tqdm', 'tqdm', ([], {'total': 'file_size', 'disable': '(not progress)', 'unit': '"""B"""', 'unit_scale': '(True)', 'unit_divisor': '(1024)'}), "(total=file_size, disable=not progress, unit='B', unit_scale=True,\n unit_divisor=1024)\n", (7031, 7120), False, 'from tqdm import tqdm\n'), ((7940, 7957), 'os.remove', 'os.remove', (['f.name'], {}), '(f.name)\n', (7949, 7957), False, 'import os\n'), ((1177, 1198), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (1196, 1198), False, 'import tempfile\n')] |
from typing import Callable
from overrides import overrides
import oneflow as flow
class Highway(flow.nn.Module):
def __init__(
self,
input_dim: int,
num_layers: int = 1,
activation: Callable[[flow.Tensor], flow.Tensor] = flow.nn.functional.relu,
) -> None:
super(Highway, self).__init__()
self._input_dim = input_dim
self._layers = flow.nn.ModuleList(
[flow.nn.Linear(input_dim, input_dim * 2) for _ in range(num_layers)]
)
self._activation = activation
for layer in self._layers:
layer.bias[input_dim:].data.fill_(1)
@overrides
def forward(self, inputs):
current_input = inputs
for layer in self._layers:
projected_input = layer(current_input)
linear_part = current_input
nonlinear_part = projected_input[
:, (0 * self._input_dim) : (1 * self._input_dim)
]
gate = projected_input[:, (1 * self._input_dim) : (2 * self._input_dim)]
nonlinear_part = self._activation(nonlinear_part)
gate = flow.sigmoid(gate)
current_input = gate * linear_part + (1 - gate) * nonlinear_part
return current_input
| [
"oneflow.sigmoid",
"oneflow.nn.Linear"
] | [((1129, 1147), 'oneflow.sigmoid', 'flow.sigmoid', (['gate'], {}), '(gate)\n', (1141, 1147), True, 'import oneflow as flow\n'), ((433, 473), 'oneflow.nn.Linear', 'flow.nn.Linear', (['input_dim', '(input_dim * 2)'], {}), '(input_dim, input_dim * 2)\n', (447, 473), True, 'import oneflow as flow\n')] |
"""
The code refers to DeepLearningForFun(https://github.com/Ldpe2G/DeepLearningForFun/tree/master/Oneflow-Python/CycleGAN) by Ldpe2G
and pytorch-CycleGAN-and-pix2pix(https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix) by junyuanz for implementation.
"""
import time
import argparse
from numpy.lib.npyio import load
import numpy as np
from image import ndarray2image, load_image2ndarray
from networks import ResnetGenerator
import os
import cv2
import oneflow as flow
def main(args):
opt = args
datasetA = os.listdir(args.datasetA_path)
datasetB = os.listdir(args.datasetB_path)
datasetA_num = len(datasetA)
datasetB_num = len(datasetB)
print("dataset A size: %d" % datasetA_num)
print("dataset B size: %d" % datasetB_num)
netG_A = ResnetGenerator().to("cuda")
netG_B = ResnetGenerator().to("cuda")
netG_A.load_state_dict(flow.load(args.netG_A_dir))
netG_B.load_state_dict(flow.load(args.netG_B_dir))
print("Begin transforming from A to B")
for i in range(datasetA_num):
if i % 10 == 0:
print("Transformed %d pictures..." % (i))
imageA = load_image2ndarray(args.datasetA_path + datasetA[i])
imageA_tensor = flow.Tensor(imageA).to("cuda")
imageB_fake = netG_A(imageA_tensor)
imageA = ndarray2image(imageA)
imageB = ndarray2image(imageB_fake.numpy())
result = np.concatenate((imageA, imageB), axis=1)
cv2.imwrite("%s%d.jpg" % (args.fake_B_save_dir, i), result)
print("Begin transforming from B to A")
for i in range(datasetB_num):
if i % 10 == 0:
print("Transformed %d pictures..." % (i))
imageB = load_image2ndarray(args.datasetB_path + datasetB[i])
imageB_tensor = flow.Tensor(imageB).to("cuda")
imageA_fake = netG_B(imageB_tensor)
imageB = ndarray2image(imageB)
imageA = ndarray2image(imageA_fake.numpy())
result = np.concatenate((imageB, imageA), axis=1)
cv2.imwrite("%s%d.jpg" % (args.fake_A_save_dir, i), result)
print("Finished")
def get_parser(parser=None):
parser = argparse.ArgumentParser("flags for cycle gan")
parser.add_argument("--datasetA_path", type=str, default="", help="dataset A path")
parser.add_argument("--datasetB_path", type=str, default="", help="dataset B path")
# checkpoint
parser.add_argument(
"--netG_A_dir", type=str, default=None, help="saving directory of netG_A_dir"
)
parser.add_argument(
"--netG_B_dir", type=str, default=None, help="saving directory of netG_B_dir"
)
# save dir
parser.add_argument(
"--fake_B_save_dir", default=None, help="directory for generated images"
)
parser.add_argument(
"--fake_A_save_dir", default=None, help="directory for generated images"
)
return parser
if __name__ == "__main__":
parser = get_parser()
args = parser.parse_args()
main(args)
| [
"oneflow.load",
"oneflow.Tensor"
] | [((523, 553), 'os.listdir', 'os.listdir', (['args.datasetA_path'], {}), '(args.datasetA_path)\n', (533, 553), False, 'import os\n'), ((569, 599), 'os.listdir', 'os.listdir', (['args.datasetB_path'], {}), '(args.datasetB_path)\n', (579, 599), False, 'import os\n'), ((2110, 2156), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""flags for cycle gan"""'], {}), "('flags for cycle gan')\n", (2133, 2156), False, 'import argparse\n'), ((874, 900), 'oneflow.load', 'flow.load', (['args.netG_A_dir'], {}), '(args.netG_A_dir)\n', (883, 900), True, 'import oneflow as flow\n'), ((929, 955), 'oneflow.load', 'flow.load', (['args.netG_B_dir'], {}), '(args.netG_B_dir)\n', (938, 955), True, 'import oneflow as flow\n'), ((1131, 1183), 'image.load_image2ndarray', 'load_image2ndarray', (['(args.datasetA_path + datasetA[i])'], {}), '(args.datasetA_path + datasetA[i])\n', (1149, 1183), False, 'from image import ndarray2image, load_image2ndarray\n'), ((1300, 1321), 'image.ndarray2image', 'ndarray2image', (['imageA'], {}), '(imageA)\n', (1313, 1321), False, 'from image import ndarray2image, load_image2ndarray\n'), ((1391, 1431), 'numpy.concatenate', 'np.concatenate', (['(imageA, imageB)'], {'axis': '(1)'}), '((imageA, imageB), axis=1)\n', (1405, 1431), True, 'import numpy as np\n'), ((1440, 1499), 'cv2.imwrite', 'cv2.imwrite', (["('%s%d.jpg' % (args.fake_B_save_dir, i))", 'result'], {}), "('%s%d.jpg' % (args.fake_B_save_dir, i), result)\n", (1451, 1499), False, 'import cv2\n'), ((1674, 1726), 'image.load_image2ndarray', 'load_image2ndarray', (['(args.datasetB_path + datasetB[i])'], {}), '(args.datasetB_path + datasetB[i])\n', (1692, 1726), False, 'from image import ndarray2image, load_image2ndarray\n'), ((1843, 1864), 'image.ndarray2image', 'ndarray2image', (['imageB'], {}), '(imageB)\n', (1856, 1864), False, 'from image import ndarray2image, load_image2ndarray\n'), ((1934, 1974), 'numpy.concatenate', 'np.concatenate', (['(imageB, imageA)'], {'axis': '(1)'}), '((imageB, imageA), axis=1)\n', (1948, 1974), True, 'import numpy as np\n'), ((1983, 2042), 'cv2.imwrite', 'cv2.imwrite', (["('%s%d.jpg' % (args.fake_A_save_dir, i))", 'result'], {}), "('%s%d.jpg' % (args.fake_A_save_dir, i), result)\n", (1994, 2042), False, 'import cv2\n'), ((775, 792), 'networks.ResnetGenerator', 'ResnetGenerator', ([], {}), '()\n', (790, 792), False, 'from networks import ResnetGenerator\n'), ((817, 834), 'networks.ResnetGenerator', 'ResnetGenerator', ([], {}), '()\n', (832, 834), False, 'from networks import ResnetGenerator\n'), ((1208, 1227), 'oneflow.Tensor', 'flow.Tensor', (['imageA'], {}), '(imageA)\n', (1219, 1227), True, 'import oneflow as flow\n'), ((1751, 1770), 'oneflow.Tensor', 'flow.Tensor', (['imageB'], {}), '(imageB)\n', (1762, 1770), 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.
"""
from __future__ import absolute_import
import getpass
import os
import sys
import uuid
from tempfile import NamedTemporaryFile
import google.protobuf.text_format as pbtxt
import oneflow.python.framework.env_util as env_util
from oneflow.core.job.env_pb2 import EnvProto
from oneflow.core.control.ctrl_bootstrap_pb2 import BootstrapConf
from oneflow.python.oneflow_export import oneflow_export
import subprocess
@oneflow_export("deprecated.init_worker")
def init_worker(
scp_binary: bool = True,
use_uuid: bool = True,
ssh_port=22,
bootstrap_conf_list=None,
) -> None:
assert type(env_util.default_env_proto) is EnvProto
env_util.defautl_env_proto_mutable = False
env_proto = env_util.default_env_proto
assert len(env_proto.machine) > 0 or len(bootstrap_conf_list) > 0
assert type(scp_binary) is bool
assert type(use_uuid) is bool
oneflow_worker_path = os.getenv("ONEFLOW_WORKER_BIN")
assert oneflow_worker_path is not None, "please set env ONEFLOW_WORKER_BIN"
assert os.path.isfile(
oneflow_worker_path
), "binary oneflow_worker not found, please check your environment variable ONEFLOW_WORKER_BIN, path: {}".format(
oneflow_worker_path
)
global _temp_run_dir
if use_uuid:
assert scp_binary is True
_temp_run_dir = os.getenv("HOME") + "/oneflow_temp/" + str(uuid.uuid1())
else:
_temp_run_dir = os.getenv("HOME") + "/oneflow_temp/no_uuid"
run_dir = _temp_run_dir
run_dir = os.path.abspath(os.path.expanduser(run_dir))
if bootstrap_conf_list is None:
env_file = NamedTemporaryFile(delete=False)
if sys.version_info >= (3, 0):
env_file.write(pbtxt.MessageToString(env_proto).encode())
else:
env_file.write(pbtxt.MessageToString(env_proto))
env_file.close()
for machine in env_proto.machine:
if machine.id == 0:
pass
else:
_SendBinaryAndConfig2Worker(
machine.addr,
oneflow_worker_path,
env_file.name,
run_dir,
scp_binary,
ssh_port,
)
os.remove(env_file.name)
else:
worker_env_proto = EnvProto()
worker_env_proto.CopyFrom(env_proto)
worker_env_proto.ClearField("ctrl_bootstrap_conf")
for bootstrap_conf in bootstrap_conf_list:
if bootstrap_conf.rank == 0:
continue
# set ctrl_bootstrap_conf of worker
assert bootstrap_conf.HasField("host")
worker_env_proto.ctrl_bootstrap_conf.CopyFrom(bootstrap_conf)
env_file = NamedTemporaryFile(delete=False)
if sys.version_info >= (3, 0):
env_file.write(pbtxt.MessageToString(worker_env_proto).encode())
else:
env_file.write(pbtxt.MessageToString(worker_env_proto))
env_file.close()
_SendBinaryAndConfig2Worker(
bootstrap_conf.host,
oneflow_worker_path,
env_file.name,
run_dir,
scp_binary,
ssh_port,
)
os.remove(env_file.name)
@oneflow_export("deprecated.delete_worker")
def delete_worker(ssh_port=22) -> None:
ssh_port_arg = " -p {} ".format(ssh_port)
# assert env_util.env_proto_mutable == False
env_proto = env_util.default_env_proto
assert isinstance(env_proto, EnvProto)
global _temp_run_dir
assert _temp_run_dir != ""
for machine in env_proto.machine:
if machine.id == 0:
continue
ssh_prefix = (
"ssh {} ".format(ssh_port_arg)
+ getpass.getuser()
+ "@"
+ machine.addr
+ " "
)
if os.getenv("ONEFLOW_WORKER_KEEP_LOG"):
print("worker log kept at: {}".format(machine.addr), flush=True)
else:
_SystemCall(ssh_prefix + '"rm -r ' + _temp_run_dir + '"')
print("temp run dir removed at: {}".format(machine.addr), flush=True)
@oneflow_export("deprecated.delete_worker_by_bootstrap")
def delete_worker_by_bootstrap(ssh_port=22) -> None:
ssh_port_arg = " -p {} ".format(ssh_port)
bootstrap_conf_list = env_util.global_ctrl_bootstrap_confs
assert isinstance(bootstrap_conf_list, list)
global _temp_run_dir
assert _temp_run_dir != ""
for bootstrap_conf in bootstrap_conf_list:
assert isinstance(bootstrap_conf, BootstrapConf)
if bootstrap_conf.rank == 0:
continue
ssh_prefix = (
"ssh {} ".format(ssh_port_arg)
+ getpass.getuser()
+ "@"
+ bootstrap_conf.host
+ " "
)
if os.getenv("ONEFLOW_WORKER_KEEP_LOG"):
print("worker log kept at: {}".format(bootstrap_conf.host), flush=True)
else:
_SystemCall(ssh_prefix + '"rm -r ' + _temp_run_dir + '"')
print("temp run dir removed at: {}".format(bootstrap_conf.host), flush=True)
@oneflow_export("deprecated.delete_worker_of_multi_process")
def delete_worker_of_multi_process(run_dir) -> None:
assert run_dir != ""
if os.getenv("ONEFLOW_WORKER_KEEP_LOG"):
print("worker log kept at localhost:" + run_dir, flush=True)
else:
os.system("rm -r " + run_dir)
print("temp run dir removed at localhost:" + run_dir, flush=True)
def _SendBinaryAndConfig2Worker(
addr, oneflow_worker_path, env_proto_path, run_dir, scp_binary, ssh_port
):
ssh_port_arg = " -p {} ".format(ssh_port)
scp_port_arg = " -P {} ".format(ssh_port)
_SystemCall(
"ssh-copy-id {} -f ".format(ssh_port_arg) + getpass.getuser() + "@" + addr
)
ssh_prefix = "ssh {}".format(ssh_port_arg) + getpass.getuser() + "@" + addr + " "
remote_file_prefix = " " + getpass.getuser() + "@" + addr + ":"
assert run_dir != ""
_SystemCall(ssh_prefix + '"mkdir -p ' + run_dir + '"')
if scp_binary:
_SystemCall(
"scp {}".format(scp_port_arg)
+ oneflow_worker_path
+ remote_file_prefix
+ run_dir
+ "/oneflow_worker"
)
_SystemCall(
"scp {}".format(scp_port_arg)
+ env_proto_path
+ remote_file_prefix
+ run_dir
+ "/env.proto"
)
oneflow_libibverbs_path = os.getenv("ONEFLOW_LIBIBVERBS_PATH")
libibverbs_env_str = ""
if oneflow_libibverbs_path:
libibverbs_env_str = "ONEFLOW_LIBIBVERBS_PATH=" + oneflow_libibverbs_path + " "
oneflow_cmd = (
'"cd '
+ run_dir
+ "; "
+ libibverbs_env_str
+ "nohup ./oneflow_worker -logtostderr=0 -log_dir=./log -v=0 -logbuflevel=-1 "
+ "-env_proto=./env.proto "
+ ' 1>/dev/null 2>&1 </dev/null & "'
)
_SystemCall(ssh_prefix + oneflow_cmd)
proc = subprocess.Popen(
ssh_prefix + "ps aux",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
shell=True,
)
outs, errs = proc.communicate(timeout=5)
print(outs)
assert "oneflow_worker" in str(outs), "fail to start oneflow_worker"
print("oneflow worker initialized:", addr, flush=True)
def _SystemCall(cmd):
print(cmd, flush=True)
subprocess.check_call(cmd, shell=True)
_temp_run_dir = ""
| [
"oneflow.core.job.env_pb2.EnvProto",
"oneflow.python.oneflow_export.oneflow_export"
] | [((1006, 1046), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""deprecated.init_worker"""'], {}), "('deprecated.init_worker')\n", (1020, 1046), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((3860, 3902), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""deprecated.delete_worker"""'], {}), "('deprecated.delete_worker')\n", (3874, 3902), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((4733, 4788), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""deprecated.delete_worker_by_bootstrap"""'], {}), "('deprecated.delete_worker_by_bootstrap')\n", (4747, 4788), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((5705, 5764), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""deprecated.delete_worker_of_multi_process"""'], {}), "('deprecated.delete_worker_of_multi_process')\n", (5719, 5764), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((1490, 1521), 'os.getenv', 'os.getenv', (['"""ONEFLOW_WORKER_BIN"""'], {}), "('ONEFLOW_WORKER_BIN')\n", (1499, 1521), False, 'import os\n'), ((1613, 1648), 'os.path.isfile', 'os.path.isfile', (['oneflow_worker_path'], {}), '(oneflow_worker_path)\n', (1627, 1648), False, 'import os\n'), ((5850, 5886), 'os.getenv', 'os.getenv', (['"""ONEFLOW_WORKER_KEEP_LOG"""'], {}), "('ONEFLOW_WORKER_KEEP_LOG')\n", (5859, 5886), False, 'import os\n'), ((7029, 7065), 'os.getenv', 'os.getenv', (['"""ONEFLOW_LIBIBVERBS_PATH"""'], {}), "('ONEFLOW_LIBIBVERBS_PATH')\n", (7038, 7065), False, 'import os\n'), ((7538, 7660), 'subprocess.Popen', 'subprocess.Popen', (["(ssh_prefix + 'ps aux')"], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE', 'encoding': '"""utf-8"""', 'shell': '(True)'}), "(ssh_prefix + 'ps aux', stdout=subprocess.PIPE, stderr=\n subprocess.PIPE, encoding='utf-8', shell=True)\n", (7554, 7660), False, 'import subprocess\n'), ((7951, 7989), 'subprocess.check_call', 'subprocess.check_call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (7972, 7989), False, 'import subprocess\n'), ((2102, 2129), 'os.path.expanduser', 'os.path.expanduser', (['run_dir'], {}), '(run_dir)\n', (2120, 2129), False, 'import os\n'), ((2186, 2218), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'delete': '(False)'}), '(delete=False)\n', (2204, 2218), False, 'from tempfile import NamedTemporaryFile\n'), ((2815, 2839), 'os.remove', 'os.remove', (['env_file.name'], {}), '(env_file.name)\n', (2824, 2839), False, 'import os\n'), ((2877, 2887), 'oneflow.core.job.env_pb2.EnvProto', 'EnvProto', ([], {}), '()\n', (2885, 2887), False, 'from oneflow.core.job.env_pb2 import EnvProto\n'), ((4449, 4485), 'os.getenv', 'os.getenv', (['"""ONEFLOW_WORKER_KEEP_LOG"""'], {}), "('ONEFLOW_WORKER_KEEP_LOG')\n", (4458, 4485), False, 'import os\n'), ((5407, 5443), 'os.getenv', 'os.getenv', (['"""ONEFLOW_WORKER_KEEP_LOG"""'], {}), "('ONEFLOW_WORKER_KEEP_LOG')\n", (5416, 5443), False, 'import os\n'), ((5975, 6004), 'os.system', 'os.system', (["('rm -r ' + run_dir)"], {}), "('rm -r ' + run_dir)\n", (5984, 6004), False, 'import os\n'), ((2000, 2017), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (2009, 2017), False, 'import os\n'), ((3305, 3337), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'delete': '(False)'}), '(delete=False)\n', (3323, 3337), False, 'from tempfile import NamedTemporaryFile\n'), ((3832, 3856), 'os.remove', 'os.remove', (['env_file.name'], {}), '(env_file.name)\n', (3841, 3856), False, 'import os\n'), ((1909, 1926), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (1918, 1926), False, 'import os\n'), ((1952, 1964), 'uuid.uuid1', 'uuid.uuid1', ([], {}), '()\n', (1962, 1964), False, 'import uuid\n'), ((2369, 2401), 'google.protobuf.text_format.MessageToString', 'pbtxt.MessageToString', (['env_proto'], {}), '(env_proto)\n', (2390, 2401), True, 'import google.protobuf.text_format as pbtxt\n'), ((3511, 3550), 'google.protobuf.text_format.MessageToString', 'pbtxt.MessageToString', (['worker_env_proto'], {}), '(worker_env_proto)\n', (3532, 3550), True, 'import google.protobuf.text_format as pbtxt\n'), ((6355, 6372), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (6370, 6372), False, 'import getpass\n'), ((6441, 6458), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (6456, 6458), False, 'import getpass\n'), ((6509, 6526), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (6524, 6526), False, 'import getpass\n'), ((2285, 2317), 'google.protobuf.text_format.MessageToString', 'pbtxt.MessageToString', (['env_proto'], {}), '(env_proto)\n', (2306, 2317), True, 'import google.protobuf.text_format as pbtxt\n'), ((4347, 4364), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (4362, 4364), False, 'import getpass\n'), ((5298, 5315), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (5313, 5315), False, 'import getpass\n'), ((3412, 3451), 'google.protobuf.text_format.MessageToString', 'pbtxt.MessageToString', (['worker_env_proto'], {}), '(worker_env_proto)\n', (3433, 3451), True, 'import google.protobuf.text_format as pbtxt\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 as flow
from oneflow.framework.tensor import register_tensor_op
def _tensor_to(input, device, dtype, copy=False):
assert input.is_local
device = device or input.device
assert isinstance(device, flow.device), f"Invalid device param: {device}"
dtype = dtype or input.dtype
assert isinstance(dtype, flow.dtype), f"Invalid dtype param: {dtype}"
ret = input
copy_happened = False
if device != ret.device:
ret = flow.F.copy(ret, device_type=device.type, device_id=device.index)
copy_happened = True
if dtype != ret.dtype:
ret = flow.F.cast(ret, dtype=dtype)
copy_happened = True
if copy and not copy_happened:
ret = flow.F.copy(ret, device_type=ret.device.type, device_id=ret.device.index)
return ret
def _consistent_tensor_to(input, device_type, dtype):
assert input.is_consistent
# TODO(zwx): support lazy check_meta_consistency
# input.check_meta_consistency()
device_type = device_type or input.placement.device_type
assert isinstance(device_type, str)
dtype = dtype or input.dtype
assert isinstance(dtype, flow.dtype)
if device_type == input.placement.device_type and dtype == input.dtype:
return input
if input.is_lazy:
return _lazy_consistent_tensor_to(input, device_type, dtype)
else:
return _eager_consistent_tensor_to(input, device_type, dtype)
def _lazy_consistent_tensor_to(input, device_type, dtype):
ret = input
if dtype != ret.dtype:
ret = flow.F.cast(ret, dtype=dtype)
if device_type != ret.placement.device_type:
ret = flow.F.copy(ret, device_type=device_type, device_id=0)
return ret
def _eager_consistent_tensor_to(input, device_type, dtype):
input.check_meta_consistency()
if device_type == input.placement.device_type and dtype != input.dtype:
return flow.F.cast(input, dtype=dtype)
device = flow.device(device_type)
placement = flow._oneflow_internal._ReplacePlacementDeviceTag(
input.placement, device_type
)
sbp = input.sbp
local_input = input.to_local()
local_output = _tensor_to(local_input, device, dtype, False)
return local_output.to_consistent(placement=placement, sbp=sbp)
def _safe_get(list, index, default):
if index < len(list) and index >= -len(list):
return list[index]
else:
return default
def _parse_args(*args, **kwargs):
device = None
dtype = None
copy = False
# parse params from args
if len(args) > 0:
first_arg = args[0]
if isinstance(first_arg, flow.Tensor):
# args format is (another_tensor, copy=False)
device = first_arg.device
dtype = first_arg.dtype
copy = _safe_get(args, 1, False)
elif isinstance(first_arg, flow.dtype):
# args format is (dtype, copy=False)
device = None
dtype = first_arg
copy = _safe_get(args, 1, False)
elif isinstance(first_arg, flow.device):
# args format is (flow.device, dtype=None, copy=False)
device = first_arg
dtype = _safe_get(args, 1, None)
copy = _safe_get(args, 2, False)
elif isinstance(first_arg, str):
# args format is (device_str, dtype=None, copy=False)
device = first_arg
dtype = _safe_get(args, 1, None)
copy = _safe_get(args, 2, False)
else:
raise TypeError(f"to() received invalid args {args}")
# parse params from kwargs
device = kwargs.get("device", device)
dtype = kwargs.get("dtype", dtype)
copy = kwargs.get("copy", copy)
return device, dtype, copy
@register_tensor_op("to")
def to_op(input, *args, **kwargs):
"""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
"""
device, dtype, copy = _parse_args(*args, **kwargs)
if not isinstance(dtype, flow.dtype) and dtype is not None:
raise TypeError("Invalid dtype param received: {dtype}")
if not isinstance(copy, bool):
raise TypeError("Invalid copy param received: {copy}")
if input.is_consistent:
if device is not None and device not in ("cuda", "cpu"):
raise TypeError(
"A consistent tensor can only call to() with device_str_without_id, "
'e.g. to("cuda") or to("cpu"), '
f"but device param {device} has been received."
)
if copy is True:
raise TypeError("A consistent tensor do not support to(copy=True)")
return _consistent_tensor_to(input, device, dtype)
else:
if isinstance(device, str):
device = flow.device(device)
return _tensor_to(input, device, dtype, copy)
if __name__ == "__main__":
import doctest
doctest.testmod(raise_on_error=True)
| [
"oneflow.framework.tensor.register_tensor_op",
"oneflow.F.copy",
"oneflow.device",
"oneflow.F.cast",
"oneflow._oneflow_internal._ReplacePlacementDeviceTag"
] | [((4326, 4350), 'oneflow.framework.tensor.register_tensor_op', 'register_tensor_op', (['"""to"""'], {}), "('to')\n", (4344, 4350), False, 'from oneflow.framework.tensor import register_tensor_op\n'), ((2534, 2558), 'oneflow.device', 'flow.device', (['device_type'], {}), '(device_type)\n', (2545, 2558), True, 'import oneflow as flow\n'), ((2575, 2654), 'oneflow._oneflow_internal._ReplacePlacementDeviceTag', 'flow._oneflow_internal._ReplacePlacementDeviceTag', (['input.placement', 'device_type'], {}), '(input.placement, device_type)\n', (2624, 2654), True, 'import oneflow as flow\n'), ((6376, 6412), 'doctest.testmod', 'doctest.testmod', ([], {'raise_on_error': '(True)'}), '(raise_on_error=True)\n', (6391, 6412), False, 'import doctest\n'), ((1055, 1120), 'oneflow.F.copy', 'flow.F.copy', (['ret'], {'device_type': 'device.type', 'device_id': 'device.index'}), '(ret, device_type=device.type, device_id=device.index)\n', (1066, 1120), True, 'import oneflow as flow\n'), ((1192, 1221), 'oneflow.F.cast', 'flow.F.cast', (['ret'], {'dtype': 'dtype'}), '(ret, dtype=dtype)\n', (1203, 1221), True, 'import oneflow as flow\n'), ((1301, 1374), 'oneflow.F.copy', 'flow.F.copy', (['ret'], {'device_type': 'ret.device.type', 'device_id': 'ret.device.index'}), '(ret, device_type=ret.device.type, device_id=ret.device.index)\n', (1312, 1374), True, 'import oneflow as flow\n'), ((2134, 2163), 'oneflow.F.cast', 'flow.F.cast', (['ret'], {'dtype': 'dtype'}), '(ret, dtype=dtype)\n', (2145, 2163), True, 'import oneflow as flow\n'), ((2228, 2282), 'oneflow.F.copy', 'flow.F.copy', (['ret'], {'device_type': 'device_type', 'device_id': '(0)'}), '(ret, device_type=device_type, device_id=0)\n', (2239, 2282), True, 'import oneflow as flow\n'), ((2488, 2519), 'oneflow.F.cast', 'flow.F.cast', (['input'], {'dtype': 'dtype'}), '(input, dtype=dtype)\n', (2499, 2519), True, 'import oneflow as flow\n'), ((6248, 6267), 'oneflow.device', 'flow.device', (['device'], {}), '(device)\n', (6259, 6267), True, 'import oneflow as flow\n')] |
import unittest
from collections import OrderedDict
import math
import numpy as np
from numpy.lib.arraysetops import union1d
import oneflow as flow
from torch._C import dtype
from test_utils import GenArgDict, GenArgList
from flowvision.loss.cross_entropy import (
SoftTargetCrossEntropy,
LabelSmoothingCrossEntropy,
)
def _gather_np(x, dim, index):
"""
Gathers values along an axis specified by ``dim``.
For a 3-D tensor the output is specified by:
out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0
out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1
out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2
Parameters
----------
dim:
The axis along which to index
index:
A tensor of indices of elements to gather
Returns
-------
Output Tensor
"""
idx_xsection_shape = index.shape[:dim] + index.shape[dim + 1 :]
self_xsection_shape = x.shape[:dim] + x.shape[dim + 1 :]
if idx_xsection_shape != self_xsection_shape:
raise ValueError(
"Except for dimension "
+ str(dim)
+ ", all dimensions of index and self should be the same size"
)
if index.dtype != np.dtype("int_"):
raise TypeError("The values of index must be integers")
data_swaped = np.swapaxes(x, 0, dim)
index_swaped = np.swapaxes(index, 0, dim)
gathered = np.choose(index_swaped, data_swaped)
return np.swapaxes(gathered, 0, dim)
def _softmax_np(x, dim):
return np.exp(x) / np.sum(np.exp(x), axis=dim, keepdims=True)
def _label_smooth_np(x, target, smoothing=0.1):
confidence = 1.0 - smoothing
probs = _softmax_np(x, dim=-1)
logprobs = np.ma.log(probs)
nll_loss = -_gather_np(logprobs, 1, np.expand_dims(target, axis=1))
nll_loss = np.squeeze(nll_loss, axis=1)
smooth_loss = -np.mean(logprobs, axis=-1)
loss = confidence * nll_loss + smoothing * smooth_loss
return np.mean(loss)
def _test_label_smooth(test_case, shape, device, smoothing):
np_predict = np.random.rand(*shape)
# TODO: build a solid label to fit all the situation
np_label = np.arange(0, len(shape))
of_predict = flow.tensor(np_predict, dtype=flow.float32, device=flow.device(device))
of_label = flow.tensor(np_label, dtype=flow.int64, device=flow.device(device))
of_label_smooth_cross_entropy = LabelSmoothingCrossEntropy(smoothing)
np_smooth_loss = _label_smooth_np(np_predict, np_label, smoothing)
of_smooth_loss = of_label_smooth_cross_entropy(of_predict, of_label)
test_case.assertTrue(
np.allclose(np_smooth_loss, of_smooth_loss.numpy(), 1e-4, 1e-4, equal_nan=True)
)
class TestLabelSmooth(unittest.TestCase):
def test_label_smooth(test_case):
arg_dict = OrderedDict()
arg_dict["shape"] = [(2, 3)]
arg_dict["device"] = ["cpu", "cuda"]
arg_dict["smoothing"] = [0.1, 0.2, 0.3, 0.5]
for arg in GenArgList(arg_dict):
_test_label_smooth(test_case, *arg)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.device"
] | [((1333, 1355), 'numpy.swapaxes', 'np.swapaxes', (['x', '(0)', 'dim'], {}), '(x, 0, dim)\n', (1344, 1355), True, 'import numpy as np\n'), ((1375, 1401), 'numpy.swapaxes', 'np.swapaxes', (['index', '(0)', 'dim'], {}), '(index, 0, dim)\n', (1386, 1401), True, 'import numpy as np\n'), ((1417, 1453), 'numpy.choose', 'np.choose', (['index_swaped', 'data_swaped'], {}), '(index_swaped, data_swaped)\n', (1426, 1453), True, 'import numpy as np\n'), ((1465, 1494), 'numpy.swapaxes', 'np.swapaxes', (['gathered', '(0)', 'dim'], {}), '(gathered, 0, dim)\n', (1476, 1494), True, 'import numpy as np\n'), ((1721, 1737), 'numpy.ma.log', 'np.ma.log', (['probs'], {}), '(probs)\n', (1730, 1737), True, 'import numpy as np\n'), ((1825, 1853), 'numpy.squeeze', 'np.squeeze', (['nll_loss'], {'axis': '(1)'}), '(nll_loss, axis=1)\n', (1835, 1853), True, 'import numpy as np\n'), ((1970, 1983), 'numpy.mean', 'np.mean', (['loss'], {}), '(loss)\n', (1977, 1983), True, 'import numpy as np\n'), ((2064, 2086), 'numpy.random.rand', 'np.random.rand', (['*shape'], {}), '(*shape)\n', (2078, 2086), True, 'import numpy as np\n'), ((2392, 2429), 'flowvision.loss.cross_entropy.LabelSmoothingCrossEntropy', 'LabelSmoothingCrossEntropy', (['smoothing'], {}), '(smoothing)\n', (2418, 2429), False, 'from flowvision.loss.cross_entropy import SoftTargetCrossEntropy, LabelSmoothingCrossEntropy\n'), ((3066, 3081), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3079, 3081), False, 'import unittest\n'), ((1233, 1249), 'numpy.dtype', 'np.dtype', (['"""int_"""'], {}), "('int_')\n", (1241, 1249), True, 'import numpy as np\n'), ((1533, 1542), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (1539, 1542), True, 'import numpy as np\n'), ((1873, 1899), 'numpy.mean', 'np.mean', (['logprobs'], {'axis': '(-1)'}), '(logprobs, axis=-1)\n', (1880, 1899), True, 'import numpy as np\n'), ((2795, 2808), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2806, 2808), False, 'from collections import OrderedDict\n'), ((2963, 2983), 'test_utils.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (2973, 2983), False, 'from test_utils import GenArgDict, GenArgList\n'), ((1552, 1561), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (1558, 1561), True, 'import numpy as np\n'), ((1778, 1808), 'numpy.expand_dims', 'np.expand_dims', (['target'], {'axis': '(1)'}), '(target, axis=1)\n', (1792, 1808), True, 'import numpy as np\n'), ((2252, 2271), 'oneflow.device', 'flow.device', (['device'], {}), '(device)\n', (2263, 2271), True, 'import oneflow as flow\n'), ((2335, 2354), 'oneflow.device', 'flow.device', (['device'], {}), '(device)\n', (2346, 2354), True, 'import oneflow as flow\n')] |
import os
import numpy as np
import argparse
from datetime import datetime
import cv2
import random
import math
import oneflow as flow
import oneflow.typing as tp
import networks
import image_pool
def random_crop(image, crop_height, crop_width):
max_x = image.shape[1] - crop_width
max_y = image.shape[0] - crop_height
x = np.random.randint(0, max_x)
y = np.random.randint(0, max_y)
crop = image[y: y + crop_height, x: x + crop_width]
return crop
def load_image2ndarray(image_path,
resize_and_crop = True,
load_size = 286,
crop_size = 256):
im = cv2.imread(image_path)
if resize_and_crop:
im = cv2.resize(im, (load_size, load_size), interpolation = cv2.INTER_CUBIC)
im = random_crop(im, crop_size, crop_size)
else:
im = cv2.resize(im, (crop_size, crop_size), interpolation = cv2.INTER_CUBIC)
im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
im = np.transpose(im, (2, 0, 1))
im = ((im.astype(np.float32) / 255.0) - 0.5) / 0.5
im = np.expand_dims(im, axis=0)
return np.ascontiguousarray(im, 'float32')
def ndarray2image(im):
im = np.squeeze(im)
im = (np.transpose(im, (1, 2, 0)) + 1) / 2.0 * 255.0
im = cv2.cvtColor(np.float32(im), cv2.COLOR_RGB2BGR)
return im.astype(np.uint8)
def get_train_config():
func_config = flow.FunctionConfig()
func_config.default_data_type(flow.float32)
func_config.default_logical_view(flow.scope.consistent_view())
return func_config
def main(args):
@flow.global_function("train", get_train_config())
def TrainDiscriminator(
real_A: tp.Numpy.Placeholder((1, 3, args.crop_size, args.crop_size), dtype = flow.float32),
fake_A: tp.Numpy.Placeholder((1, 3, args.crop_size, args.crop_size), dtype = flow.float32),
real_B: tp.Numpy.Placeholder((1, 3, args.crop_size, args.crop_size), dtype = flow.float32),
fake_B: tp.Numpy.Placeholder((1, 3, args.crop_size, args.crop_size), dtype = flow.float32)):
with flow.scope.placement("gpu", "0:0-0"):
# Calculate GAN loss for discriminator D_A
# Real
pred_real_B = networks.define_D(real_B, "netD_A", ndf = args.ndf, n_layers_D = 3, trainable = True, reuse = True)
loss_D_A_real = networks.GANLoss(pred_real_B, True)
# Fake
pred_fake_B = networks.define_D(fake_B, "netD_A", ndf = args.ndf, n_layers_D = 3, trainable = True, reuse = True)
loss_D_A_fake = networks.GANLoss(pred_fake_B, False)
# Combined loss and calculate gradients
loss_D_A = (loss_D_A_real + loss_D_A_fake) * 0.5
# Calculate GAN loss for discriminator D_B
# Real
pred_real_A = networks.define_D(real_A, "netD_B", ndf = args.ndf, n_layers_D = 3, trainable = True, reuse = True)
loss_D_B_real = networks.GANLoss(pred_real_A, True)
# Fake
pred_fake_A = networks.define_D(fake_A, "netD_B", ndf = args.ndf, n_layers_D = 3, trainable = True, reuse = True)
loss_D_B_fake = networks.GANLoss(pred_fake_A, False)
# Combined loss and calculate gradients
loss_D_B = (loss_D_B_real + loss_D_B_fake) * 0.5
loss_D = loss_D_A + loss_D_B
flow.optimizer.Adam(flow.optimizer.PiecewiseConstantScheduler([], [args.learning_rate]), beta1 = 0.5).minimize(loss_D)
return loss_D
@flow.global_function("train", get_train_config())
def TrainGenerator(
real_A: tp.Numpy.Placeholder((1, 3, args.crop_size, args.crop_size), dtype = flow.float32),
real_B: tp.Numpy.Placeholder((1, 3, args.crop_size, args.crop_size), dtype = flow.float32)):
with flow.scope.placement("gpu", "0:0-0"):
# G_A(A)
fake_B = networks.define_G(real_A, "netG_A", ngf = args.ngf, n_blocks = 9, trainable = True, reuse = True)
# G_B(G_A(A))
rec_A = networks.define_G(fake_B, "netG_B", ngf = args.ngf, n_blocks = 9, trainable = True, reuse = True)
# G_B(B)
fake_A = networks.define_G(real_B, "netG_B", ngf = args.ngf, n_blocks = 9, trainable = True, reuse = True)
# G_A(G_B(B))
rec_B = networks.define_G(fake_A, "netG_A", ngf = args.ngf, n_blocks = 9, trainable = True, reuse = True)
# Identity loss
# G_A should be identity if real_B is fed: ||G_A(B) - B||
idt_A = networks.define_G(real_B, "netG_A", ngf = args.ngf, n_blocks = 9, trainable = True, reuse = True)
loss_idt_A = networks.L1Loss(idt_A - real_B) * args.lambda_B * args.lambda_identity
# G_B should be identity if real_A is fed: ||G_B(A) - A||
idt_B = networks.define_G(real_A, "netG_B", ngf = args.ngf, n_blocks = 9, trainable = True, reuse = True)
loss_idt_B = networks.L1Loss(idt_B - real_A) * args.lambda_A * args.lambda_identity
# GAN loss D_A(G_A(A))
netD_A_out = networks.define_D(fake_B, "netD_A", ndf = args.ndf, n_layers_D = 3, trainable = False, reuse = True)
loss_G_A = networks.GANLoss(netD_A_out, True)
# GAN loss D_B(G_B(B))
netD_B_out = networks.define_D(fake_A, "netD_B", ndf = args.ndf, n_layers_D = 3, trainable = False, reuse = True)
loss_G_B = networks.GANLoss(netD_B_out, True)
# Forward cycle loss || G_B(G_A(A)) - A||
loss_cycle_A = networks.L1Loss(rec_A - real_A) * args.lambda_A
# Backward cycle loss || G_A(G_B(B)) - B||
loss_cycle_B = networks.L1Loss(rec_B - real_B) * args.lambda_B
# combined loss and calculate gradients
loss_G = loss_G_A + loss_G_B + loss_cycle_A + loss_cycle_B + loss_idt_A + loss_idt_B
flow.optimizer.Adam(flow.optimizer.PiecewiseConstantScheduler([], [args.learning_rate]), beta1 = 0.5).minimize(loss_G)
return fake_B, rec_A, fake_A, rec_B, loss_G
check_point = flow.train.CheckPoint()
if args.checkpoint_load_dir != "":
check_point.load(args.checkpoint_load_dir)
else:
check_point.init()
datasetA = os.listdir(args.datasetA_path)
datasetB = os.listdir(args.datasetB_path)
datasetA_num = len(datasetA)
datasetB_num = len(datasetB)
print("dataset A size: %d" % datasetA_num)
print("dataset B size: %d" % datasetB_num)
train_iters = min(datasetA_num, datasetB_num)
fake_A_pool = image_pool.ImagePool(50) # create image buffer to store previously generated images
fake_B_pool = image_pool.ImagePool(50) # create image buffer to store previously generated images
begin_epoch = 0
for e in range(args.train_epoch):
random.shuffle(datasetA)
random.shuffle(datasetB)
for i in range(train_iters):
real_A = load_image2ndarray("%s/%s" % (args.datasetA_path, datasetA[i]), args.resize_and_crop, args.load_size, args.crop_size)
real_B = load_image2ndarray("%s/%s" % (args.datasetB_path, datasetB[i]), args.resize_and_crop, args.load_size, args.crop_size)
fake_B, rec_A, fake_A, rec_B, loss_G = TrainGenerator(real_A, real_B).get()
fake_B = fake_B.numpy()
fake_A = fake_A.numpy()
fake_BB = fake_B_pool.query(fake_B)
fake_AA = fake_A_pool.query(fake_A)
loss_D = TrainDiscriminator(real_A, fake_AA, real_B, fake_BB).get()
if i % 20 == 0:
imageA = ndarray2image(real_A)
imageB = ndarray2image(real_B)
image_fake_B = ndarray2image(fake_B)
image_rec_A = ndarray2image(rec_A.numpy())
image_fake_A = ndarray2image(fake_A)
image_rec_B = ndarray2image(rec_B.numpy())
result1 = np.concatenate((imageA, image_fake_B, image_rec_A), axis = 1)
result2 = np.concatenate((imageB, image_fake_A, image_rec_B), axis = 1)
result = np.concatenate((result1, result2), axis = 0)
cv2.imwrite(args.save_tmp_image_path, result)
cur_g_loss = loss_G.numpy().mean()
cur_d_loss = loss_D.numpy().mean()
print("epoch: %d, iter: %d, gloss : %f, dloss : %f" % (e + begin_epoch, i, cur_g_loss, cur_d_loss))
if i % 200 == 0:
check_point.save("%s/epoch_%d_iter_%d_gloss_%f_dloss_%f" % \
(args.checkpoint_save_dir, e + begin_epoch, i, cur_g_loss, cur_d_loss))
def get_parser(parser = None):
parser = argparse.ArgumentParser("flags for cycle gan")
parser.add_argument("--datasetA_path", type = str, default = "", help = "dataset A path")
parser.add_argument("--datasetB_path", type = str, default = "", help = "dataset B path")
# image preprocess
parser.add_argument("--crop_size", type = int, default = 286)
parser.add_argument("--load_size", type = int, default = 256)
parser.add_argument("--resize_and_crop", type = bool, default = True)
# checkpoint
parser.add_argument("--checkpoint_load_dir", type = str, default = "", help = "load previous saved checkpoint from")
parser.add_argument("--checkpoint_save_dir", type = str, default = "./checkpoints", help = "save checkpoint to")
parser.add_argument("--save_tmp_image_path", type = str, default = 'train_temp_image.jpg', help = "image path")
# hyper-parameters
parser.add_argument("--train_epoch", type = int, default = 300)
parser.add_argument("--learning_rate", type = float, default = 0.0002)
parser.add_argument('--lambda_A', type=float, default = 10.0, help = 'weight for cycle loss (A -> B -> A)')
parser.add_argument('--lambda_B', type=float, default = 10.0, help = 'weight for cycle loss (B -> A -> B)')
parser.add_argument('--lambda_identity', type=float, default = 0.5, help='use identity mapping. Setting lambda_identity other than 0 has an effect of scaling the weight of the identity mapping loss. For example, if the weight of the identity loss should be 10 times smaller than the weight of the reconstruction loss, please set lambda_identity = 0.1')
parser.add_argument('--ngf', type = int, default = 64, help = '# of gen filters in the last conv layer')
parser.add_argument('--ndf', type = int, default = 64, help = '# of discrim filters in the first conv layer')
return parser
if __name__ == '__main__':
parser = get_parser()
args = parser.parse_args()
main(args)
| [
"oneflow.FunctionConfig",
"oneflow.scope.consistent_view",
"oneflow.optimizer.PiecewiseConstantScheduler",
"oneflow.typing.Numpy.Placeholder",
"oneflow.train.CheckPoint",
"oneflow.scope.placement"
] | [((340, 367), 'numpy.random.randint', 'np.random.randint', (['(0)', 'max_x'], {}), '(0, max_x)\n', (357, 367), True, 'import numpy as np\n'), ((376, 403), 'numpy.random.randint', 'np.random.randint', (['(0)', 'max_y'], {}), '(0, max_y)\n', (393, 403), True, 'import numpy as np\n'), ((652, 674), 'cv2.imread', 'cv2.imread', (['image_path'], {}), '(image_path)\n', (662, 674), False, 'import cv2\n'), ((945, 980), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2RGB'], {}), '(im, cv2.COLOR_BGR2RGB)\n', (957, 980), False, 'import cv2\n'), ((990, 1017), 'numpy.transpose', 'np.transpose', (['im', '(2, 0, 1)'], {}), '(im, (2, 0, 1))\n', (1002, 1017), True, 'import numpy as np\n'), ((1082, 1108), 'numpy.expand_dims', 'np.expand_dims', (['im'], {'axis': '(0)'}), '(im, axis=0)\n', (1096, 1108), True, 'import numpy as np\n'), ((1120, 1155), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['im', '"""float32"""'], {}), "(im, 'float32')\n", (1140, 1155), True, 'import numpy as np\n'), ((1189, 1203), 'numpy.squeeze', 'np.squeeze', (['im'], {}), '(im)\n', (1199, 1203), True, 'import numpy as np\n'), ((1392, 1413), 'oneflow.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (1411, 1413), True, 'import oneflow as flow\n'), ((6028, 6051), 'oneflow.train.CheckPoint', 'flow.train.CheckPoint', ([], {}), '()\n', (6049, 6051), True, 'import oneflow as flow\n'), ((6195, 6225), 'os.listdir', 'os.listdir', (['args.datasetA_path'], {}), '(args.datasetA_path)\n', (6205, 6225), False, 'import os\n'), ((6241, 6271), 'os.listdir', 'os.listdir', (['args.datasetB_path'], {}), '(args.datasetB_path)\n', (6251, 6271), False, 'import os\n'), ((6503, 6527), 'image_pool.ImagePool', 'image_pool.ImagePool', (['(50)'], {}), '(50)\n', (6523, 6527), False, 'import image_pool\n'), ((6606, 6630), 'image_pool.ImagePool', 'image_pool.ImagePool', (['(50)'], {}), '(50)\n', (6626, 6630), False, 'import image_pool\n'), ((8638, 8684), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""flags for cycle gan"""'], {}), "('flags for cycle gan')\n", (8661, 8684), False, 'import argparse\n'), ((713, 782), 'cv2.resize', 'cv2.resize', (['im', '(load_size, load_size)'], {'interpolation': 'cv2.INTER_CUBIC'}), '(im, (load_size, load_size), interpolation=cv2.INTER_CUBIC)\n', (723, 782), False, 'import cv2\n'), ((859, 928), 'cv2.resize', 'cv2.resize', (['im', '(crop_size, crop_size)'], {'interpolation': 'cv2.INTER_CUBIC'}), '(im, (crop_size, crop_size), interpolation=cv2.INTER_CUBIC)\n', (869, 928), False, 'import cv2\n'), ((1283, 1297), 'numpy.float32', 'np.float32', (['im'], {}), '(im)\n', (1293, 1297), True, 'import numpy as np\n'), ((1499, 1527), 'oneflow.scope.consistent_view', 'flow.scope.consistent_view', ([], {}), '()\n', (1525, 1527), True, 'import oneflow as flow\n'), ((6758, 6782), 'random.shuffle', 'random.shuffle', (['datasetA'], {}), '(datasetA)\n', (6772, 6782), False, 'import random\n'), ((6791, 6815), 'random.shuffle', 'random.shuffle', (['datasetB'], {}), '(datasetB)\n', (6805, 6815), False, 'import random\n'), ((1669, 1754), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(1, 3, args.crop_size, args.crop_size)'], {'dtype': 'flow.float32'}), '((1, 3, args.crop_size, args.crop_size), dtype=flow.float32\n )\n', (1689, 1754), True, 'import oneflow.typing as tp\n'), ((1769, 1854), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(1, 3, args.crop_size, args.crop_size)'], {'dtype': 'flow.float32'}), '((1, 3, args.crop_size, args.crop_size), dtype=flow.float32\n )\n', (1789, 1854), True, 'import oneflow.typing as tp\n'), ((1869, 1954), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(1, 3, args.crop_size, args.crop_size)'], {'dtype': 'flow.float32'}), '((1, 3, args.crop_size, args.crop_size), dtype=flow.float32\n )\n', (1889, 1954), True, 'import oneflow.typing as tp\n'), ((1969, 2054), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(1, 3, args.crop_size, args.crop_size)'], {'dtype': 'flow.float32'}), '((1, 3, args.crop_size, args.crop_size), dtype=flow.float32\n )\n', (1989, 2054), True, 'import oneflow.typing as tp\n'), ((2067, 2103), 'oneflow.scope.placement', 'flow.scope.placement', (['"""gpu"""', '"""0:0-0"""'], {}), "('gpu', '0:0-0')\n", (2087, 2103), True, 'import oneflow as flow\n'), ((2205, 2301), 'networks.define_D', 'networks.define_D', (['real_B', '"""netD_A"""'], {'ndf': 'args.ndf', 'n_layers_D': '(3)', 'trainable': '(True)', 'reuse': '(True)'}), "(real_B, 'netD_A', ndf=args.ndf, n_layers_D=3, trainable=\n True, reuse=True)\n", (2222, 2301), False, 'import networks\n'), ((2333, 2368), 'networks.GANLoss', 'networks.GANLoss', (['pred_real_B', '(True)'], {}), '(pred_real_B, True)\n', (2349, 2368), False, 'import networks\n'), ((2414, 2510), 'networks.define_D', 'networks.define_D', (['fake_B', '"""netD_A"""'], {'ndf': 'args.ndf', 'n_layers_D': '(3)', 'trainable': '(True)', 'reuse': '(True)'}), "(fake_B, 'netD_A', ndf=args.ndf, n_layers_D=3, trainable=\n True, reuse=True)\n", (2431, 2510), False, 'import networks\n'), ((2542, 2578), 'networks.GANLoss', 'networks.GANLoss', (['pred_fake_B', '(False)'], {}), '(pred_fake_B, False)\n', (2558, 2578), False, 'import networks\n'), ((2793, 2889), 'networks.define_D', 'networks.define_D', (['real_A', '"""netD_B"""'], {'ndf': 'args.ndf', 'n_layers_D': '(3)', 'trainable': '(True)', 'reuse': '(True)'}), "(real_A, 'netD_B', ndf=args.ndf, n_layers_D=3, trainable=\n True, reuse=True)\n", (2810, 2889), False, 'import networks\n'), ((2921, 2956), 'networks.GANLoss', 'networks.GANLoss', (['pred_real_A', '(True)'], {}), '(pred_real_A, True)\n', (2937, 2956), False, 'import networks\n'), ((3002, 3098), 'networks.define_D', 'networks.define_D', (['fake_A', '"""netD_B"""'], {'ndf': 'args.ndf', 'n_layers_D': '(3)', 'trainable': '(True)', 'reuse': '(True)'}), "(fake_A, 'netD_B', ndf=args.ndf, n_layers_D=3, trainable=\n True, reuse=True)\n", (3019, 3098), False, 'import networks\n'), ((3130, 3166), 'networks.GANLoss', 'networks.GANLoss', (['pred_fake_A', '(False)'], {}), '(pred_fake_A, False)\n', (3146, 3166), False, 'import networks\n'), ((3573, 3658), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(1, 3, args.crop_size, args.crop_size)'], {'dtype': 'flow.float32'}), '((1, 3, args.crop_size, args.crop_size), dtype=flow.float32\n )\n', (3593, 3658), True, 'import oneflow.typing as tp\n'), ((3673, 3758), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(1, 3, args.crop_size, args.crop_size)'], {'dtype': 'flow.float32'}), '((1, 3, args.crop_size, args.crop_size), dtype=flow.float32\n )\n', (3693, 3758), True, 'import oneflow.typing as tp\n'), ((3771, 3807), 'oneflow.scope.placement', 'flow.scope.placement', (['"""gpu"""', '"""0:0-0"""'], {}), "('gpu', '0:0-0')\n", (3791, 3807), True, 'import oneflow as flow\n'), ((3851, 3945), 'networks.define_G', 'networks.define_G', (['real_A', '"""netG_A"""'], {'ngf': 'args.ngf', 'n_blocks': '(9)', 'trainable': '(True)', 'reuse': '(True)'}), "(real_A, 'netG_A', ngf=args.ngf, n_blocks=9, trainable=\n True, reuse=True)\n", (3868, 3945), False, 'import networks\n'), ((3995, 4089), 'networks.define_G', 'networks.define_G', (['fake_B', '"""netG_B"""'], {'ngf': 'args.ngf', 'n_blocks': '(9)', 'trainable': '(True)', 'reuse': '(True)'}), "(fake_B, 'netG_B', ngf=args.ngf, n_blocks=9, trainable=\n True, reuse=True)\n", (4012, 4089), False, 'import networks\n'), ((4135, 4229), 'networks.define_G', 'networks.define_G', (['real_B', '"""netG_B"""'], {'ngf': 'args.ngf', 'n_blocks': '(9)', 'trainable': '(True)', 'reuse': '(True)'}), "(real_B, 'netG_B', ngf=args.ngf, n_blocks=9, trainable=\n True, reuse=True)\n", (4152, 4229), False, 'import networks\n'), ((4279, 4373), 'networks.define_G', 'networks.define_G', (['fake_A', '"""netG_A"""'], {'ngf': 'args.ngf', 'n_blocks': '(9)', 'trainable': '(True)', 'reuse': '(True)'}), "(fake_A, 'netG_A', ngf=args.ngf, n_blocks=9, trainable=\n True, reuse=True)\n", (4296, 4373), False, 'import networks\n'), ((4496, 4590), 'networks.define_G', 'networks.define_G', (['real_B', '"""netG_A"""'], {'ngf': 'args.ngf', 'n_blocks': '(9)', 'trainable': '(True)', 'reuse': '(True)'}), "(real_B, 'netG_A', ngf=args.ngf, n_blocks=9, trainable=\n True, reuse=True)\n", (4513, 4590), False, 'import networks\n'), ((4781, 4875), 'networks.define_G', 'networks.define_G', (['real_A', '"""netG_B"""'], {'ngf': 'args.ngf', 'n_blocks': '(9)', 'trainable': '(True)', 'reuse': '(True)'}), "(real_A, 'netG_B', ngf=args.ngf, n_blocks=9, trainable=\n True, reuse=True)\n", (4798, 4875), False, 'import networks\n'), ((5036, 5133), 'networks.define_D', 'networks.define_D', (['fake_B', '"""netD_A"""'], {'ndf': 'args.ndf', 'n_layers_D': '(3)', 'trainable': '(False)', 'reuse': '(True)'}), "(fake_B, 'netD_A', ndf=args.ndf, n_layers_D=3, trainable=\n False, reuse=True)\n", (5053, 5133), False, 'import networks\n'), ((5160, 5194), 'networks.GANLoss', 'networks.GANLoss', (['netD_A_out', '(True)'], {}), '(netD_A_out, True)\n', (5176, 5194), False, 'import networks\n'), ((5256, 5353), 'networks.define_D', 'networks.define_D', (['fake_A', '"""netD_B"""'], {'ndf': 'args.ndf', 'n_layers_D': '(3)', 'trainable': '(False)', 'reuse': '(True)'}), "(fake_A, 'netD_B', ndf=args.ndf, n_layers_D=3, trainable=\n False, reuse=True)\n", (5273, 5353), False, 'import networks\n'), ((5380, 5414), 'networks.GANLoss', 'networks.GANLoss', (['netD_B_out', '(True)'], {}), '(netD_B_out, True)\n', (5396, 5414), False, 'import networks\n'), ((1214, 1241), 'numpy.transpose', 'np.transpose', (['im', '(1, 2, 0)'], {}), '(im, (1, 2, 0))\n', (1226, 1241), True, 'import numpy as np\n'), ((5497, 5528), 'networks.L1Loss', 'networks.L1Loss', (['(rec_A - real_A)'], {}), '(rec_A - real_A)\n', (5512, 5528), False, 'import networks\n'), ((5627, 5658), 'networks.L1Loss', 'networks.L1Loss', (['(rec_B - real_B)'], {}), '(rec_B - real_B)\n', (5642, 5658), False, 'import networks\n'), ((7863, 7922), 'numpy.concatenate', 'np.concatenate', (['(imageA, image_fake_B, image_rec_A)'], {'axis': '(1)'}), '((imageA, image_fake_B, image_rec_A), axis=1)\n', (7877, 7922), True, 'import numpy as np\n'), ((7951, 8010), 'numpy.concatenate', 'np.concatenate', (['(imageB, image_fake_A, image_rec_B)'], {'axis': '(1)'}), '((imageB, image_fake_A, image_rec_B), axis=1)\n', (7965, 8010), True, 'import numpy as np\n'), ((8038, 8080), 'numpy.concatenate', 'np.concatenate', (['(result1, result2)'], {'axis': '(0)'}), '((result1, result2), axis=0)\n', (8052, 8080), True, 'import numpy as np\n'), ((8100, 8145), 'cv2.imwrite', 'cv2.imwrite', (['args.save_tmp_image_path', 'result'], {}), '(args.save_tmp_image_path, result)\n', (8111, 8145), False, 'import cv2\n'), ((4619, 4650), 'networks.L1Loss', 'networks.L1Loss', (['(idt_A - real_B)'], {}), '(idt_A - real_B)\n', (4634, 4650), False, 'import networks\n'), ((4904, 4935), 'networks.L1Loss', 'networks.L1Loss', (['(idt_B - real_A)'], {}), '(idt_B - real_A)\n', (4919, 4935), False, 'import networks\n'), ((3355, 3422), 'oneflow.optimizer.PiecewiseConstantScheduler', 'flow.optimizer.PiecewiseConstantScheduler', (['[]', '[args.learning_rate]'], {}), '([], [args.learning_rate])\n', (3396, 3422), True, 'import oneflow as flow\n'), ((5857, 5924), 'oneflow.optimizer.PiecewiseConstantScheduler', 'flow.optimizer.PiecewiseConstantScheduler', (['[]', '[args.learning_rate]'], {}), '([], [args.learning_rate])\n', (5898, 5924), True, 'import oneflow as flow\n')] |
"""
Modified from https://github.com/FrancescoSaverioZuppichini/glasses/blob/master/glasses/nn/regularization/__init__.py
"""
import oneflow as flow
import oneflow.nn as nn
import oneflow.nn.functional as F
from oneflow import Tensor
class DropBlock(nn.Module):
def __init__(self, block_size: int = 7, p: float = 0.5):
super(DropBlock, self).__init__()
self.block_size = block_size
self.p = p
def cal_gamma(self, x: Tensor):
gamma = (
self.p
* x.shape[-1] ** 2
/ (self.block_size ** 2 * (x.shape[-1] - self.block_size + 1) ** 2)
)
return gamma
def forward(self, x):
if self.training:
gamma = self.cal_gamma(x)
mask = flow.bernoulli(flow.ones_like(x) * gamma)
mask_block = 1 - F.max_pool2d(
mask,
kernel_size=(self.block_size, self.block_size),
stride=(1, 1),
padding=(self.block_size // 2, self.block_size // 2),
)
x = mask_block * x * (mask_block.numel() / mask_block.sum())
return x
| [
"oneflow.nn.functional.max_pool2d",
"oneflow.ones_like"
] | [((821, 961), 'oneflow.nn.functional.max_pool2d', 'F.max_pool2d', (['mask'], {'kernel_size': '(self.block_size, self.block_size)', 'stride': '(1, 1)', 'padding': '(self.block_size // 2, self.block_size // 2)'}), '(mask, kernel_size=(self.block_size, self.block_size), stride=(\n 1, 1), padding=(self.block_size // 2, self.block_size // 2))\n', (833, 961), True, 'import oneflow.nn.functional as F\n'), ((765, 782), 'oneflow.ones_like', 'flow.ones_like', (['x'], {}), '(x)\n', (779, 782), 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 unittest
import numpy as np
import oneflow.experimental as flow
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestEq(flow.unittest.TestCase):
def test_eq(test_case):
arr1 = np.array([2, 3, 4, 5,])
arr2 = np.array([2, 3, 4, 1])
input = flow.Tensor(arr1, dtype=flow.float32)
other = flow.Tensor(arr2, dtype=flow.float32)
of_out = flow.eq(input, other)
of_out2 = flow.equal(input, other)
np_out = np.equal(arr1, arr2)
test_case.assertTrue(np.array_equal(of_out.numpy(), np_out))
test_case.assertTrue(np.array_equal(of_out2.numpy(), np_out))
def test_eq_tensor_function(test_case):
arr1 = np.random.randint(1, 10, size=(2, 3, 4, 5))
arr2 = np.random.randint(1, 10, size=(2, 3, 4, 5))
input = flow.Tensor(arr1, dtype=flow.float32)
other = flow.Tensor(arr2, dtype=flow.float32)
of_out = input.eq(other)
np_out = np.equal(arr1, arr2)
test_case.assertTrue(np.array_equal(of_out.numpy(), np_out))
if __name__ == "__main__":
unittest.main()
| [
"oneflow.experimental.equal",
"oneflow.experimental.eq",
"oneflow.experimental.unittest.env.eager_execution_enabled",
"oneflow.experimental.Tensor"
] | [((1735, 1750), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1748, 1750), False, 'import unittest\n'), ((860, 882), 'numpy.array', 'np.array', (['[2, 3, 4, 5]'], {}), '([2, 3, 4, 5])\n', (868, 882), True, 'import numpy as np\n'), ((899, 921), 'numpy.array', 'np.array', (['[2, 3, 4, 1]'], {}), '([2, 3, 4, 1])\n', (907, 921), True, 'import numpy as np\n'), ((938, 975), 'oneflow.experimental.Tensor', 'flow.Tensor', (['arr1'], {'dtype': 'flow.float32'}), '(arr1, dtype=flow.float32)\n', (949, 975), True, 'import oneflow.experimental as flow\n'), ((992, 1029), 'oneflow.experimental.Tensor', 'flow.Tensor', (['arr2'], {'dtype': 'flow.float32'}), '(arr2, dtype=flow.float32)\n', (1003, 1029), True, 'import oneflow.experimental as flow\n'), ((1048, 1069), 'oneflow.experimental.eq', 'flow.eq', (['input', 'other'], {}), '(input, other)\n', (1055, 1069), True, 'import oneflow.experimental as flow\n'), ((1088, 1112), 'oneflow.experimental.equal', 'flow.equal', (['input', 'other'], {}), '(input, other)\n', (1098, 1112), True, 'import oneflow.experimental as flow\n'), ((1130, 1150), 'numpy.equal', 'np.equal', (['arr1', 'arr2'], {}), '(arr1, arr2)\n', (1138, 1150), True, 'import numpy as np\n'), ((1350, 1393), 'numpy.random.randint', 'np.random.randint', (['(1)', '(10)'], {'size': '(2, 3, 4, 5)'}), '(1, 10, size=(2, 3, 4, 5))\n', (1367, 1393), True, 'import numpy as np\n'), ((1409, 1452), 'numpy.random.randint', 'np.random.randint', (['(1)', '(10)'], {'size': '(2, 3, 4, 5)'}), '(1, 10, size=(2, 3, 4, 5))\n', (1426, 1452), True, 'import numpy as np\n'), ((1469, 1506), 'oneflow.experimental.Tensor', 'flow.Tensor', (['arr1'], {'dtype': 'flow.float32'}), '(arr1, dtype=flow.float32)\n', (1480, 1506), True, 'import oneflow.experimental as flow\n'), ((1523, 1560), 'oneflow.experimental.Tensor', 'flow.Tensor', (['arr2'], {'dtype': 'flow.float32'}), '(arr2, dtype=flow.float32)\n', (1534, 1560), True, 'import oneflow.experimental as flow\n'), ((1612, 1632), 'numpy.equal', 'np.equal', (['arr1', 'arr2'], {}), '(arr1, arr2)\n', (1620, 1632), True, 'import numpy as np\n'), ((690, 733), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (731, 733), 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 os
import random
import string
import struct
import tempfile
from collections import OrderedDict
import numpy as np
import oneflow as flow
import oneflow.core.record.record_pb2 as ofrecord
import six
from test_util import GenArgList
tmp = tempfile.mkdtemp()
def get_temp_dir():
return tmp
def int32_feature(value):
"""Wrapper for inserting int32 features into Example proto."""
if not isinstance(value, (list, tuple)):
value = [value]
return ofrecord.Feature(int32_list=ofrecord.Int32List(value=value))
def int64_feature(value):
if not isinstance(value, (list, tuple)):
value = [value]
return ofrecord.Feature(int64_list=ofrecord.Int64List(value=value))
def float_feature(value):
"""Wrapper for inserting float features into Example proto."""
if not isinstance(value, (list, tuple)):
value = [value]
return ofrecord.Feature(float_list=ofrecord.FloatList(value=value))
def double_feature(value):
"""Wrapper for inserting double features into Example proto."""
if not isinstance(value, (list, tuple)):
value = [value]
return ofrecord.Feature(double_list=ofrecord.DoubleList(value=value))
def bytes_feature(value):
if not isinstance(value, (list, tuple)):
value = [value]
if not six.PY2:
if isinstance(value[0], str):
value = [x.encode() for x in value]
return ofrecord.Feature(bytes_list=ofrecord.BytesList(value=value))
def random_int(N, b=32):
b -= 1
return [random.randint(-(2 ** b) + 1, 2 ** b - 1) for _ in range(N)]
def random_float(N):
return [random.random() for _ in range(N)]
def random_string(N):
return "".join(
random.choice(string.ascii_uppercase + string.digits) for _ in range(N)
)
# python version > 3.6
# return ''.join(random.choices(string.ascii_uppercase + string.digits, k=N))
def gen_example(length=32):
int32_list = random_int(length, 32)
int64_list = random_int(length, 64)
float_list = random_float(length)
bytes_list = random_string(length)
example = ofrecord.OFRecord(
feature={
"int32": int32_feature(int32_list),
"int64": int64_feature(int64_list),
"float": float_feature(float_list),
"double": double_feature(float_list),
"bytes": bytes_feature(bytes_list),
}
)
return example, int32_list, int64_list, float_list, bytes_list
def gen_ofrecord(num_examples, length, batch_size):
with open(os.path.join(get_temp_dir(), "part-0"), "wb") as f:
int32_data, int64_data, float_data, bytes_data = [], [], [], []
for i in range(num_examples):
example, int32_list, int64_list, float_list, bytes_list = gen_example(
length
)
l = example.ByteSize()
f.write(struct.pack("q", l))
f.write(example.SerializeToString())
int32_data.append(int32_list)
int64_data.append(int64_list)
float_data.append(float_list)
bytes_data.append(bytes_list)
int32_np = np.array(int32_data, dtype=np.int32).reshape(-1, batch_size, length)
int64_np = np.array(int64_data, dtype=np.int64).reshape(-1, batch_size, length)
float_np = np.array(float_data, dtype=np.float).reshape(-1, batch_size, length)
double_np = np.array(float_data, dtype=np.double).reshape(
-1, batch_size, length
)
return int32_np, int64_np, float_np, double_np, bytes_data
def _blob_conf(name, shape, dtype=flow.int32, codec=flow.data.RawCodec()):
return flow.data.BlobConf(name=name, shape=shape, dtype=dtype, codec=codec)
def decoder(data_dir, length, batch_size=1, data_part_num=1):
ofrecord = flow.data.ofrecord_reader(
data_dir, batch_size=batch_size, data_part_num=data_part_num
)
blob_int32 = flow.data.ofrecord_raw_decoder(
ofrecord, "int32", shape=(length,), dtype=flow.int32
)
blob_int64 = flow.data.ofrecord_raw_decoder(
ofrecord, "int64", shape=(length,), dtype=flow.int64
)
blob_float = flow.data.ofrecord_raw_decoder(
ofrecord, "float", shape=(length,), dtype=flow.float
)
blob_double = flow.data.ofrecord_raw_decoder(
ofrecord, "double", shape=(length,), dtype=flow.double
)
blob_bytes = flow.data.ofrecord_raw_decoder(
ofrecord, "bytes", shape=(1, length,), dtype=flow.int8
)
return {
"int32": blob_int32,
"int64": blob_int64,
"float": blob_float,
"double": blob_double,
"bytes": blob_bytes,
}
func_config = flow.FunctionConfig()
func_config.default_data_type(flow.float)
def test_ofrecord_decoder(test_case):
num_examples = 1000
batch_size = 100
assert num_examples % batch_size == 0
length = 64
int32_np, int64_np, float_np, double_np, bytes_data = gen_ofrecord(
num_examples, length, batch_size
)
@flow.global_function(func_config)
def OfrecordDecoderJob():
data = decoder(get_temp_dir(), length, batch_size)
return data
for i in range(num_examples // batch_size):
d = OfrecordDecoderJob().get()
test_case.assertTrue(np.array_equal(d["int32"].numpy(), int32_np[i]))
test_case.assertTrue(np.array_equal(d["int64"].numpy(), int64_np[i]))
# test_case.assertTrue(np.array_equal(d['float'].numpy(), float_np[i]))
assert np.allclose(d["float"].numpy(), float_np[i], rtol=1e-5, atol=1e-5)
test_case.assertTrue(np.array_equal(d["double"].numpy(), double_np[i]))
for j, int8_list in enumerate(d["bytes"]):
# print(''.join([chr(x) for x in int8_list[0]]), bytes_data[i*batch_size + j])
assert (
"".join([chr(x) for x in int8_list[0]])
== bytes_data[i * batch_size + j]
)
| [
"oneflow.FunctionConfig",
"oneflow.core.record.record_pb2.Int64List",
"oneflow.core.record.record_pb2.Int32List",
"oneflow.data.RawCodec",
"oneflow.data.ofrecord_raw_decoder",
"oneflow.data.ofrecord_reader",
"oneflow.global_function",
"oneflow.core.record.record_pb2.DoubleList",
"oneflow.core.record.record_pb2.BytesList",
"oneflow.core.record.record_pb2.FloatList",
"oneflow.data.BlobConf"
] | [((838, 856), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (854, 856), False, 'import tempfile\n'), ((5227, 5248), 'oneflow.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (5246, 5248), True, 'import oneflow as flow\n'), ((4175, 4195), 'oneflow.data.RawCodec', 'flow.data.RawCodec', ([], {}), '()\n', (4193, 4195), True, 'import oneflow as flow\n'), ((4209, 4277), 'oneflow.data.BlobConf', 'flow.data.BlobConf', ([], {'name': 'name', 'shape': 'shape', 'dtype': 'dtype', 'codec': 'codec'}), '(name=name, shape=shape, dtype=dtype, codec=codec)\n', (4227, 4277), True, 'import oneflow as flow\n'), ((4357, 4449), 'oneflow.data.ofrecord_reader', 'flow.data.ofrecord_reader', (['data_dir'], {'batch_size': 'batch_size', 'data_part_num': 'data_part_num'}), '(data_dir, batch_size=batch_size, data_part_num=\n data_part_num)\n', (4382, 4449), True, 'import oneflow as flow\n'), ((4476, 4565), 'oneflow.data.ofrecord_raw_decoder', 'flow.data.ofrecord_raw_decoder', (['ofrecord', '"""int32"""'], {'shape': '(length,)', 'dtype': 'flow.int32'}), "(ofrecord, 'int32', shape=(length,), dtype=\n flow.int32)\n", (4506, 4565), True, 'import oneflow as flow\n'), ((4592, 4681), 'oneflow.data.ofrecord_raw_decoder', 'flow.data.ofrecord_raw_decoder', (['ofrecord', '"""int64"""'], {'shape': '(length,)', 'dtype': 'flow.int64'}), "(ofrecord, 'int64', shape=(length,), dtype=\n flow.int64)\n", (4622, 4681), True, 'import oneflow as flow\n'), ((4708, 4797), 'oneflow.data.ofrecord_raw_decoder', 'flow.data.ofrecord_raw_decoder', (['ofrecord', '"""float"""'], {'shape': '(length,)', 'dtype': 'flow.float'}), "(ofrecord, 'float', shape=(length,), dtype=\n flow.float)\n", (4738, 4797), True, 'import oneflow as flow\n'), ((4825, 4916), 'oneflow.data.ofrecord_raw_decoder', 'flow.data.ofrecord_raw_decoder', (['ofrecord', '"""double"""'], {'shape': '(length,)', 'dtype': 'flow.double'}), "(ofrecord, 'double', shape=(length,), dtype=\n flow.double)\n", (4855, 4916), True, 'import oneflow as flow\n'), ((4943, 5033), 'oneflow.data.ofrecord_raw_decoder', 'flow.data.ofrecord_raw_decoder', (['ofrecord', '"""bytes"""'], {'shape': '(1, length)', 'dtype': 'flow.int8'}), "(ofrecord, 'bytes', shape=(1, length), dtype=\n flow.int8)\n", (4973, 5033), True, 'import oneflow as flow\n'), ((5559, 5592), 'oneflow.global_function', 'flow.global_function', (['func_config'], {}), '(func_config)\n', (5579, 5592), True, 'import oneflow as flow\n'), ((2100, 2139), 'random.randint', 'random.randint', (['(-2 ** b + 1)', '(2 ** b - 1)'], {}), '(-2 ** b + 1, 2 ** b - 1)\n', (2114, 2139), False, 'import random\n'), ((2196, 2211), 'random.random', 'random.random', ([], {}), '()\n', (2209, 2211), False, 'import random\n'), ((1097, 1128), 'oneflow.core.record.record_pb2.Int32List', 'ofrecord.Int32List', ([], {'value': 'value'}), '(value=value)\n', (1115, 1128), True, 'import oneflow.core.record.record_pb2 as ofrecord\n'), ((1266, 1297), 'oneflow.core.record.record_pb2.Int64List', 'ofrecord.Int64List', ([], {'value': 'value'}), '(value=value)\n', (1284, 1297), True, 'import oneflow.core.record.record_pb2 as ofrecord\n'), ((1502, 1533), 'oneflow.core.record.record_pb2.FloatList', 'ofrecord.FloatList', ([], {'value': 'value'}), '(value=value)\n', (1520, 1533), True, 'import oneflow.core.record.record_pb2 as ofrecord\n'), ((1741, 1773), 'oneflow.core.record.record_pb2.DoubleList', 'ofrecord.DoubleList', ([], {'value': 'value'}), '(value=value)\n', (1760, 1773), True, 'import oneflow.core.record.record_pb2 as ofrecord\n'), ((2017, 2048), 'oneflow.core.record.record_pb2.BytesList', 'ofrecord.BytesList', ([], {'value': 'value'}), '(value=value)\n', (2035, 2048), True, 'import oneflow.core.record.record_pb2 as ofrecord\n'), ((2283, 2336), 'random.choice', 'random.choice', (['(string.ascii_uppercase + string.digits)'], {}), '(string.ascii_uppercase + string.digits)\n', (2296, 2336), False, 'import random\n'), ((3439, 3458), 'struct.pack', 'struct.pack', (['"""q"""', 'l'], {}), "('q', l)\n", (3450, 3458), False, 'import struct\n'), ((3697, 3733), 'numpy.array', 'np.array', (['int32_data'], {'dtype': 'np.int32'}), '(int32_data, dtype=np.int32)\n', (3705, 3733), True, 'import numpy as np\n'), ((3785, 3821), 'numpy.array', 'np.array', (['int64_data'], {'dtype': 'np.int64'}), '(int64_data, dtype=np.int64)\n', (3793, 3821), True, 'import numpy as np\n'), ((3873, 3909), 'numpy.array', 'np.array', (['float_data'], {'dtype': 'np.float'}), '(float_data, dtype=np.float)\n', (3881, 3909), True, 'import numpy as np\n'), ((3962, 3999), 'numpy.array', 'np.array', (['float_data'], {'dtype': 'np.double'}), '(float_data, dtype=np.double)\n', (3970, 3999), True, 'import numpy as np\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
import os
import numpy as np
import oneflow as flow
import oneflow.unittest
def _test_linear_train_graph(test_case, device):
def train_with_module(iter_num=3):
linear = flow.nn.Linear(3, 8)
linear = linear.to(device)
flow.nn.init.constant_(linear.weight, 2.068758)
flow.nn.init.constant_(linear.bias, 0.23)
of_sgd = flow.optim.SGD(linear.parameters(), lr=0.001, momentum=0.9)
x = flow.tensor(
[
[-0.94630778, -0.83378579, -0.87060891],
[2.0289922, -0.28708987, -2.18369248],
[0.35217619, -0.67095644, -1.58943879],
[0.08086036, -1.81075924, 1.20752494],
[0.8901075, -0.49976737, -1.07153746],
[-0.44872912, -1.07275683, 0.06256855],
[-0.22556897, 0.74798368, 0.90416439],
[0.48339456, -2.32742195, -0.59321527],
],
dtype=flow.float32,
device=device,
requires_grad=False,
)
def one_iter():
of_out = linear(x)
of_out = of_out.sum()
of_out.backward()
of_sgd.step()
of_sgd.zero_grad()
return of_out.numpy(), linear.weight.numpy()
check_list = []
for i in range(iter_num):
check_list.append(one_iter())
return check_list
def train_with_graph(iter_num=3):
linear = flow.nn.Linear(3, 8)
linear = linear.to(device)
flow.nn.init.constant_(linear.weight, 2.068758)
flow.nn.init.constant_(linear.bias, 0.23)
of_sgd = flow.optim.SGD(linear.parameters(), lr=0.001, momentum=0.9)
x = flow.tensor(
[
[-0.94630778, -0.83378579, -0.87060891],
[2.0289922, -0.28708987, -2.18369248],
[0.35217619, -0.67095644, -1.58943879],
[0.08086036, -1.81075924, 1.20752494],
[0.8901075, -0.49976737, -1.07153746],
[-0.44872912, -1.07275683, 0.06256855],
[-0.22556897, 0.74798368, 0.90416439],
[0.48339456, -2.32742195, -0.59321527],
],
dtype=flow.float32,
device=device,
requires_grad=False,
)
class LinearTrainGraph(flow.nn.Graph):
def __init__(self):
super().__init__()
self.linear = linear
self.add_optimizer(of_sgd)
def build(self, x):
out = self.linear(x)
out = out.sum()
out.backward()
return out
linear_t_g = LinearTrainGraph()
def one_iter():
of_graph_out = linear_t_g(x)
return of_graph_out.numpy(), linear_t_g.linear.weight.origin.numpy()
check_list = []
for i in range(iter_num):
check_list.append(one_iter())
return check_list
iter_num = 3
module_check_list = train_with_module(iter_num)
graph_check_list = train_with_graph(iter_num)
for i in range(iter_num):
# check equal on loss
test_case.assertTrue(
np.array_equal(module_check_list[i][0], graph_check_list[i][0])
)
# check equal on weight
test_case.assertTrue(
np.array_equal(module_check_list[i][1], graph_check_list[i][1])
)
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
@flow.unittest.skip_unless_1n1d()
class TestLinearTrainGraph(oneflow.unittest.TestCase):
def test_linear_train_graph_gpu(test_case):
_test_linear_train_graph(test_case, flow.device("cuda"))
def test_linear_train_graph_cpu(test_case):
_test_linear_train_graph(test_case, flow.device("cpu"))
if __name__ == "__main__":
unittest.main()
| [
"oneflow.nn.init.constant_",
"oneflow.nn.Linear",
"oneflow.device",
"oneflow.unittest.skip_unless_1n1d",
"oneflow.tensor"
] | [((4084, 4116), 'oneflow.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (4114, 4116), True, 'import oneflow as flow\n'), ((4024, 4058), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (4033, 4058), False, 'import os\n'), ((4431, 4446), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4444, 4446), False, 'import unittest\n'), ((790, 810), 'oneflow.nn.Linear', 'flow.nn.Linear', (['(3)', '(8)'], {}), '(3, 8)\n', (804, 810), True, 'import oneflow as flow\n'), ((854, 901), 'oneflow.nn.init.constant_', 'flow.nn.init.constant_', (['linear.weight', '(2.068758)'], {}), '(linear.weight, 2.068758)\n', (876, 901), True, 'import oneflow as flow\n'), ((910, 951), 'oneflow.nn.init.constant_', 'flow.nn.init.constant_', (['linear.bias', '(0.23)'], {}), '(linear.bias, 0.23)\n', (932, 951), True, 'import oneflow as flow\n'), ((1042, 1453), 'oneflow.tensor', 'flow.tensor', (['[[-0.94630778, -0.83378579, -0.87060891], [2.0289922, -0.28708987, -\n 2.18369248], [0.35217619, -0.67095644, -1.58943879], [0.08086036, -\n 1.81075924, 1.20752494], [0.8901075, -0.49976737, -1.07153746], [-\n 0.44872912, -1.07275683, 0.06256855], [-0.22556897, 0.74798368, \n 0.90416439], [0.48339456, -2.32742195, -0.59321527]]'], {'dtype': 'flow.float32', 'device': 'device', 'requires_grad': '(False)'}), '([[-0.94630778, -0.83378579, -0.87060891], [2.0289922, -\n 0.28708987, -2.18369248], [0.35217619, -0.67095644, -1.58943879], [\n 0.08086036, -1.81075924, 1.20752494], [0.8901075, -0.49976737, -\n 1.07153746], [-0.44872912, -1.07275683, 0.06256855], [-0.22556897, \n 0.74798368, 0.90416439], [0.48339456, -2.32742195, -0.59321527]], dtype\n =flow.float32, device=device, requires_grad=False)\n', (1053, 1453), True, 'import oneflow as flow\n'), ((2050, 2070), 'oneflow.nn.Linear', 'flow.nn.Linear', (['(3)', '(8)'], {}), '(3, 8)\n', (2064, 2070), True, 'import oneflow as flow\n'), ((2114, 2161), 'oneflow.nn.init.constant_', 'flow.nn.init.constant_', (['linear.weight', '(2.068758)'], {}), '(linear.weight, 2.068758)\n', (2136, 2161), True, 'import oneflow as flow\n'), ((2170, 2211), 'oneflow.nn.init.constant_', 'flow.nn.init.constant_', (['linear.bias', '(0.23)'], {}), '(linear.bias, 0.23)\n', (2192, 2211), True, 'import oneflow as flow\n'), ((2302, 2713), 'oneflow.tensor', 'flow.tensor', (['[[-0.94630778, -0.83378579, -0.87060891], [2.0289922, -0.28708987, -\n 2.18369248], [0.35217619, -0.67095644, -1.58943879], [0.08086036, -\n 1.81075924, 1.20752494], [0.8901075, -0.49976737, -1.07153746], [-\n 0.44872912, -1.07275683, 0.06256855], [-0.22556897, 0.74798368, \n 0.90416439], [0.48339456, -2.32742195, -0.59321527]]'], {'dtype': 'flow.float32', 'device': 'device', 'requires_grad': '(False)'}), '([[-0.94630778, -0.83378579, -0.87060891], [2.0289922, -\n 0.28708987, -2.18369248], [0.35217619, -0.67095644, -1.58943879], [\n 0.08086036, -1.81075924, 1.20752494], [0.8901075, -0.49976737, -\n 1.07153746], [-0.44872912, -1.07275683, 0.06256855], [-0.22556897, \n 0.74798368, 0.90416439], [0.48339456, -2.32742195, -0.59321527]], dtype\n =flow.float32, device=device, requires_grad=False)\n', (2313, 2713), True, 'import oneflow as flow\n'), ((3783, 3846), 'numpy.array_equal', 'np.array_equal', (['module_check_list[i][0]', 'graph_check_list[i][0]'], {}), '(module_check_list[i][0], graph_check_list[i][0])\n', (3797, 3846), True, 'import numpy as np\n'), ((3931, 3994), 'numpy.array_equal', 'np.array_equal', (['module_check_list[i][1]', 'graph_check_list[i][1]'], {}), '(module_check_list[i][1], graph_check_list[i][1])\n', (3945, 3994), True, 'import numpy as np\n'), ((4264, 4283), 'oneflow.device', 'flow.device', (['"""cuda"""'], {}), "('cuda')\n", (4275, 4283), True, 'import oneflow as flow\n'), ((4378, 4396), 'oneflow.device', 'flow.device', (['"""cpu"""'], {}), "('cpu')\n", (4389, 4396), True, 'import oneflow as flow\n')] |
import oneflow as flow
def get_transformer_decoder_mask(targets):
batch_size, steps = targets.size()
seq_mask = flow.ones([batch_size, steps, steps], device=targets.device)
seq_mask = flow.tril(seq_mask).to(flow.int8)
return seq_mask
| [
"oneflow.tril",
"oneflow.ones"
] | [((122, 182), 'oneflow.ones', 'flow.ones', (['[batch_size, steps, steps]'], {'device': 'targets.device'}), '([batch_size, steps, steps], device=targets.device)\n', (131, 182), True, 'import oneflow as flow\n'), ((198, 217), 'oneflow.tril', 'flow.tril', (['seq_mask'], {}), '(seq_mask)\n', (207, 217), True, 'import oneflow as flow\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 logging
import os
import time
import numpy as np
import oneflow as flow
from libai.data.data_utils import helpers
from libai.utils import distributed as dist
logger = logging.getLogger(__name__)
def get_samples_mapping(data_prefix, indexed_dataset, max_seq_length, short_seq_prob, binary_head):
"""Get a list that maps a sample index to a starting sentence index,
end sentence index, and length"""
# Filename of the index mapping
indexmap_filename = data_prefix
indexmap_filename += "_{}msl".format(max_seq_length)
indexmap_filename += "_{}ssp".format(short_seq_prob)
indexmap_filename += "_sample_mapping.npy"
documents = indexed_dataset.doc_idx
sizes = indexed_dataset.sizes
# Build the indexed mapping if not exist.
if flow.env.get_rank() == 0 and not os.path.isfile(indexmap_filename):
logger.info(
"WARNING: could not find index map file {}, building "
"the indices on rank 0 ...".format(indexmap_filename)
)
# Build samples mapping
verbose = flow.env.get_rank() == 0
start_time = time.time()
logger.info("building samples index mapping for {} ...".format(data_prefix))
samples_mapping = helpers.build_mapping(
documents,
sizes,
max_seq_length,
short_seq_prob,
verbose,
2 if binary_head else 1,
)
logger.info("done building samples index maping")
np.save(indexmap_filename, samples_mapping, allow_pickle=True)
logger.info("saved the index mapping in {}".format(indexmap_filename))
# Make sure all the ranks have built the mapping
logger.info(
"elapsed time to build and save samples mapping "
"(seconds): {:4f}".format(time.time() - start_time)
)
dist.synchronize()
# Load indexed dataset.
logger.info("loading indexed mapping from {}".format(indexmap_filename))
start_time = time.time()
samples_mapping = np.load(indexmap_filename, allow_pickle=True, mmap_mode="r")
logger.info("loaded indexed file in {:3.3f} seconds".format(time.time() - start_time))
logger.info("total number of samples: {}".format(samples_mapping.shape[0]))
return samples_mapping
class SentenceIndexedDataset(flow.utils.data.Dataset):
"""This class is propused for building sample mapping index from `indexed_dataset` to
actural dataset.
It will combine as many consecutive sentences as possible in the same document without
exceeding `max_seq_length`.
When it does not reach maximum length, the pad will be filled later. All the sentences in it
are complete.
`binary_head` controls whether to return one or two sentences, which will be used in Bert.
"""
def __init__(
self,
data_prefix,
indexed_dataset,
max_seq_length=512,
short_seq_prob=0.0,
binary_head=False,
):
self.max_seq_length = max_seq_length
self.short_seq_prob = short_seq_prob
self.binary_head = binary_head
self.indexed_dataset = indexed_dataset
self.samples_mapping = get_samples_mapping(
data_prefix,
self.indexed_dataset,
self.max_seq_length,
self.short_seq_prob,
self.binary_head,
)
def __len__(self):
return self.samples_mapping.shape[0]
def __getitem__(self, idx):
start_idx, end_idx, seq_length = self.samples_mapping[idx]
sample = [self.indexed_dataset[i] for i in range(start_idx, end_idx)]
assert seq_length <= self.max_seq_length
return sample
@property
def supports_prefetch(self):
return self.indexed_dataset.supports_prefetch
def prefetch(self, indices):
new_indices = []
for idx in indices:
start_idx, end_idx, _ = self.samples_mapping[idx]
new_indices.extend([i for i in range(start_idx, end_idx)])
self.indexed_dataset.prefetch(new_indices)
def build_index_mappings(data_prefix, indexed_dataset, max_seq_length):
"""Build sample-idx.
sample-idx: is the start document index and document offset for each training sample.
"""
# Filename of the index mappings.
indexmap_filename = data_prefix
indexmap_filename += "_{}msl".format(max_seq_length)
indexmap_filename += "_sample_idx.npy"
documents = indexed_dataset.doc_idx.astype(np.int64)
sizes = indexed_dataset.sizes.astype(np.int64)
num_tokens = np.sum(sizes[documents[:-1]])
# Build the indexed mapping if not exist.
if flow.env.get_rank() == 0 and not os.path.isfile(indexmap_filename):
logger.info("could not find index map files, building the indices on rank 0 ...")
# sample-idx.
start_time = time.time()
sample_idx = helpers.build_sample_idx(documents, sizes, max_seq_length, num_tokens)
np.save(indexmap_filename, sample_idx, allow_pickle=True)
logger.info(
"elasped time to build and save sample-idx mapping "
"(seconds): {:4f}".format(time.time() - start_time)
)
dist.synchronize()
# Load mappings.
start_time = time.time()
logger.info(" > loading sample-idx mapping from {}".format(indexmap_filename))
sample_idx = np.load(indexmap_filename, allow_pickle=True, mmap_mode="r")
logger.info("loaded indexed file in {:3.3f} seconds".format(time.time() - start_time))
logger.info("total number of samples: {}".format(sample_idx.shape[0]))
return sample_idx
class BlockIndexedDataset(flow.utils.data.Dataset):
"""This class is propused for building sample mapping index from `indexed_dataset`
to actural dataset.
It will extract the sentence with the length of `max_seq_length` from the document.
If it is less than the maximum length, it will be intercepted from the next document.
Therefore, it always returns sentences with `max_seq_length`, but it may
contain incomplete sentences.
This is used for GPT training, and it can reduce padding and improve training efficiency.
"""
def __init__(self, data_prefix, indexed_dataset, max_seq_length=512):
self.max_seq_length = max_seq_length
self.indexed_dataset = indexed_dataset
self.doc_idx = indexed_dataset.doc_idx
self.sample_idx = build_index_mappings(
data_prefix, self.indexed_dataset, self.max_seq_length
)
def __len__(self):
return self.sample_idx.shape[0] - 1
def __getitem__(self, idx):
doc_index_f = self.sample_idx[idx][0]
doc_index_l = self.sample_idx[idx + 1][0]
offset_f = self.sample_idx[idx][1]
offset_l = self.sample_idx[idx + 1][1]
if doc_index_f == doc_index_l:
sample = self.indexed_dataset.get(
self.doc_idx[doc_index_f], offset=offset_f, length=offset_l - offset_f + 1
)
else:
# Otherwise, get the rest of the initial document.
sample_list = [self.indexed_dataset.get(self.doc_idx[doc_index_f], offset=offset_f)]
# Loop over all in between documents and add the entire document.
for i in range(doc_index_f + 1, doc_index_l):
sample_list.append(self.indexed_dataset.get(self.doc_idx[i]))
# And finally add the relevant portion of last document.
sample_list.append(
self.indexed_dataset.get(self.doc_idx[doc_index_l], length=offset_l + 1)
)
sample = np.concatenate(sample_list)
return sample
@property
def supports_prefetch(self):
# this dataset must be `cached`, and IndexedCachedDataset are not support prefetch.
return False
| [
"oneflow.env.get_rank"
] | [((799, 826), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (816, 826), False, 'import logging\n'), ((2471, 2489), 'libai.utils.distributed.synchronize', 'dist.synchronize', ([], {}), '()\n', (2487, 2489), True, 'from libai.utils import distributed as dist\n'), ((2613, 2624), 'time.time', 'time.time', ([], {}), '()\n', (2622, 2624), False, 'import time\n'), ((2647, 2707), 'numpy.load', 'np.load', (['indexmap_filename'], {'allow_pickle': '(True)', 'mmap_mode': '"""r"""'}), "(indexmap_filename, allow_pickle=True, mmap_mode='r')\n", (2654, 2707), True, 'import numpy as np\n'), ((5167, 5196), 'numpy.sum', 'np.sum', (['sizes[documents[:-1]]'], {}), '(sizes[documents[:-1]])\n', (5173, 5196), True, 'import numpy as np\n'), ((5788, 5806), 'libai.utils.distributed.synchronize', 'dist.synchronize', ([], {}), '()\n', (5804, 5806), True, 'from libai.utils import distributed as dist\n'), ((5846, 5857), 'time.time', 'time.time', ([], {}), '()\n', (5855, 5857), False, 'import time\n'), ((5958, 6018), 'numpy.load', 'np.load', (['indexmap_filename'], {'allow_pickle': '(True)', 'mmap_mode': '"""r"""'}), "(indexmap_filename, allow_pickle=True, mmap_mode='r')\n", (5965, 6018), True, 'import numpy as np\n'), ((1732, 1743), 'time.time', 'time.time', ([], {}), '()\n', (1741, 1743), False, 'import time\n'), ((1855, 1964), 'libai.data.data_utils.helpers.build_mapping', 'helpers.build_mapping', (['documents', 'sizes', 'max_seq_length', 'short_seq_prob', 'verbose', '(2 if binary_head else 1)'], {}), '(documents, sizes, max_seq_length, short_seq_prob,\n verbose, 2 if binary_head else 1)\n', (1876, 1964), False, 'from libai.data.data_utils import helpers\n'), ((2110, 2172), 'numpy.save', 'np.save', (['indexmap_filename', 'samples_mapping'], {'allow_pickle': '(True)'}), '(indexmap_filename, samples_mapping, allow_pickle=True)\n', (2117, 2172), True, 'import numpy as np\n'), ((5453, 5464), 'time.time', 'time.time', ([], {}), '()\n', (5462, 5464), False, 'import time\n'), ((5486, 5556), 'libai.data.data_utils.helpers.build_sample_idx', 'helpers.build_sample_idx', (['documents', 'sizes', 'max_seq_length', 'num_tokens'], {}), '(documents, sizes, max_seq_length, num_tokens)\n', (5510, 5556), False, 'from libai.data.data_utils import helpers\n'), ((5565, 5622), 'numpy.save', 'np.save', (['indexmap_filename', 'sample_idx'], {'allow_pickle': '(True)'}), '(indexmap_filename, sample_idx, allow_pickle=True)\n', (5572, 5622), True, 'import numpy as np\n'), ((1403, 1422), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (1420, 1422), True, 'import oneflow as flow\n'), ((1436, 1469), 'os.path.isfile', 'os.path.isfile', (['indexmap_filename'], {}), '(indexmap_filename)\n', (1450, 1469), False, 'import os\n'), ((1686, 1705), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (1703, 1705), True, 'import oneflow as flow\n'), ((5251, 5270), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (5268, 5270), True, 'import oneflow as flow\n'), ((5284, 5317), 'os.path.isfile', 'os.path.isfile', (['indexmap_filename'], {}), '(indexmap_filename)\n', (5298, 5317), False, 'import os\n'), ((8195, 8222), 'numpy.concatenate', 'np.concatenate', (['sample_list'], {}), '(sample_list)\n', (8209, 8222), True, 'import numpy as np\n'), ((2772, 2783), 'time.time', 'time.time', ([], {}), '()\n', (2781, 2783), False, 'import time\n'), ((6083, 6094), 'time.time', 'time.time', ([], {}), '()\n', (6092, 6094), False, 'import time\n'), ((2430, 2441), 'time.time', 'time.time', ([], {}), '()\n', (2439, 2441), False, 'import time\n'), ((5747, 5758), 'time.time', 'time.time', ([], {}), '()\n', (5756, 5758), 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
import oneflow as flow
import numpy as np
import os
import random
import oneflow.typing as oft
from collections import OrderedDict
def fake_flow_ones(shape):
tensor = flow.Tensor(*shape)
tensor.set_data_initializer(flow.ones_initializer())
return tensor
@flow.unittest.skip_unless_1n1d()
class TestTensor(flow.unittest.TestCase):
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
"numpy doesn't work in lazy mode",
)
def test_numpy(test_case):
@flow.global_function()
def job():
shape = (2, 3)
test_case.assertTrue(
np.array_equal(
fake_flow_ones(shape).numpy(), np.ones(shape, dtype=np.float32)
)
)
job()
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
"numpy doesn't work in lazy mode",
)
def test_init(test_case):
shape = (2, 3)
x = flow.Tensor(*shape)
x.fill_(5)
@flow.global_function()
def job():
test_case.assertTrue(np.array_equal(x.numpy(), 5 * np.ones(x.shape)))
job()
flow.nn.init.ones_(x)
@flow.global_function()
def job():
test_case.assertTrue(np.array_equal(x.numpy(), np.ones(x.shape)))
job()
if __name__ == "__main__":
unittest.main()
| [
"oneflow.nn.init.ones_",
"oneflow.unittest.env.eager_execution_enabled",
"oneflow.ones_initializer",
"oneflow.global_function",
"oneflow.Tensor",
"oneflow.unittest.skip_unless_1n1d"
] | [((877, 909), 'oneflow.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (907, 909), True, 'import oneflow as flow\n'), ((779, 798), 'oneflow.Tensor', 'flow.Tensor', (['*shape'], {}), '(*shape)\n', (790, 798), True, 'import oneflow as flow\n'), ((1978, 1993), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1991, 1993), False, 'import unittest\n'), ((831, 854), 'oneflow.ones_initializer', 'flow.ones_initializer', ([], {}), '()\n', (852, 854), True, 'import oneflow as flow\n'), ((1120, 1142), 'oneflow.global_function', 'flow.global_function', ([], {}), '()\n', (1140, 1142), True, 'import oneflow as flow\n'), ((1580, 1599), 'oneflow.Tensor', 'flow.Tensor', (['*shape'], {}), '(*shape)\n', (1591, 1599), True, 'import oneflow as flow\n'), ((1630, 1652), 'oneflow.global_function', 'flow.global_function', ([], {}), '()\n', (1650, 1652), True, 'import oneflow as flow\n'), ((1778, 1799), 'oneflow.nn.init.ones_', 'flow.nn.init.ones_', (['x'], {}), '(x)\n', (1796, 1799), True, 'import oneflow as flow\n'), ((1810, 1832), 'oneflow.global_function', 'flow.global_function', ([], {}), '()\n', (1830, 1832), True, 'import oneflow as flow\n'), ((986, 1029), 'oneflow.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (1027, 1029), True, 'import oneflow as flow\n'), ((1421, 1464), 'oneflow.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (1462, 1464), True, 'import oneflow as flow\n'), ((1306, 1338), 'numpy.ones', 'np.ones', (['shape'], {'dtype': 'np.float32'}), '(shape, dtype=np.float32)\n', (1313, 1338), True, 'import numpy as np\n'), ((1911, 1927), 'numpy.ones', 'np.ones', (['x.shape'], {}), '(x.shape)\n', (1918, 1927), True, 'import numpy as np\n'), ((1735, 1751), 'numpy.ones', 'np.ones', (['x.shape'], {}), '(x.shape)\n', (1742, 1751), True, 'import numpy as np\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 math
import oneflow as flow
from oneflow.framework.tensor import Tensor
from oneflow.nn.init import _calculate_fan_in_and_fan_out
from oneflow.nn.module import Module
from typing import Tuple
class FusedMLP(Module):
"""Applies a linear transformation with relu activation to the incoming data: :math:`y = ReLU(xA^T + b)`
Args:
in_features: size of each input sample
hidden_features: A tuple of each Linear layer hidden size
out_features: The final Linear layer hidden size
Shape:
- Input: :math:`(N, *, H_{in})` where :math:`*` means any number of
additional dimensions and :math:`H_{in} = {in\\_features}`
- Output: :math:`(N, *, H_{out})` where all but the last dimension
are the same shape as the input and :math:`H_{out} = {out\\_features}`.
Attr:
- :attr:`skip_final_activation`: Whether to skip final hidden layer's activation. Default: False.
For example:
.. code-block:: python
>>> import numpy as np
>>> import oneflow as flow
>>> m = flow.nn.FusedMLP(128, [256, 512], 1024).to("cuda")
>>> input = flow.Tensor(np.random.randn(1, 128)).to("cuda")
>>> output = m(input)
>>> output.size()
oneflow.Size([1, 1024])
"""
def __init__(
self,
in_features: int,
hidden_features: Tuple[int],
out_features: int,
skip_final_activation=False,
) -> None:
super().__init__()
self.in_features = in_features
self.hidden_features = hidden_features
self.out_features = out_features
# TODO(zzk): Add more activation support.
self.skip_final_activation = skip_final_activation
self.hidden_layer_num = len(hidden_features)
self.add_parameters()
self.reset_parameters()
def add_parameters(self) -> None:
if self.hidden_layer_num != 0:
# First layer.
self.register_parameter(
f"weight_{0}",
flow.nn.Parameter(
flow.Tensor(self.hidden_features[0], self.in_features)
),
)
self.register_parameter(
f"bias_{0}", flow.nn.Parameter(flow.Tensor(self.hidden_features[0]))
)
# Middle Layer.
for idx in range(1, self.hidden_layer_num):
self.register_parameter(
f"weight_{idx}",
flow.nn.Parameter(
flow.Tensor(
self.hidden_features[idx], self.hidden_features[idx - 1],
)
),
)
self.register_parameter(
f"bias_{idx}",
flow.nn.Parameter(flow.Tensor(self.hidden_features[idx])),
)
# Final Layer.
self.register_parameter(
f"weight_{self.hidden_layer_num}",
flow.nn.Parameter(
flow.Tensor(
self.out_features,
self.hidden_features[self.hidden_layer_num - 1],
)
),
)
self.register_parameter(
f"bias_{self.hidden_layer_num}",
flow.nn.Parameter(flow.Tensor(self.out_features)),
)
else:
# there is only 1 layer.
self.register_parameter(
f"weight_{0}",
flow.nn.Parameter(flow.Tensor(self.out_features, self.in_features)),
)
self.register_parameter(
f"bias_{0}", flow.nn.Parameter(flow.Tensor(self.out_features))
)
def weight(self, i):
return getattr(self, f"weight_{i}")
def weights(self):
return [self.weight(i) for i in range(self.hidden_layer_num + 1)]
def bias(self, i):
return getattr(self, f"bias_{i}")
def biases(self):
return [self.bias(i) for i in range(self.hidden_layer_num + 1)]
def reset_parameters(self) -> None:
for layer_idx in range(self.hidden_layer_num + 1):
flow.nn.init.kaiming_uniform_(self.weight(layer_idx), a=math.sqrt(5))
(fan_in, _) = _calculate_fan_in_and_fan_out(self.weight(layer_idx))
bound = 1 / math.sqrt(fan_in)
flow.nn.init.uniform_(self.bias(layer_idx), -bound, bound)
def forward(self, x):
res = flow._C.fused_mlp(
x, self.weights(), self.biases(), self.skip_final_activation
)
return res
def extra_repr(self) -> str:
return "in_features={}, hidden_features={}, out_features={}, skip_final_activation={}".format(
self.in_features,
self.hidden_features,
self.out_features,
self.skip_final_activation,
)
if __name__ == "__main__":
import doctest
doctest.testmod(raise_on_error=True)
| [
"oneflow.Tensor"
] | [((5538, 5574), 'doctest.testmod', 'doctest.testmod', ([], {'raise_on_error': '(True)'}), '(raise_on_error=True)\n', (5553, 5574), False, 'import doctest\n'), ((4952, 4969), 'math.sqrt', 'math.sqrt', (['fan_in'], {}), '(fan_in)\n', (4961, 4969), False, 'import math\n'), ((2678, 2732), 'oneflow.Tensor', 'flow.Tensor', (['self.hidden_features[0]', 'self.in_features'], {}), '(self.hidden_features[0], self.in_features)\n', (2689, 2732), True, 'import oneflow as flow\n'), ((2850, 2886), 'oneflow.Tensor', 'flow.Tensor', (['self.hidden_features[0]'], {}), '(self.hidden_features[0])\n', (2861, 2886), True, 'import oneflow as flow\n'), ((3638, 3717), 'oneflow.Tensor', 'flow.Tensor', (['self.out_features', 'self.hidden_features[self.hidden_layer_num - 1]'], {}), '(self.out_features, self.hidden_features[self.hidden_layer_num - 1])\n', (3649, 3717), True, 'import oneflow as flow\n'), ((3942, 3972), 'oneflow.Tensor', 'flow.Tensor', (['self.out_features'], {}), '(self.out_features)\n', (3953, 3972), True, 'import oneflow as flow\n'), ((4142, 4190), 'oneflow.Tensor', 'flow.Tensor', (['self.out_features', 'self.in_features'], {}), '(self.out_features, self.in_features)\n', (4153, 4190), True, 'import oneflow as flow\n'), ((4291, 4321), 'oneflow.Tensor', 'flow.Tensor', (['self.out_features'], {}), '(self.out_features)\n', (4302, 4321), True, 'import oneflow as flow\n'), ((4834, 4846), 'math.sqrt', 'math.sqrt', (['(5)'], {}), '(5)\n', (4843, 4846), False, 'import math\n'), ((3128, 3197), 'oneflow.Tensor', 'flow.Tensor', (['self.hidden_features[idx]', 'self.hidden_features[idx - 1]'], {}), '(self.hidden_features[idx], self.hidden_features[idx - 1])\n', (3139, 3197), True, 'import oneflow as flow\n'), ((3408, 3446), 'oneflow.Tensor', 'flow.Tensor', (['self.hidden_features[idx]'], {}), '(self.hidden_features[idx])\n', (3419, 3446), 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 as flow
from util import convert_to_onnx_and_check
func_config = flow.FunctionConfig()
func_config.default_data_type(flow.float)
def generate_binary_op_test(flow_op, *args, opset=None, **kwargs):
@flow.global_function(func_config)
def job1():
x = flow.get_variable(
name="x1",
shape=(2, 3, 4),
dtype=flow.float,
initializer=flow.random_uniform_initializer(-10, 10),
)
y = flow.get_variable(
name="y1",
shape=(1, 3, 1),
dtype=flow.float,
initializer=flow.random_uniform_initializer(-10, 10),
)
return flow_op(x, y, *args, **kwargs)
convert_to_onnx_and_check(job1, opset=opset)
def generate_unary_op_test(
flow_op, *args, opset=None, min_val=-10, max_val=10, **kwargs
):
@flow.global_function(func_config)
def job1():
x = flow.get_variable(
name="x1",
shape=(2, 3, 4),
dtype=flow.float,
initializer=flow.random_uniform_initializer(min_val, max_val),
)
return flow_op(x, *args, **kwargs)
convert_to_onnx_and_check(job1, opset=opset)
def test_mul(test_case):
generate_binary_op_test(flow.math.multiply)
def test_div(test_case):
generate_binary_op_test(flow.math.divide)
def test_sub(test_case):
generate_binary_op_test(flow.math.subtract)
def test_add(test_case):
generate_binary_op_test(flow.math.add)
def test_abs(test_case):
generate_unary_op_test(flow.math.abs)
def test_ceil(test_case):
generate_unary_op_test(flow.math.ceil)
def test_acos(test_case):
generate_unary_op_test(flow.math.acos, min_val=-1, max_val=1)
def test_asin(test_case):
generate_unary_op_test(flow.math.asin, min_val=-1, max_val=1)
def test_atan(test_case):
generate_unary_op_test(flow.math.atan, min_val=-1, max_val=1)
def test_acosh(test_case):
generate_unary_op_test(flow.math.acosh, min_val=1, max_val=100)
def test_asinh(test_case):
generate_unary_op_test(flow.math.asinh, min_val=-1, max_val=1)
def test_atanh(test_case):
generate_unary_op_test(flow.math.atanh, min_val=-1, max_val=1)
def test_sin(test_case):
generate_unary_op_test(flow.math.sin)
def test_cos(test_case):
generate_unary_op_test(flow.math.cos)
def test_tan(test_case):
generate_unary_op_test(flow.math.tan)
def test_sinh(test_case):
generate_unary_op_test(flow.math.sinh)
def test_cosh(test_case):
generate_unary_op_test(flow.math.cosh)
def test_tanh_v2(test_case):
generate_unary_op_test(flow.math.tanh_v2)
def test_tanh(test_case):
generate_unary_op_test(flow.math.tanh)
def test_erf(test_case):
generate_unary_op_test(flow.math.erf)
def test_log(test_case):
generate_unary_op_test(flow.math.log, min_val=0, max_val=100)
def test_floor(test_case):
generate_unary_op_test(flow.math.floor)
def test_reciprocal(test_case):
generate_unary_op_test(flow.math.reciprocal)
def test_round(test_case):
generate_unary_op_test(flow.math.round, opset=11)
def test_rsqrt(test_case):
generate_unary_op_test(flow.math.rsqrt, min_val=0, max_val=100)
def test_sigmoid_v2(test_case):
generate_unary_op_test(flow.math.sigmoid_v2)
def test_sigmoid(test_case):
generate_unary_op_test(flow.math.sigmoid)
def test_sign(test_case):
generate_unary_op_test(flow.math.sign)
def test_softplus(test_case):
generate_unary_op_test(flow.math.softplus)
def test_sigmoid(test_case):
generate_unary_op_test(flow.math.sigmoid)
def test_sqrt(test_case):
generate_unary_op_test(flow.math.sqrt, min_val=0, max_val=100)
def test_sqaure(test_case):
generate_unary_op_test(flow.math.square)
def test_maximum(test_case):
generate_binary_op_test(flow.math.maximum)
def test_minimum(test_case):
generate_binary_op_test(flow.math.minimum)
def test_equal(test_case):
generate_binary_op_test(flow.math.equal, opset=11)
def test_not_equal(test_case):
generate_binary_op_test(flow.math.not_equal, opset=11)
def test_less(test_case):
generate_binary_op_test(flow.math.less)
def test_greater(test_case):
generate_binary_op_test(flow.math.greater)
def test_less_equal(test_case):
generate_binary_op_test(flow.math.less_equal)
def test_greater_equal(test_case):
generate_binary_op_test(flow.math.greater_equal)
def test_squared_difference(test_case):
generate_binary_op_test(flow.math.squared_difference)
def test_cast(test_case):
generate_unary_op_test(flow.cast, dtype=flow.int32)
def test_scalar_mul_int(test_cast):
generate_unary_op_test(flow.math.multiply, 5)
def test_scalar_mul_float(test_cast):
generate_unary_op_test(flow.math.multiply, 5.1)
def test_scalar_add_int(test_cast):
generate_unary_op_test(flow.math.add, 5)
def test_scalar_add_float(test_cast):
generate_unary_op_test(flow.math.add, 5.1)
| [
"oneflow.FunctionConfig",
"oneflow.global_function",
"oneflow.random_uniform_initializer"
] | [((672, 693), 'oneflow.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (691, 693), True, 'import oneflow as flow\n'), ((810, 843), 'oneflow.global_function', 'flow.global_function', (['func_config'], {}), '(func_config)\n', (830, 843), True, 'import oneflow as flow\n'), ((1289, 1333), 'util.convert_to_onnx_and_check', 'convert_to_onnx_and_check', (['job1'], {'opset': 'opset'}), '(job1, opset=opset)\n', (1314, 1333), False, 'from util import convert_to_onnx_and_check\n'), ((1438, 1471), 'oneflow.global_function', 'flow.global_function', (['func_config'], {}), '(func_config)\n', (1458, 1471), True, 'import oneflow as flow\n'), ((1734, 1778), 'util.convert_to_onnx_and_check', 'convert_to_onnx_and_check', (['job1'], {'opset': 'opset'}), '(job1, opset=opset)\n', (1759, 1778), False, 'from util import convert_to_onnx_and_check\n'), ((997, 1037), 'oneflow.random_uniform_initializer', 'flow.random_uniform_initializer', (['(-10)', '(10)'], {}), '(-10, 10)\n', (1028, 1037), True, 'import oneflow as flow\n'), ((1186, 1226), 'oneflow.random_uniform_initializer', 'flow.random_uniform_initializer', (['(-10)', '(10)'], {}), '(-10, 10)\n', (1217, 1226), True, 'import oneflow as flow\n'), ((1625, 1674), 'oneflow.random_uniform_initializer', 'flow.random_uniform_initializer', (['min_val', 'max_val'], {}), '(min_val, max_val)\n', (1656, 1674), 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 unittest
import numpy as np
import oneflow as flow
import oneflow.typing as tp
# flow.config.enable_debug_mode(True)
def flow_matmul(a, b):
def make_job(a_shape, b_shape, dtype=flow.float32):
config = flow.function_config()
config.default_placement_scope(flow.scope.placement("cambricon", "0:0"))
flow.config.enable_legacy_model_io(True)
@flow.global_function(type="predict", function_config=config)
def matmul_job(
a: tp.Numpy.Placeholder(a_shape), b: tp.Numpy.Placeholder(b_shape)
) -> tp.Numpy:
return flow.matmul(a, b, transpose_b=True)
return matmul_job
matmul_fakedev_job = make_job(a.shape, b.shape, dtype=flow.float32)
c = matmul_fakedev_job(a, b)
return c
def np_matmul(a, b):
b = np.transpose(b, (1, 0))
return np.matmul(a, b)
def _compare_with_np(test_case, a_shape, b_shape):
a = np.random.random(a_shape).astype(np.float32)
b = np.random.random(b_shape).astype(np.float32)
np_res = np_matmul(a, b)
print(np_res)
flow_res = flow_matmul(a, b)
print(flow_res)
test_case.assertTrue(np.allclose(np_res, flow_res, rtol=1e-1, atol=1e-5))
@flow.unittest.skip_unless_1n1d()
class TestMatmul(flow.unittest.TestCase):
def test_random_value(test_case):
_compare_with_np(test_case, (1, 2048), (1000, 2048))
if __name__ == "__main__":
unittest.main()
| [
"oneflow.matmul",
"oneflow.function_config",
"oneflow.config.enable_legacy_model_io",
"oneflow.typing.Numpy.Placeholder",
"oneflow.global_function",
"oneflow.scope.placement",
"oneflow.unittest.skip_unless_1n1d"
] | [((1787, 1819), 'oneflow.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (1817, 1819), True, 'import oneflow as flow\n'), ((1396, 1419), 'numpy.transpose', 'np.transpose', (['b', '(1, 0)'], {}), '(b, (1, 0))\n', (1408, 1419), True, 'import numpy as np\n'), ((1431, 1446), 'numpy.matmul', 'np.matmul', (['a', 'b'], {}), '(a, b)\n', (1440, 1446), True, 'import numpy as np\n'), ((1994, 2009), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2007, 2009), False, 'import unittest\n'), ((814, 836), 'oneflow.function_config', 'flow.function_config', ([], {}), '()\n', (834, 836), True, 'import oneflow as flow\n'), ((926, 966), 'oneflow.config.enable_legacy_model_io', 'flow.config.enable_legacy_model_io', (['(True)'], {}), '(True)\n', (960, 966), True, 'import oneflow as flow\n'), ((977, 1037), 'oneflow.global_function', 'flow.global_function', ([], {'type': '"""predict"""', 'function_config': 'config'}), "(type='predict', function_config=config)\n", (997, 1037), True, 'import oneflow as flow\n'), ((1731, 1782), 'numpy.allclose', 'np.allclose', (['np_res', 'flow_res'], {'rtol': '(0.1)', 'atol': '(1e-05)'}), '(np_res, flow_res, rtol=0.1, atol=1e-05)\n', (1742, 1782), True, 'import numpy as np\n'), ((876, 916), 'oneflow.scope.placement', 'flow.scope.placement', (['"""cambricon"""', '"""0:0"""'], {}), "('cambricon', '0:0')\n", (896, 916), True, 'import oneflow as flow\n'), ((1183, 1218), 'oneflow.matmul', 'flow.matmul', (['a', 'b'], {'transpose_b': '(True)'}), '(a, b, transpose_b=True)\n', (1194, 1218), True, 'import oneflow as flow\n'), ((1508, 1533), 'numpy.random.random', 'np.random.random', (['a_shape'], {}), '(a_shape)\n', (1524, 1533), True, 'import numpy as np\n'), ((1561, 1586), 'numpy.random.random', 'np.random.random', (['b_shape'], {}), '(b_shape)\n', (1577, 1586), True, 'import numpy as np\n'), ((1077, 1106), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['a_shape'], {}), '(a_shape)\n', (1097, 1106), True, 'import oneflow.typing as tp\n'), ((1111, 1140), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['b_shape'], {}), '(b_shape)\n', (1131, 1140), True, 'import oneflow.typing as tp\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
import numpy as np
import oneflow.experimental as flow
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestUpsample2d(flow.unittest.TestCase):
def test_upsample2d(test_case):
input = flow.Tensor(np.arange(1, 5).reshape((1, 1, 2, 2)), dtype=flow.float32)
input = input.to("cuda")
m = flow.nn.Upsample(scale_factor=2.0, mode="nearest")
of_out = m(input)
np_out = np.array(
[
[
[
[1.0, 1.0, 2.0, 2.0],
[1.0, 1.0, 2.0, 2.0],
[3.0, 3.0, 4.0, 4.0],
[3.0, 3.0, 4.0, 4.0],
]
]
]
)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
def test_upsample2d_bilinear(test_case):
input = flow.Tensor(np.arange(1, 5).reshape((1, 1, 2, 2)), dtype=flow.float32)
input = input.to("cuda")
m = flow.nn.Upsample(scale_factor=2.0, mode="bilinear")
of_out = m(input)
np_out = np.array(
[
[
[
[1.0000, 1.2500, 1.7500, 2.0000],
[1.5000, 1.7500, 2.2500, 2.5000],
[2.5000, 2.7500, 3.2500, 3.5000],
[3.0000, 3.2500, 3.7500, 4.0000],
]
]
]
)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
def test_upsample2d_bilinear_aligncorner(test_case):
input = flow.Tensor(np.arange(1, 5).reshape((1, 1, 2, 2)), dtype=flow.float32)
input = input.to("cuda")
m = flow.nn.Upsample(scale_factor=2.0, mode="bilinear", align_corners=True)
of_out = m(input)
np_out = np.array(
[
[
[
[1.0000, 1.3333, 1.6667, 2.0000],
[1.6667, 2.0000, 2.3333, 2.6667],
[2.3333, 2.6667, 3.0000, 3.3333],
[3.0000, 3.3333, 3.6667, 4.0000],
]
]
]
)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-3, 1e-3))
def test_UpsamplingNearest2d(test_case):
input = flow.Tensor(np.arange(1, 5).reshape((1, 1, 2, 2)), dtype=flow.float32)
input = input.to("cuda")
m = flow.nn.UpsamplingNearest2d(scale_factor=2.0)
of_out = m(input)
np_out = np.array(
[
[
[
[1.0, 1.0, 2.0, 2.0],
[1.0, 1.0, 2.0, 2.0],
[3.0, 3.0, 4.0, 4.0],
[3.0, 3.0, 4.0, 4.0],
]
]
]
)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
def test_UpsamplingBilinear2d(test_case):
input = flow.Tensor(np.arange(1, 5).reshape((1, 1, 2, 2)), dtype=flow.float32)
input = input.to("cuda")
m = flow.nn.UpsamplingBilinear2d(scale_factor=2.0)
of_out = m(input)
np_out = np.array(
[
[
[
[1.0000, 1.3333, 1.6667, 2.0000],
[1.6667, 2.0000, 2.3333, 2.6667],
[2.3333, 2.6667, 3.0000, 3.3333],
[3.0000, 3.3333, 3.6667, 4.0000],
]
]
]
)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-3, 1e-3))
def test_upsample2d_4dim(test_case):
input = flow.Tensor(np.arange(1, 37).reshape((2, 2, 3, 3)), dtype=flow.float32)
input = input.to("cuda")
m = flow.nn.Upsample(scale_factor=2.0, mode="nearest")
of_out = m(input)
np_out = np.array(
[
[
[
[1.0, 1.0, 2.0, 2.0, 3.0, 3.0,],
[1.0, 1.0, 2.0, 2.0, 3.0, 3.0,],
[4.0, 4.0, 5.0, 5.0, 6.0, 6.0,],
[4.0, 4.0, 5.0, 5.0, 6.0, 6.0,],
[7.0, 7.0, 8.0, 8.0, 9.0, 9.0,],
[7.0, 7.0, 8.0, 8.0, 9.0, 9.0,],
],
[
[10.0, 10.0, 11.0, 11.0, 12.0, 12.0,],
[10.0, 10.0, 11.0, 11.0, 12.0, 12.0,],
[13.0, 13.0, 14.0, 14.0, 15.0, 15.0,],
[13.0, 13.0, 14.0, 14.0, 15.0, 15.0,],
[16.0, 16.0, 17.0, 17.0, 18.0, 18.0,],
[16.0, 16.0, 17.0, 17.0, 18.0, 18.0,],
],
],
[
[
[19.0, 19.0, 20.0, 20.0, 21.0, 21.0,],
[19.0, 19.0, 20.0, 20.0, 21.0, 21.0,],
[22.0, 22.0, 23.0, 23.0, 24.0, 24.0,],
[22.0, 22.0, 23.0, 23.0, 24.0, 24.0,],
[25.0, 25.0, 26.0, 26.0, 27.0, 27.0,],
[25.0, 25.0, 26.0, 26.0, 27.0, 27.0,],
],
[
[28.0, 28.0, 29.0, 29.0, 30.0, 30.0,],
[28.0, 28.0, 29.0, 29.0, 30.0, 30.0,],
[31.0, 31.0, 32.0, 32.0, 33.0, 33.0,],
[31.0, 31.0, 32.0, 32.0, 33.0, 33.0,],
[34.0, 34.0, 35.0, 35.0, 36.0, 36.0,],
[34.0, 34.0, 35.0, 35.0, 36.0, 36.0,],
],
],
]
)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
def test_upsample2d_bilinear_4dim(test_case):
input = flow.Tensor(np.arange(1, 37).reshape((2, 2, 3, 3)), dtype=flow.float32)
input = input.to("cuda")
m = flow.nn.Upsample(scale_factor=2.0, mode="bilinear")
of_out = m(input)
np_out = np.array(
[
[
[
[1.0, 1.25, 1.75, 2.25, 2.75, 3.0],
[1.75, 2.0, 2.5, 3.0, 3.5, 3.75],
[3.25, 3.5, 4.0, 4.5, 5.0, 5.25],
[4.75, 5.0, 5.5, 6.0, 6.5, 6.75],
[6.25, 6.5, 7.0, 7.5, 8.0, 8.25],
[7.0, 7.25, 7.75, 8.25, 8.75, 9.0],
],
[
[10.0, 10.25, 10.75, 11.25, 11.75, 12.0],
[10.75, 11.0, 11.5, 12.0, 12.5, 12.75],
[12.25, 12.5, 13.0, 13.5, 14.0, 14.25],
[13.75, 14.0, 14.5, 15.0, 15.5, 15.75],
[15.25, 15.5, 16.0, 16.5, 17.0, 17.25],
[16.0, 16.25, 16.75, 17.25, 17.75, 18.0],
],
],
[
[
[19.0, 19.25, 19.75, 20.25, 20.75, 21.0],
[19.75, 20.0, 20.5, 21.0, 21.5, 21.75],
[21.25, 21.5, 22.0, 22.5, 23.0, 23.25],
[22.75, 23.0, 23.5, 24.0, 24.5, 24.75],
[24.25, 24.5, 25.0, 25.5, 26.0, 26.25],
[25.0, 25.25, 25.75, 26.25, 26.75, 27.0],
],
[
[28.0, 28.25, 28.75, 29.25, 29.75, 30.0],
[28.75, 29.0, 29.5, 30.0, 30.5, 30.75],
[30.25, 30.5, 31.0, 31.5, 32.0, 32.25],
[31.75, 32.0, 32.5, 33.0, 33.5, 33.75],
[33.25, 33.5, 34.0, 34.5, 35.0, 35.25],
[34.0, 34.25, 34.75, 35.25, 35.75, 36.0],
],
],
]
)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
if __name__ == "__main__":
unittest.main()
| [
"oneflow.experimental.nn.UpsamplingBilinear2d",
"oneflow.experimental.nn.Upsample",
"oneflow.experimental.unittest.env.eager_execution_enabled",
"oneflow.experimental.nn.UpsamplingNearest2d"
] | [((8628, 8643), 'unittest.main', 'unittest.main', ([], {}), '()\n', (8641, 8643), False, 'import unittest\n'), ((993, 1043), 'oneflow.experimental.nn.Upsample', 'flow.nn.Upsample', ([], {'scale_factor': '(2.0)', 'mode': '"""nearest"""'}), "(scale_factor=2.0, mode='nearest')\n", (1009, 1043), True, 'import oneflow.experimental as flow\n'), ((1087, 1194), 'numpy.array', 'np.array', (['[[[[1.0, 1.0, 2.0, 2.0], [1.0, 1.0, 2.0, 2.0], [3.0, 3.0, 4.0, 4.0], [3.0, \n 3.0, 4.0, 4.0]]]]'], {}), '([[[[1.0, 1.0, 2.0, 2.0], [1.0, 1.0, 2.0, 2.0], [3.0, 3.0, 4.0, 4.0\n ], [3.0, 3.0, 4.0, 4.0]]]])\n', (1095, 1194), True, 'import numpy as np\n'), ((1655, 1706), 'oneflow.experimental.nn.Upsample', 'flow.nn.Upsample', ([], {'scale_factor': '(2.0)', 'mode': '"""bilinear"""'}), "(scale_factor=2.0, mode='bilinear')\n", (1671, 1706), True, 'import oneflow.experimental as flow\n'), ((1750, 1865), 'numpy.array', 'np.array', (['[[[[1.0, 1.25, 1.75, 2.0], [1.5, 1.75, 2.25, 2.5], [2.5, 2.75, 3.25, 3.5],\n [3.0, 3.25, 3.75, 4.0]]]]'], {}), '([[[[1.0, 1.25, 1.75, 2.0], [1.5, 1.75, 2.25, 2.5], [2.5, 2.75, \n 3.25, 3.5], [3.0, 3.25, 3.75, 4.0]]]])\n', (1758, 1865), True, 'import numpy as np\n'), ((2378, 2449), 'oneflow.experimental.nn.Upsample', 'flow.nn.Upsample', ([], {'scale_factor': '(2.0)', 'mode': '"""bilinear"""', 'align_corners': '(True)'}), "(scale_factor=2.0, mode='bilinear', align_corners=True)\n", (2394, 2449), True, 'import oneflow.experimental as flow\n'), ((2493, 2630), 'numpy.array', 'np.array', (['[[[[1.0, 1.3333, 1.6667, 2.0], [1.6667, 2.0, 2.3333, 2.6667], [2.3333, \n 2.6667, 3.0, 3.3333], [3.0, 3.3333, 3.6667, 4.0]]]]'], {}), '([[[[1.0, 1.3333, 1.6667, 2.0], [1.6667, 2.0, 2.3333, 2.6667], [\n 2.3333, 2.6667, 3.0, 3.3333], [3.0, 3.3333, 3.6667, 4.0]]]])\n', (2501, 2630), True, 'import numpy as np\n'), ((3109, 3154), 'oneflow.experimental.nn.UpsamplingNearest2d', 'flow.nn.UpsamplingNearest2d', ([], {'scale_factor': '(2.0)'}), '(scale_factor=2.0)\n', (3136, 3154), True, 'import oneflow.experimental as flow\n'), ((3198, 3305), 'numpy.array', 'np.array', (['[[[[1.0, 1.0, 2.0, 2.0], [1.0, 1.0, 2.0, 2.0], [3.0, 3.0, 4.0, 4.0], [3.0, \n 3.0, 4.0, 4.0]]]]'], {}), '([[[[1.0, 1.0, 2.0, 2.0], [1.0, 1.0, 2.0, 2.0], [3.0, 3.0, 4.0, 4.0\n ], [3.0, 3.0, 4.0, 4.0]]]])\n', (3206, 3305), True, 'import numpy as np\n'), ((3767, 3813), 'oneflow.experimental.nn.UpsamplingBilinear2d', 'flow.nn.UpsamplingBilinear2d', ([], {'scale_factor': '(2.0)'}), '(scale_factor=2.0)\n', (3795, 3813), True, 'import oneflow.experimental as flow\n'), ((3857, 3994), 'numpy.array', 'np.array', (['[[[[1.0, 1.3333, 1.6667, 2.0], [1.6667, 2.0, 2.3333, 2.6667], [2.3333, \n 2.6667, 3.0, 3.3333], [3.0, 3.3333, 3.6667, 4.0]]]]'], {}), '([[[[1.0, 1.3333, 1.6667, 2.0], [1.6667, 2.0, 2.3333, 2.6667], [\n 2.3333, 2.6667, 3.0, 3.3333], [3.0, 3.3333, 3.6667, 4.0]]]])\n', (3865, 3994), True, 'import numpy as np\n'), ((4470, 4520), 'oneflow.experimental.nn.Upsample', 'flow.nn.Upsample', ([], {'scale_factor': '(2.0)', 'mode': '"""nearest"""'}), "(scale_factor=2.0, mode='nearest')\n", (4486, 4520), True, 'import oneflow.experimental as flow\n'), ((4564, 5519), 'numpy.array', 'np.array', (['[[[[1.0, 1.0, 2.0, 2.0, 3.0, 3.0], [1.0, 1.0, 2.0, 2.0, 3.0, 3.0], [4.0, \n 4.0, 5.0, 5.0, 6.0, 6.0], [4.0, 4.0, 5.0, 5.0, 6.0, 6.0], [7.0, 7.0, \n 8.0, 8.0, 9.0, 9.0], [7.0, 7.0, 8.0, 8.0, 9.0, 9.0]], [[10.0, 10.0, \n 11.0, 11.0, 12.0, 12.0], [10.0, 10.0, 11.0, 11.0, 12.0, 12.0], [13.0, \n 13.0, 14.0, 14.0, 15.0, 15.0], [13.0, 13.0, 14.0, 14.0, 15.0, 15.0], [\n 16.0, 16.0, 17.0, 17.0, 18.0, 18.0], [16.0, 16.0, 17.0, 17.0, 18.0, \n 18.0]]], [[[19.0, 19.0, 20.0, 20.0, 21.0, 21.0], [19.0, 19.0, 20.0, \n 20.0, 21.0, 21.0], [22.0, 22.0, 23.0, 23.0, 24.0, 24.0], [22.0, 22.0, \n 23.0, 23.0, 24.0, 24.0], [25.0, 25.0, 26.0, 26.0, 27.0, 27.0], [25.0, \n 25.0, 26.0, 26.0, 27.0, 27.0]], [[28.0, 28.0, 29.0, 29.0, 30.0, 30.0],\n [28.0, 28.0, 29.0, 29.0, 30.0, 30.0], [31.0, 31.0, 32.0, 32.0, 33.0, \n 33.0], [31.0, 31.0, 32.0, 32.0, 33.0, 33.0], [34.0, 34.0, 35.0, 35.0, \n 36.0, 36.0], [34.0, 34.0, 35.0, 35.0, 36.0, 36.0]]]]'], {}), '([[[[1.0, 1.0, 2.0, 2.0, 3.0, 3.0], [1.0, 1.0, 2.0, 2.0, 3.0, 3.0],\n [4.0, 4.0, 5.0, 5.0, 6.0, 6.0], [4.0, 4.0, 5.0, 5.0, 6.0, 6.0], [7.0, \n 7.0, 8.0, 8.0, 9.0, 9.0], [7.0, 7.0, 8.0, 8.0, 9.0, 9.0]], [[10.0, 10.0,\n 11.0, 11.0, 12.0, 12.0], [10.0, 10.0, 11.0, 11.0, 12.0, 12.0], [13.0, \n 13.0, 14.0, 14.0, 15.0, 15.0], [13.0, 13.0, 14.0, 14.0, 15.0, 15.0], [\n 16.0, 16.0, 17.0, 17.0, 18.0, 18.0], [16.0, 16.0, 17.0, 17.0, 18.0, \n 18.0]]], [[[19.0, 19.0, 20.0, 20.0, 21.0, 21.0], [19.0, 19.0, 20.0, \n 20.0, 21.0, 21.0], [22.0, 22.0, 23.0, 23.0, 24.0, 24.0], [22.0, 22.0, \n 23.0, 23.0, 24.0, 24.0], [25.0, 25.0, 26.0, 26.0, 27.0, 27.0], [25.0, \n 25.0, 26.0, 26.0, 27.0, 27.0]], [[28.0, 28.0, 29.0, 29.0, 30.0, 30.0],\n [28.0, 28.0, 29.0, 29.0, 30.0, 30.0], [31.0, 31.0, 32.0, 32.0, 33.0, \n 33.0], [31.0, 31.0, 32.0, 32.0, 33.0, 33.0], [34.0, 34.0, 35.0, 35.0, \n 36.0, 36.0], [34.0, 34.0, 35.0, 35.0, 36.0, 36.0]]]])\n', (4572, 5519), True, 'import numpy as np\n'), ((6604, 6655), 'oneflow.experimental.nn.Upsample', 'flow.nn.Upsample', ([], {'scale_factor': '(2.0)', 'mode': '"""bilinear"""'}), "(scale_factor=2.0, mode='bilinear')\n", (6620, 6655), True, 'import oneflow.experimental as flow\n'), ((6699, 7723), 'numpy.array', 'np.array', (['[[[[1.0, 1.25, 1.75, 2.25, 2.75, 3.0], [1.75, 2.0, 2.5, 3.0, 3.5, 3.75], [\n 3.25, 3.5, 4.0, 4.5, 5.0, 5.25], [4.75, 5.0, 5.5, 6.0, 6.5, 6.75], [\n 6.25, 6.5, 7.0, 7.5, 8.0, 8.25], [7.0, 7.25, 7.75, 8.25, 8.75, 9.0]], [\n [10.0, 10.25, 10.75, 11.25, 11.75, 12.0], [10.75, 11.0, 11.5, 12.0, \n 12.5, 12.75], [12.25, 12.5, 13.0, 13.5, 14.0, 14.25], [13.75, 14.0, \n 14.5, 15.0, 15.5, 15.75], [15.25, 15.5, 16.0, 16.5, 17.0, 17.25], [16.0,\n 16.25, 16.75, 17.25, 17.75, 18.0]]], [[[19.0, 19.25, 19.75, 20.25, \n 20.75, 21.0], [19.75, 20.0, 20.5, 21.0, 21.5, 21.75], [21.25, 21.5, \n 22.0, 22.5, 23.0, 23.25], [22.75, 23.0, 23.5, 24.0, 24.5, 24.75], [\n 24.25, 24.5, 25.0, 25.5, 26.0, 26.25], [25.0, 25.25, 25.75, 26.25, \n 26.75, 27.0]], [[28.0, 28.25, 28.75, 29.25, 29.75, 30.0], [28.75, 29.0,\n 29.5, 30.0, 30.5, 30.75], [30.25, 30.5, 31.0, 31.5, 32.0, 32.25], [\n 31.75, 32.0, 32.5, 33.0, 33.5, 33.75], [33.25, 33.5, 34.0, 34.5, 35.0, \n 35.25], [34.0, 34.25, 34.75, 35.25, 35.75, 36.0]]]]'], {}), '([[[[1.0, 1.25, 1.75, 2.25, 2.75, 3.0], [1.75, 2.0, 2.5, 3.0, 3.5, \n 3.75], [3.25, 3.5, 4.0, 4.5, 5.0, 5.25], [4.75, 5.0, 5.5, 6.0, 6.5, \n 6.75], [6.25, 6.5, 7.0, 7.5, 8.0, 8.25], [7.0, 7.25, 7.75, 8.25, 8.75, \n 9.0]], [[10.0, 10.25, 10.75, 11.25, 11.75, 12.0], [10.75, 11.0, 11.5, \n 12.0, 12.5, 12.75], [12.25, 12.5, 13.0, 13.5, 14.0, 14.25], [13.75, \n 14.0, 14.5, 15.0, 15.5, 15.75], [15.25, 15.5, 16.0, 16.5, 17.0, 17.25],\n [16.0, 16.25, 16.75, 17.25, 17.75, 18.0]]], [[[19.0, 19.25, 19.75, \n 20.25, 20.75, 21.0], [19.75, 20.0, 20.5, 21.0, 21.5, 21.75], [21.25, \n 21.5, 22.0, 22.5, 23.0, 23.25], [22.75, 23.0, 23.5, 24.0, 24.5, 24.75],\n [24.25, 24.5, 25.0, 25.5, 26.0, 26.25], [25.0, 25.25, 25.75, 26.25, \n 26.75, 27.0]], [[28.0, 28.25, 28.75, 29.25, 29.75, 30.0], [28.75, 29.0,\n 29.5, 30.0, 30.5, 30.75], [30.25, 30.5, 31.0, 31.5, 32.0, 32.25], [\n 31.75, 32.0, 32.5, 33.0, 33.5, 33.75], [33.25, 33.5, 34.0, 34.5, 35.0, \n 35.25], [34.0, 34.25, 34.75, 35.25, 35.75, 36.0]]]])\n', (6707, 7723), True, 'import numpy as np\n'), ((690, 733), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (731, 733), True, 'import oneflow.experimental as flow\n'), ((889, 904), 'numpy.arange', 'np.arange', (['(1)', '(5)'], {}), '(1, 5)\n', (898, 904), True, 'import numpy as np\n'), ((1551, 1566), 'numpy.arange', 'np.arange', (['(1)', '(5)'], {}), '(1, 5)\n', (1560, 1566), True, 'import numpy as np\n'), ((2274, 2289), 'numpy.arange', 'np.arange', (['(1)', '(5)'], {}), '(1, 5)\n', (2283, 2289), True, 'import numpy as np\n'), ((3005, 3020), 'numpy.arange', 'np.arange', (['(1)', '(5)'], {}), '(1, 5)\n', (3014, 3020), True, 'import numpy as np\n'), ((3663, 3678), 'numpy.arange', 'np.arange', (['(1)', '(5)'], {}), '(1, 5)\n', (3672, 3678), True, 'import numpy as np\n'), ((4365, 4381), 'numpy.arange', 'np.arange', (['(1)', '(37)'], {}), '(1, 37)\n', (4374, 4381), True, 'import numpy as np\n'), ((6499, 6515), 'numpy.arange', 'np.arange', (['(1)', '(37)'], {}), '(1, 37)\n', (6508, 6515), True, 'import numpy as np\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 _np_pixel_shuffle(input, factor):
_batch, _channel, _height, _width = input.shape
assert (
_channel % (factor ** 2) == 0
), "The channels of input tensor must be divisible by (upscale_factor * upscale_factor)"
_new_c = int(_channel / (factor ** 2))
out = np.reshape(input, [_batch, _new_c, factor ** 2, _height, _width])
out = np.reshape(out, [_batch, _new_c, factor, factor, _height, _width])
out = np.transpose(out, [0, 1, 4, 2, 5, 3])
out = np.reshape(out, [_batch, _new_c, _height * factor, _width * factor])
return out
def _np_pixel_shuffle_grad(input, factor):
_batch, _new_channel, _height_mul_factor, _width_mul_factor = input.shape
_channel = _new_channel * (factor ** 2)
_height = _height_mul_factor // factor
_width = _width_mul_factor // factor
out = np.ones(shape=(_batch, _channel, _height, _width))
return out
def _test_pixel_shuffle_impl(test_case, device, shape, upscale_factor):
x = np.random.randn(*shape)
input = flow.Tensor(
x, dtype=flow.float32, requires_grad=True, device=flow.device(device)
)
m = flow.nn.PixelShuffle(upscale_factor)
m = m.to(device)
of_out = m(input)
np_out = _np_pixel_shuffle(x, upscale_factor)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
of_out = of_out.sum()
of_out.backward()
np_grad = _np_pixel_shuffle_grad(np_out, upscale_factor)
test_case.assertTrue(np.allclose(input.grad.numpy(), np_grad, 1e-5, 1e-5))
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestPixelShuffleModule(flow.unittest.TestCase):
def test_pixel_shuffle(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [
_test_pixel_shuffle_impl,
]
arg_dict["device"] = ["cpu", "cuda"]
arg_dict["shape"] = [(2, 144, 5, 5), (11, 144, 1, 1)]
arg_dict["upscale_factor"] = [2, 3, 4]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
arg_dict["shape"] = [(8, 25, 18, 18), (1, 25, 2, 2)]
arg_dict["upscale_factor"] = [5]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
if __name__ == "__main__":
unittest.main()
| [
"oneflow.experimental.nn.PixelShuffle",
"oneflow.experimental.unittest.env.eager_execution_enabled",
"oneflow.experimental.device"
] | [((1022, 1087), 'numpy.reshape', 'np.reshape', (['input', '[_batch, _new_c, factor ** 2, _height, _width]'], {}), '(input, [_batch, _new_c, factor ** 2, _height, _width])\n', (1032, 1087), True, 'import numpy as np\n'), ((1098, 1164), 'numpy.reshape', 'np.reshape', (['out', '[_batch, _new_c, factor, factor, _height, _width]'], {}), '(out, [_batch, _new_c, factor, factor, _height, _width])\n', (1108, 1164), True, 'import numpy as np\n'), ((1175, 1212), 'numpy.transpose', 'np.transpose', (['out', '[0, 1, 4, 2, 5, 3]'], {}), '(out, [0, 1, 4, 2, 5, 3])\n', (1187, 1212), True, 'import numpy as np\n'), ((1223, 1291), 'numpy.reshape', 'np.reshape', (['out', '[_batch, _new_c, _height * factor, _width * factor]'], {}), '(out, [_batch, _new_c, _height * factor, _width * factor])\n', (1233, 1291), True, 'import numpy as np\n'), ((1569, 1619), 'numpy.ones', 'np.ones', ([], {'shape': '(_batch, _channel, _height, _width)'}), '(shape=(_batch, _channel, _height, _width))\n', (1576, 1619), True, 'import numpy as np\n'), ((1717, 1740), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (1732, 1740), True, 'import numpy as np\n'), ((1859, 1895), 'oneflow.experimental.nn.PixelShuffle', 'flow.nn.PixelShuffle', (['upscale_factor'], {}), '(upscale_factor)\n', (1879, 1895), True, 'import oneflow.experimental as flow\n'), ((3029, 3044), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3042, 3044), False, 'import unittest\n'), ((2481, 2494), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2492, 2494), False, 'from collections import OrderedDict\n'), ((2750, 2770), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (2760, 2770), False, 'from test_util import GenArgList\n'), ((2934, 2954), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (2944, 2954), False, 'from test_util import GenArgList\n'), ((2280, 2323), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (2321, 2323), True, 'import oneflow.experimental as flow\n'), ((1824, 1843), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (1835, 1843), True, 'import oneflow.experimental as flow\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 logging
import os
import time
from enum import Enum
from typing import Optional, Union
import oneflow as flow
from filelock import FileLock
from oneflow.utils.data import Dataset
from libai.data.structures import DistTensorData, Instance
from .utils import EncodePattern
from .utils_clue import clue_convert_examples_to_features, clue_output_modes, clue_processors
logger = logging.getLogger(__name__)
class Split(Enum):
train = "train"
dev = "dev"
test = "test"
class ClueDataset(Dataset):
def __init__(
self,
task_name,
data_dir,
tokenizer,
max_seq_length: int = 128,
mode: Union[str, Split] = Split.train,
pattern: Union[str, EncodePattern] = EncodePattern.bert_pattern,
cache_dir: Optional[str] = None,
overwrite_cache: bool = True,
):
self.processor = clue_processors[task_name]()
self.output_mode = clue_output_modes[task_name]
if isinstance(mode, str):
try:
mode = Split[mode]
except KeyError:
raise KeyError("mode is not a valid split name")
# Load data features from cache or dataset file
cached_features_file = os.path.join(
cache_dir if cache_dir is not None else data_dir,
f"cached_{mode.value}_{tokenizer.__class__.__name__}_{max_seq_length}_{task_name}",
)
label_list = self.processor.get_labels()
self.label_list = label_list
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
lock_path = cached_features_file + ".lock"
with FileLock(lock_path):
if os.path.exists(cached_features_file) and not overwrite_cache:
start = time.time()
self.features = flow.load(cached_features_file)
logger.info(
f"Loading features from cached file {cached_features_file} [took %.3f s]",
time.time() - start,
)
else:
logger.info(f"Creating features from dataset file at {data_dir}")
if mode == Split.dev:
examples = self.processor.get_dev_examples(data_dir)
elif mode == Split.test:
examples = self.processor.get_test_examples(data_dir)
else:
examples = self.processor.get_train_examples(data_dir)
self.features = clue_convert_examples_to_features(
examples,
tokenizer,
max_length=max_seq_length,
pattern=pattern,
label_list=label_list,
output_mode=self.output_mode,
)
start = time.time()
flow.save(self.features, cached_features_file)
logger.info(
f"Saving features into cached file {cached_features_file} "
f"[took {time.time() - start:.3f} s]"
)
def __len__(self):
return len(self.features)
def __getitem__(self, i):
feature = self.features[i]
tensors = {}
for k, v in feature.__dict__.items():
if v is not None:
if k == "labels":
dtype = flow.long if isinstance(v, int) else flow.float
t = flow.tensor(v, dtype=dtype)
tensors[k] = DistTensorData(t, placement_idx=-1)
else:
t = flow.tensor(v, dtype=flow.long)
tensors[k] = DistTensorData(t)
sample = Instance(**tensors)
return sample
def get_labels(self):
return self.label_list
| [
"oneflow.save",
"oneflow.load",
"oneflow.tensor"
] | [((1006, 1033), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1023, 1033), False, 'import logging\n'), ((1845, 2000), 'os.path.join', 'os.path.join', (['(cache_dir if cache_dir is not None else data_dir)', 'f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{max_seq_length}_{task_name}"""'], {}), "(cache_dir if cache_dir is not None else data_dir,\n f'cached_{mode.value}_{tokenizer.__class__.__name__}_{max_seq_length}_{task_name}'\n )\n", (1857, 2000), False, 'import os\n'), ((4325, 4344), 'libai.data.structures.Instance', 'Instance', ([], {}), '(**tensors)\n', (4333, 4344), False, 'from libai.data.structures import DistTensorData, Instance\n'), ((2313, 2332), 'filelock.FileLock', 'FileLock', (['lock_path'], {}), '(lock_path)\n', (2321, 2332), False, 'from filelock import FileLock\n'), ((2350, 2386), 'os.path.exists', 'os.path.exists', (['cached_features_file'], {}), '(cached_features_file)\n', (2364, 2386), False, 'import os\n'), ((2436, 2447), 'time.time', 'time.time', ([], {}), '()\n', (2445, 2447), False, 'import time\n'), ((2480, 2511), 'oneflow.load', 'flow.load', (['cached_features_file'], {}), '(cached_features_file)\n', (2489, 2511), True, 'import oneflow as flow\n'), ((3467, 3478), 'time.time', 'time.time', ([], {}), '()\n', (3476, 3478), False, 'import time\n'), ((3495, 3541), 'oneflow.save', 'flow.save', (['self.features', 'cached_features_file'], {}), '(self.features, cached_features_file)\n', (3504, 3541), True, 'import oneflow as flow\n'), ((4082, 4109), 'oneflow.tensor', 'flow.tensor', (['v'], {'dtype': 'dtype'}), '(v, dtype=dtype)\n', (4093, 4109), True, 'import oneflow as flow\n'), ((4143, 4178), 'libai.data.structures.DistTensorData', 'DistTensorData', (['t'], {'placement_idx': '(-1)'}), '(t, placement_idx=-1)\n', (4157, 4178), False, 'from libai.data.structures import DistTensorData, Instance\n'), ((4225, 4256), 'oneflow.tensor', 'flow.tensor', (['v'], {'dtype': 'flow.long'}), '(v, dtype=flow.long)\n', (4236, 4256), True, 'import oneflow as flow\n'), ((4290, 4307), 'libai.data.structures.DistTensorData', 'DistTensorData', (['t'], {}), '(t)\n', (4304, 4307), False, 'from libai.data.structures import DistTensorData, Instance\n'), ((2656, 2667), 'time.time', 'time.time', ([], {}), '()\n', (2665, 2667), False, 'import time\n'), ((3680, 3691), 'time.time', 'time.time', ([], {}), '()\n', (3689, 3691), 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.
"""
from typing import Optional
import oneflow as flow
from oneflow.python.oneflow_export import oneflow_export, experimental_api
from oneflow.python.nn.module import Module
from oneflow.python.nn.modules.utils import _pair
from oneflow.python.nn.common_types import _size_2_t
from oneflow.python.ops.nn_ops import calc_pool_padding, get_dhw_offset
@oneflow_export("nn.AvgPool2d")
@experimental_api
class AvgPool2d(Module):
r"""Performs the 2d-average pooling on the input.
In the simplest case, the output value of the layer with input size :math:`(N, C, H, W)`,
output :math:`(N, C, H_{out}, W_{out})` and `kernel_size` :math:`(kH, kW)`
can be precisely described as:
.. math::
out(N_i, C_j, h, w) = \frac{1}{kH * kW} \sum_{m=0}^{kH-1} \sum_{n=0}^{kW-1}
input(N_i, C_j, stride[0] \times h + m, stride[1] \times w + n)
Args:
kernel_size (Union[int, Tuple[int, int]]): An int or list of ints that has length 1, 2. The size of the window for each dimension of the input Tensor.
strides (Union[int, Tuple[int, int]]): An int or list of ints that has length 1, 2. The stride of the sliding window for each dimension of the input Tensor.
padding (Tuple[int, int]): An int or list of ints that has length 1, 2. Implicit zero padding to be added on both sides.
ceil_mode (bool, default to False): When True, will use ceil instead of floor to compute the output shape.
For example:
.. code-block:: python
import oneflow.experimental as flow
import numpy as np
of_avgpool2d = flow.nn.AvgPool2d(
kernel_size=(3, 2),
padding=0,
stride=(2, 1),
)
x = flow.Tensor(shape=(1, 1, 10, 10))
of_y = of_avgpool2d(x)
"""
def __init__(
self,
kernel_size: _size_2_t,
stride: Optional[_size_2_t] = None,
padding: _size_2_t = 0,
ceil_mode: bool = False,
count_include_pad: Optional[bool] = None,
divisor_override: Optional[int] = None,
name: Optional[str] = None,
):
super().__init__()
kernel_size = _pair(kernel_size)
stride = _pair(stride) if (stride is not None) else kernel_size
assert isinstance(padding, int) or isinstance(
padding, tuple
), "padding can only int int or tuple of 2 ints."
padding = _pair(padding)
padding = [0, 0, *padding]
assert count_include_pad is None, "count_include_pad not supported yet"
assert divisor_override is None, "divisor_override not supported yet"
_channel_pos = "channels_first"
# TODO(yaochi): align with pytorch when padding is asymmetric
_padding_type, _pads_list = calc_pool_padding(
padding, get_dhw_offset(_channel_pos), 2
)
_padding_before = [pad[0] for pad in _pads_list]
_padding_after = [pad[1] for pad in _pads_list]
self._op = (
flow.builtin_op("avg_pool_2d", name)
.Attr("data_format", _channel_pos)
.Attr("pool_size", kernel_size)
.Attr("strides", stride)
.Attr("ceil_mode", ceil_mode)
.Attr("padding", _padding_type)
.Attr("padding_before", _padding_before)
.Attr("padding_after", _padding_after)
.Input("x")
.Output("y")
.Build()
)
def forward(self, x):
res = self._op(x)[0]
return res
@oneflow_export("nn.MaxPool2d")
@experimental_api
class MaxPool2d(Module):
r"""Applies a 2D max pooling over an input signal composed of several input planes.
In the simplest case, the output value of the layer with input size :math:`(N, C, H, W)`,
output :math:`(N, C, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kH, kW)`
can be precisely described as:
.. math::
\begin{aligned}
out(N_i, C_j, h, w) ={} & \max_{m=0, \ldots, kH-1} \max_{n=0, \ldots, kW-1} \\
& \text{input}(N_i, C_j, \text{stride[0]} \times h + m,
\text{stride[1]} \times w + n)
\end{aligned}
If :attr:`padding` is non-zero, then the input is implicitly minimum value padded on both sides
for :attr:`padding` number of points. :attr:`dilation` controls the spacing between the kernel points.
It is harder to describe, but this `link`_ has a nice visualization of what :attr:`dilation` does.
Note:
When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
or the input. Sliding windows that would start in the right padded region are ignored.
The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be:
- a single ``int`` -- in which case the same value is used for the height and width dimension
- a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension,
and the second `int` for the width dimension
Args:
kernel_size: the size of the window to take a max over
stride: the stride of the window. Default value is :attr:`kernel_size`
padding: implicit minimum value padding to be added on both sides
dilation: a parameter that controls the stride of elements in the window
return_indices: if ``True``, will return the max indices along with the outputs.
Useful for :class:`torch.nn.MaxUnpool2d` later
ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
Shape:
- Input: :math:`(N, C, H_{in}, W_{in})`
- Output: :math:`(N, C, H_{out}, W_{out})`, where
.. math::
H_{out} = \left\lfloor\frac{H_{in} + 2 * \text{padding[0]} - \text{dilation[0]}
\times (\text{kernel_size[0]} - 1) - 1}{\text{stride[0]}} + 1\right\rfloor
.. math::
W_{out} = \left\lfloor\frac{W_{in} + 2 * \text{padding[1]} - \text{dilation[1]}
\times (\text{kernel_size[1]} - 1) - 1}{\text{stride[1]}} + 1\right\rfloor
For example:
.. code-block:: python
import oneflow.experimental as flow
import numpy as np
kernel_size, stride, padding = (4, 4), (1, 1), (1, 2)
m = flow.nn.MaxPool2d(kernel_size, stride, padding)
x = flow.Tensor(np.random.rand(6, 4, 7, 9))
y = m(x)
"""
def __init__(
self,
kernel_size: _size_2_t,
stride: Optional[_size_2_t] = None,
padding: _size_2_t = 0,
dilation: _size_2_t = 1,
return_indices: bool = False,
ceil_mode: bool = False,
):
super().__init__()
kernel_size = _pair(kernel_size)
strides = _pair(stride) if (stride is not None) else kernel_size
data_format = "NCHW"
channel_pos = "channels_last" if data_format == "NHWC" else "channels_first"
assert return_indices is False, "Only support return_indices==False for now!"
assert dilation == 1, "Only support dilation==1 for now!"
padding = _pair(padding)
if len(padding) == 2:
if data_format == "NCHW":
padding = (0, 0, padding[0], padding[1])
else:
raise ValueError("error padding param!")
else:
raise ValueError("error padding param!")
padding_type, pads_list = calc_pool_padding(
padding, get_dhw_offset(channel_pos), 2
)
padding_before = [pad[0] for pad in pads_list]
padding_after = [pad[1] for pad in pads_list]
self._op = (
flow.builtin_op("max_pool_2d")
.Attr("data_format", channel_pos)
.Attr("pool_size", kernel_size)
.Attr("strides", strides)
.Attr("ceil_mode", ceil_mode)
.Attr("padding", padding_type)
.Attr("padding_before", padding_before)
.Attr("padding_after", padding_after)
.Input("x")
.Output("y")
.Build()
)
def forward(self, x):
return self._op(x)[0]
| [
"oneflow.builtin_op",
"oneflow.python.nn.modules.utils._pair",
"oneflow.python.ops.nn_ops.get_dhw_offset",
"oneflow.python.oneflow_export.oneflow_export"
] | [((939, 969), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""nn.AvgPool2d"""'], {}), "('nn.AvgPool2d')\n", (953, 969), False, 'from oneflow.python.oneflow_export import oneflow_export, experimental_api\n'), ((4104, 4134), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""nn.MaxPool2d"""'], {}), "('nn.MaxPool2d')\n", (4118, 4134), False, 'from oneflow.python.oneflow_export import oneflow_export, experimental_api\n'), ((2756, 2774), 'oneflow.python.nn.modules.utils._pair', '_pair', (['kernel_size'], {}), '(kernel_size)\n', (2761, 2774), False, 'from oneflow.python.nn.modules.utils import _pair\n'), ((3006, 3020), 'oneflow.python.nn.modules.utils._pair', '_pair', (['padding'], {}), '(padding)\n', (3011, 3020), False, 'from oneflow.python.nn.modules.utils import _pair\n'), ((7419, 7437), 'oneflow.python.nn.modules.utils._pair', '_pair', (['kernel_size'], {}), '(kernel_size)\n', (7424, 7437), False, 'from oneflow.python.nn.modules.utils import _pair\n'), ((7797, 7811), 'oneflow.python.nn.modules.utils._pair', '_pair', (['padding'], {}), '(padding)\n', (7802, 7811), False, 'from oneflow.python.nn.modules.utils import _pair\n'), ((2792, 2805), 'oneflow.python.nn.modules.utils._pair', '_pair', (['stride'], {}), '(stride)\n', (2797, 2805), False, 'from oneflow.python.nn.modules.utils import _pair\n'), ((3402, 3430), 'oneflow.python.ops.nn_ops.get_dhw_offset', 'get_dhw_offset', (['_channel_pos'], {}), '(_channel_pos)\n', (3416, 3430), False, 'from oneflow.python.ops.nn_ops import calc_pool_padding, get_dhw_offset\n'), ((7456, 7469), 'oneflow.python.nn.modules.utils._pair', '_pair', (['stride'], {}), '(stride)\n', (7461, 7469), False, 'from oneflow.python.nn.modules.utils import _pair\n'), ((8154, 8181), 'oneflow.python.ops.nn_ops.get_dhw_offset', 'get_dhw_offset', (['channel_pos'], {}), '(channel_pos)\n', (8168, 8181), False, 'from oneflow.python.ops.nn_ops import calc_pool_padding, get_dhw_offset\n'), ((3591, 3627), 'oneflow.builtin_op', 'flow.builtin_op', (['"""avg_pool_2d"""', 'name'], {}), "('avg_pool_2d', name)\n", (3606, 3627), True, 'import oneflow as flow\n'), ((8338, 8368), 'oneflow.builtin_op', 'flow.builtin_op', (['"""max_pool_2d"""'], {}), "('max_pool_2d')\n", (8353, 8368), 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.
"""
from oneflow.compatible import single_client as flow
from oneflow.compatible.single_client.python.nn.module import Module
from oneflow.compatible.single_client.python.oneflow_export import (
oneflow_export,
experimental_api,
)
from oneflow.compatible.single_client.python.framework.tensor import register_tensor_op
from typing import Optional, Sequence
class Transpose(Module):
def __init__(
self, dim0, dim1, conjugate: bool = False, batch_axis_non_change: bool = False,
) -> None:
super().__init__()
if conjugate:
raise NotImplementedError
if batch_axis_non_change:
raise NotImplementedError
self.dim0 = dim0
self.dim1 = dim1
def forward(self, x):
x_shape = x.shape
dim0 = self.dim0
dim1 = self.dim1
if dim0 < 0:
dim0 += len(x_shape)
if dim1 < 0:
dim1 += len(x_shape)
assert dim0 >= 0 and dim0 < len(
x_shape
), "Invalid dim0 {}, len(shape): {}".format(dim0, len(x_shape))
assert dim1 >= 0 and dim1 < len(
x_shape
), "Invalid dim1 {}, len(shape): {}".format(dim1, len(x_shape))
perm = []
for i in range(len(x_shape)):
perm.append(i)
perm[dim0], perm[dim1] = perm[dim1], perm[dim0]
return flow.F.transpose(x, perm=perm)
@oneflow_export("transpose")
@register_tensor_op("transpose")
@experimental_api
def transpose_op(tensor, dim0, dim1):
r"""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:
tensor (oneflow.compatible.single_client.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.compatible.single_client.experimental as flow
>>> flow.enable_eager_execution()
>>> input = flow.Tensor(np.random.randn(2, 6, 5, 3), dtype=flow.float32)
>>> out = flow.transpose(input, 0, 1).shape
>>> out
flow.Size([6, 2, 5, 3])
"""
return Transpose(dim0=dim0, dim1=dim1)(tensor)
if __name__ == "__main__":
import doctest
doctest.testmod(raise_on_error=True)
| [
"oneflow.compatible.single_client.F.transpose",
"oneflow.compatible.single_client.python.framework.tensor.register_tensor_op",
"oneflow.compatible.single_client.python.oneflow_export.oneflow_export"
] | [((1978, 2005), 'oneflow.compatible.single_client.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""transpose"""'], {}), "('transpose')\n", (1992, 2005), False, 'from oneflow.compatible.single_client.python.oneflow_export import oneflow_export, experimental_api\n'), ((2007, 2038), 'oneflow.compatible.single_client.python.framework.tensor.register_tensor_op', 'register_tensor_op', (['"""transpose"""'], {}), "('transpose')\n", (2025, 2038), False, 'from oneflow.compatible.single_client.python.framework.tensor import register_tensor_op\n'), ((3102, 3138), 'doctest.testmod', 'doctest.testmod', ([], {'raise_on_error': '(True)'}), '(raise_on_error=True)\n', (3117, 3138), False, 'import doctest\n'), ((1944, 1974), 'oneflow.compatible.single_client.F.transpose', 'flow.F.transpose', (['x'], {'perm': 'perm'}), '(x, perm=perm)\n', (1960, 1974), True, 'from oneflow.compatible import single_client 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.
"""
from typing import Optional
import oneflow._oneflow_internal
from oneflow.compatible import single_client as flow
from oneflow.compatible.single_client.framework import id_util as id_util
from oneflow.compatible.single_client.framework import remote_blob as remote_blob_util
def diag(
input: oneflow._oneflow_internal.BlobDesc,
diagonal: Optional[int] = 0,
name: Optional[str] = None,
) -> oneflow._oneflow_internal.BlobDesc:
"""This operator compute diagonal.
If input is a vector, then returns a square matrix with the elements of input as the diagonal.
If input is a matrix, then returns a vector with the diagonal elements of input.
Args:
input (remote_blob_util.BlobDef): The input Blob.
diagonal (Optional[int], 0): The diagonal to consider. Defaults to 0.
- 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.
Returns:
remote_blob_util.BlobDef: The result Blob.
For example:
.. code-block:: python
import oneflow.compatible.single_client as flow
import numpy as np
import oneflow.compatible.single_client.typing as tp
@flow.global_function()
def Diag_Job(input: tp.Numpy.Placeholder((3, 3), dtype=flow.float32),) -> tp.Numpy:
return flow.diag(input)
input = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0],], dtype=np.float32)
out = Diag_Job(input)
# out [1. 5. 9.]
"""
return (
flow.user_op_builder(name if name is not None else id_util.UniqueStr("Diag_"))
.Op("diag")
.Input("in", [input])
.Attr("diagonal", int(diagonal))
.Output("out")
.Build()
.InferAndTryRun()
.RemoteBlobList()[0]
)
| [
"oneflow.compatible.single_client.framework.id_util.UniqueStr"
] | [((2292, 2318), 'oneflow.compatible.single_client.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""Diag_"""'], {}), "('Diag_')\n", (2309, 2318), True, 'from oneflow.compatible.single_client.framework import id_util as id_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.
"""
import unittest
import oneflow as flow
import oneflow.unittest
@flow.unittest.skip_unless_1n1d()
class TestModule(flow.unittest.TestCase):
def test_reshape_exception_only_one_dim_infered(test_case):
# torch exception and messge:
#
# RuntimeError: only one dimension can be inferred
#
x = flow.tensor((2, 2))
with test_case.assertRaises(RuntimeError) as ctx:
y = x.reshape((-1, -1))
test_case.assertTrue("only one dimension can be inferred" in str(ctx.exception))
if __name__ == "__main__":
unittest.main()
| [
"oneflow.unittest.skip_unless_1n1d",
"oneflow.tensor"
] | [((658, 690), 'oneflow.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (688, 690), True, 'import oneflow as flow\n'), ((1164, 1179), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1177, 1179), False, 'import unittest\n'), ((928, 947), 'oneflow.tensor', 'flow.tensor', (['(2, 2)'], {}), '((2, 2))\n', (939, 947), 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 as flow
from oneflow import nn
from oneflow.nn import Module
from math import sqrt
class RNN(Module):
"""The interface is consistent with PyTorch.
The documentation is referenced from: https://pytorch.org/docs/stable/generated/torch.nn.RNN.html#torch.nn.RNN
Applies a multi-layer Elman RNN with \tanhtanh or \text{ReLU}ReLU non-linearity to an input sequence.
For each element in the input sequence, each layer computes the following function:
function:
.. math::
h_t = \tanh(W_{ih} x_t + b_{ih} + W_{hh} h_{(t-1)} + b_{hh})
where :math:`h_t` is the hidden state at time `t`, :math:`x_t` is
the input at time `t`, and :math:`h_{(t-1)}` is the hidden state of the
previous layer at time `t-1` or the initial hidden state at time `0`.
If :attr:`nonlinearity` is ``'relu'``, then :math:`\text{ReLU}` is used instead of :math:`\tanh`.
Args:
input_size: The number of expected features in the input `x`
hidden_size: The number of features in the hidden state `h`
num_layers: Number of recurrent layers. E.g., setting ``num_layers=2``
would mean stacking two RNNs together to form a `stacked RNN`,
with the second RNN taking in outputs of the first RNN and
computing the final results. Default: 1
nonlinearity: The non-linearity to use. Can be either ``'tanh'`` or ``'relu'``. Default: ``'tanh'``
bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`.
Default: ``True``
batch_first: If ``True``, then the input and output tensors are provided
as `(batch, seq, feature)` instead of `(seq, batch, feature)`.
Note that this does not apply to hidden or cell states. See the
Inputs/Outputs sections below for details. Default: ``False``
dropout: If non-zero, introduces a `Dropout` layer on the outputs of each
RNN layer except the last layer, with dropout probability equal to
:attr:`dropout`. Default: 0
bidirectional: If ``True``, becomes a bidirectional RNN. Default: ``False``
Inputs: input, h_0
* **input**: tensor of shape :math:`(L, N, H_{in})` when ``batch_first=False`` or
:math:`(N, L, H_{in})` when ``batch_first=True`` containing the features of
the input sequence.
* **h_0**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{out})` containing the initial hidden
state for each element in the batch. Defaults to zeros if not provided.
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input\_size} \\
H_{out} ={} & \text{hidden\_size}
\end{aligned}
Outputs: output, h_n
* **output**: tensor of shape :math:`(L, N, D * H_{out})` when ``batch_first=False`` or
:math:`(N, L, D * H_{out})` when ``batch_first=True`` containing the output features
`(h_t)` from the last layer of the RNN, for each `t`.
* **h_n**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{out})` containing the final hidden state
for each element in the batch.
Attributes:
weight_ih_l[k]: the learnable input-hidden weights of the k-th layer,
of shape `(hidden_size, input_size)` for `k = 0`. Otherwise, the shape is
`(hidden_size, num_directions * hidden_size)`
weight_hh_l[k]: the learnable hidden-hidden weights of the k-th layer,
of shape `(hidden_size, hidden_size)`
bias_ih_l[k]: the learnable input-hidden bias of the k-th layer,
of shape `(hidden_size)`
bias_hh_l[k]: the learnable hidden-hidden bias of the k-th layer,
of shape `(hidden_size)`
.. note::
All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`
where :math:`k = \frac{1}{\text{hidden\_size}}`
.. note::
For bidirectional RNNs, forward and backward are directions 0 and 1 respectively.
Example of splitting the output layers when ``batch_first=False``:
``output.view((seq_len, batch, num_directions, hidden_size))``.
# For example:
# .. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> rnn = flow.nn.RNN(10, 20, 2)
>>> input = flow.tensor(np.random.randn(5, 3, 10), dtype=flow.float32)
>>> h0 = flow.tensor(np.random.randn(2, 3, 20), dtype=flow.float32)
>>> output, hn = rnn(input, h0)
>>> output.size()
oneflow.Size([5, 3, 20])
"""
def __init__(
self,
input_size: int,
hidden_size: int,
num_layers: int = 1,
nonlinearity: str = "tanh",
bias: bool = True,
batch_first: bool = False,
dropout: float = 0,
bidirectional: bool = False,
):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.nonlinearity = nonlinearity
self.bias = bias
self.batch_first = batch_first
self.dropout = dropout
self.bidirectional = bidirectional
num_directions = 2 if bidirectional else 1
gate_size = hidden_size
self.drop = nn.Dropout(self.dropout)
if self.nonlinearity == "tanh":
self.act = nn.Tanh()
elif self.nonlinearity == "relu":
self.act = nn.ReLU()
else:
raise ValueError("Unknown nonlinearity '{}'".format(self.nonlinearity))
for layer in range(num_layers):
for direction in range(num_directions):
real_hidden_size = hidden_size
layer_input_size = (
input_size if layer == 0 else real_hidden_size * num_directions
)
# TODO: Modify after adding the stride attribute
# w_ih = flow.nn.Parameter(flow.Tensor(gate_size, layer_input_size))
# w_hh = flow.nn.Parameter(flow.Tensor(gate_size, real_hidden_size))
# b_ih = flow.nn.Parameter(flow.Tensor(gate_size))
# b_hh = flow.nn.Parameter(flow.Tensor(gate_size))
w_ih = flow.nn.Parameter(flow.Tensor(layer_input_size, gate_size))
w_hh = flow.nn.Parameter(flow.Tensor(real_hidden_size, gate_size))
b_ih = flow.nn.Parameter(flow.Tensor(gate_size))
b_hh = flow.nn.Parameter(flow.Tensor(gate_size))
layer_params = ()
if bias:
layer_params = (w_ih, w_hh, b_ih, b_hh)
else:
layer_params = (w_ih, w_hh)
suffix = "_reverse" if direction == 1 else ""
param_names = ["weight_ih_l{}{}", "weight_hh_l{}{}"]
if bias:
param_names += ["bias_ih_l{}{}", "bias_hh_l{}{}"]
param_names = [x.format(layer, suffix) for x in param_names]
for name, param in zip(param_names, layer_params):
setattr(self, name, param)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / sqrt(self.hidden_size)
for weight in self.parameters():
weight.uniform_(-stdv, stdv)
def permute_tensor(self, input):
return input.permute(1, 0, 2)
def forward(self, input, h_0=None):
if self.batch_first == False:
input = self.permute_tensor(input)
D = 2 if self.bidirectional else 1
num_layers = self.num_layers
batch_size, seq_len, _ = input.size()
if h_0 is None:
h_t = flow.zeros(
(D * num_layers, batch_size, self.hidden_size),
dtype=input.dtype,
device=input.device,
)
else:
h_t = h_0
if self.bidirectional:
if h_0 is None:
h_t_f = h_t[:num_layers, :, :]
h_t_b = h_t[num_layers:, :, :]
else:
h_t_f = flow.cat(
[
h_t[l, :, :].unsqueeze(0)
for l in range(h_t.size(0))
if l % 2 == 0
],
dim=0,
)
h_t_b = flow.cat(
[
h_t[l, :, :].unsqueeze(0)
for l in range(h_t.size(0))
if l % 2 != 0
],
dim=0,
)
else:
h_t_f = h_t
layer_hidden = []
for layer in range(self.num_layers):
hidden_seq_f = []
if self.bidirectional:
hidden_seq_b = []
hid_t_f = h_t_f[layer, :, :]
if self.bidirectional:
hid_t_b = h_t_b[layer, :, :]
for t in range(seq_len):
if layer == 0:
x_t_f = input[:, t, :]
if self.bidirectional:
x_t_b = input[:, seq_len - 1 - t, :]
else:
x_t_f = hidden_seq[:, t, :]
if self.bidirectional:
x_t_b = hidden_seq[:, seq_len - 1 - t, :]
# TODO: Modify after adding the stride attribute
# hy1_f = flow.matmul(
# x_t_f,
# getattr(self, "weight_ih_l{}{}".format(layer, "")).permute(1, 0),
# )
# hy2_f = flow.matmul(
# hid_t_f,
# getattr(self, "weight_hh_l{}{}".format(layer, "")).permute(1, 0),
# )
hy1_f = flow.matmul(
x_t_f, getattr(self, "weight_ih_l{}{}".format(layer, "")),
)
hy2_f = flow.matmul(
hid_t_f, getattr(self, "weight_hh_l{}{}".format(layer, "")),
)
if self.bias:
hy1_f += getattr(self, "bias_ih_l{}{}".format(layer, ""))
hy2_f += getattr(self, "bias_hh_l{}{}".format(layer, ""))
hid_t_f = self.act(hy1_f + hy2_f)
hidden_seq_f.append(hid_t_f.unsqueeze(1))
if self.bidirectional:
# TODO:Modify after adding the stride attribute
# hy1_b = flow.matmul(
# x_t_b,
# getattr(
# self, "weight_ih_l{}{}".format(layer, "_reverse")
# ).permute(1, 0),
# )
# hy2_b = flow.matmul(
# hid_t_b,
# getattr(
# self, "weight_hh_l{}{}".format(layer, "_reverse")
# ).permute(1, 0),
# )
hy1_b = flow.matmul(
x_t_b,
getattr(self, "weight_ih_l{}{}".format(layer, "_reverse")),
)
hy2_b = flow.matmul(
hid_t_b,
getattr(self, "weight_hh_l{}{}".format(layer, "_reverse")),
)
if self.bias:
hy1_b += getattr(
self, "bias_ih_l{}{}".format(layer, "_reverse")
)
hy2_b += getattr(
self, "bias_hh_l{}{}".format(layer, "_reverse")
)
hid_t_b = self.act(hy1_b + hy2_b)
hidden_seq_b.insert(0, hid_t_b.unsqueeze(1))
hidden_seq_f = flow.cat(hidden_seq_f, dim=1)
if self.bidirectional:
hidden_seq_b = flow.cat(hidden_seq_b, dim=1)
if self.dropout != 0 and layer != self.num_layers - 1:
hidden_seq_f = self.drop(hidden_seq_f)
if self.bidirectional:
hidden_seq_b = self.drop(hidden_seq_b)
if self.bidirectional:
hidden_seq = flow.cat([hidden_seq_f, hidden_seq_b], dim=2)
else:
hidden_seq = hidden_seq_f
if self.bidirectional:
h_t = flow.cat([hid_t_f.unsqueeze(0), hid_t_b.unsqueeze(0)], dim=0)
else:
h_t = hid_t_f.unsqueeze(0)
layer_hidden.append(h_t)
h_t = flow.cat(layer_hidden, dim=0)
if self.batch_first == False:
hidden_seq = self.permute_tensor(hidden_seq)
return hidden_seq, h_t
class GRU(Module):
"""The interface is consistent with PyTorch.
The documentation is referenced from: https://pytorch.org/docs/stable/_modules/torch/nn/modules/rnn.html#GRU
Applies a multi-layer gated recurrent unit (GRU) RNN to an input sequence.
For each element in the input sequence, each layer computes the following
function:
.. math::
\begin{array}{ll}
r_t = \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\
z_t = \sigma(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\
n_t = \tanh(W_{in} x_t + b_{in} + r_t * (W_{hn} h_{(t-1)}+ b_{hn})) \\
h_t = (1 - z_t) * n_t + z_t * h_{(t-1)}
\end{array}
where :math:`h_t` is the hidden state at time `t`, :math:`x_t` is the input
at time `t`, :math:`h_{(t-1)}` is the hidden state of the layer
at time `t-1` or the initial hidden state at time `0`, and :math:`r_t`,
:math:`z_t`, :math:`n_t` are the reset, update, and new gates, respectively.
:math:`\sigma` is the sigmoid function, and :math:`*` is the Hadamard product.
In a multilayer GRU, the input :math:`x^{(l)}_t` of the :math:`l` -th layer
(:math:`l >= 2`) is the hidden state :math:`h^{(l-1)}_t` of the previous layer multiplied by
dropout :math:`\delta^{(l-1)}_t` where each :math:`\delta^{(l-1)}_t` is a Bernoulli random
variable which is :math:`0` with probability :attr:`dropout`.
Args:
input_size: The number of expected features in the input `x`
hidden_size: The number of features in the hidden state `h`
num_layers: Number of recurrent layers. E.g., setting ``num_layers=2``
would mean stacking two GRUs together to form a `stacked GRU`,
with the second GRU taking in outputs of the first GRU and
computing the final results. Default: 1
bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`.
Default: ``True``
batch_first: If ``True``, then the input and output tensors are provided
as `(batch, seq, feature)` instead of `(seq, batch, feature)`.
Note that this does not apply to hidden or cell states. See the
Inputs/Outputs sections below for details. Default: ``False``
dropout: If non-zero, introduces a `Dropout` layer on the outputs of each
GRU layer except the last layer, with dropout probability equal to
:attr:`dropout`. Default: 0
bidirectional: If ``True``, becomes a bidirectional GRU. Default: ``False``
Inputs: input, h_0
* **input**: tensor of shape :math:`(L, N, H_{in})` when ``batch_first=False`` or
:math:`(N, L, H_{in})` when ``batch_first=True`` containing the features of
the input sequence.
* **h_0**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{out})` containing the initial hidden
state for each element in the batch. Defaults to zeros if not provided.
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input\_size} \\
H_{out} ={} & \text{hidden\_size}
\end{aligned}
Outputs: output, h_n
* **output**: tensor of shape :math:`(L, N, D * H_{out})` when ``batch_first=False`` or
:math:`(N, L, D * H_{out})` when ``batch_first=True`` containing the output features
`(h_t)` from the last layer of the GRU, for each `t`. If a
* **h_n**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{out})` containing the final hidden state
for each element in the batch.
Attributes:
weight_ih_l[k] : the learnable input-hidden weights of the :math:`\text{k}^{th}` layer
(W_ir|W_iz|W_in), of shape `(3*hidden_size, input_size)` for `k = 0`.
Otherwise, the shape is `(3*hidden_size, num_directions * hidden_size)`
weight_hh_l[k] : the learnable hidden-hidden weights of the :math:`\text{k}^{th}` layer
(W_hr|W_hz|W_hn), of shape `(3*hidden_size, hidden_size)`
bias_ih_l[k] : the learnable input-hidden bias of the :math:`\text{k}^{th}` layer
(b_ir|b_iz|b_in), of shape `(3*hidden_size)`
bias_hh_l[k] : the learnable hidden-hidden bias of the :math:`\text{k}^{th}` layer
(b_hr|b_hz|b_hn), of shape `(3*hidden_size)`
.. note::
All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`
where :math:`k = \frac{1}{\text{hidden\_size}}`
.. note::
For bidirectional GRUs, forward and backward are directions 0 and 1 respectively.
Example of splitting the output layers when ``batch_first=False``:
``output.view(seq_len, batch, num_directions, hidden_size)``.
# For example:
# .. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> rnn = flow.nn.GRU(10, 20, 2)
>>> input = flow.tensor(np.random.randn(5, 3, 10), dtype=flow.float32)
>>> h0 = flow.tensor(np.random.randn(2, 3, 20), dtype=flow.float32)
>>> output, hn = rnn(input, h0)
>>> output.size()
oneflow.Size([5, 3, 20])
"""
def __init__(
self,
input_size: int,
hidden_size: int,
num_layers: int = 1,
bias: bool = True,
batch_first: bool = False,
dropout: float = 0,
bidirectional: bool = False,
):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.bias = bias
self.batch_first = batch_first
self.dropout = dropout
self.bidirectional = bidirectional
num_directions = 2 if bidirectional else 1
gate_size = 3 * hidden_size
self.drop = nn.Dropout(self.dropout)
for layer in range(num_layers):
for direction in range(num_directions):
real_hidden_size = hidden_size
layer_input_size = (
input_size if layer == 0 else real_hidden_size * num_directions
)
# TODO: Modify after adding the stride attribute
# w_ih = flow.nn.Parameter(flow.Tensor(gate_size, layer_input_size))
# w_hh = flow.nn.Parameter(flow.Tensor(gate_size, real_hidden_size))
# b_ih = flow.nn.Parameter(flow.Tensor(gate_size))
# b_hh = flow.nn.Parameter(flow.Tensor(gate_size))
w_ih = flow.nn.Parameter(flow.Tensor(layer_input_size, gate_size))
w_hh = flow.nn.Parameter(flow.Tensor(real_hidden_size, gate_size))
b_ih = flow.nn.Parameter(flow.Tensor(gate_size))
b_hh = flow.nn.Parameter(flow.Tensor(gate_size))
layer_params = ()
if bias:
layer_params = (w_ih, w_hh, b_ih, b_hh)
else:
layer_params = (w_ih, w_hh)
suffix = "_reverse" if direction == 1 else ""
param_names = ["weight_ih_l{}{}", "weight_hh_l{}{}"]
if bias:
param_names += ["bias_ih_l{}{}", "bias_hh_l{}{}"]
param_names = [x.format(layer, suffix) for x in param_names]
for name, param in zip(param_names, layer_params):
setattr(self, name, param)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / sqrt(self.hidden_size)
for weight in self.parameters():
weight.uniform_(-stdv, stdv)
def permute_tensor(self, input):
return input.permute(1, 0, 2)
def forward(self, input, h_0=None):
if self.batch_first == False:
input = self.permute_tensor(input)
D = 2 if self.bidirectional else 1
num_layers = self.num_layers
batch_size, seq_len, _ = input.size()
if h_0 is None:
h_t = flow.zeros(
(D * num_layers, batch_size, self.hidden_size),
dtype=input.dtype,
device=input.device,
)
else:
h_t = h_0
if self.bidirectional:
if h_0 is None:
h_t_f = h_t[:num_layers, :, :]
h_t_b = h_t[num_layers:, :, :]
else:
h_t_f = flow.cat(
[
h_t[l, :, :].unsqueeze(0)
for l in range(h_t.size(0))
if l % 2 == 0
],
dim=0,
)
h_t_b = flow.cat(
[
h_t[l, :, :].unsqueeze(0)
for l in range(h_t.size(0))
if l % 2 != 0
],
dim=0,
)
else:
h_t_f = h_t
layer_hidden = []
for layer in range(self.num_layers):
hidden_seq_f = []
if self.bidirectional:
hidden_seq_b = []
hid_t_f = h_t_f[layer, :, :]
if self.bidirectional:
hid_t_b = h_t_b[layer, :, :]
for t in range(seq_len):
if layer == 0:
x_t_f = input[:, t, :]
if self.bidirectional:
x_t_b = input[:, seq_len - 1 - t, :]
else:
x_t_f = hidden_seq[:, t, :]
if self.bidirectional:
x_t_b = hidden_seq[:, seq_len - 1 - t, :]
# TODO: Modify after adding the stride attribute
# gi_f = flow.matmul(
# x_t_f,
# getattr(self, "weight_ih_l{}{}".format(layer, "")).permute(1, 0),
# )
# gh_f = flow.matmul(
# hid_t_f,
# getattr(self, "weight_hh_l{}{}".format(layer, "")).permute(1, 0),
# )
gi_f = flow.matmul(
x_t_f, getattr(self, "weight_ih_l{}{}".format(layer, "")),
)
gh_f = flow.matmul(
hid_t_f, getattr(self, "weight_hh_l{}{}".format(layer, "")),
)
if self.bias:
gi_f += getattr(self, "bias_ih_l{}{}".format(layer, ""))
gh_f += getattr(self, "bias_hh_l{}{}".format(layer, ""))
i_r_f, i_i_f, i_n_f = gi_f.chunk(3, dim=1)
h_r_f, h_i_f, h_n_f = gh_f.chunk(3, dim=1)
resetgate_f = flow.sigmoid(i_r_f + h_r_f)
inputgate_f = flow.sigmoid(i_i_f + h_i_f)
newgate_f = flow.tanh(i_n_f + resetgate_f * h_n_f)
hid_t_f = newgate_f + inputgate_f * (hid_t_f - newgate_f)
hidden_seq_f.append(hid_t_f.unsqueeze(1))
if self.bidirectional:
# TODO:Modify after adding the stride attribute
# gi_b = flow.matmul(
# x_t_b,
# getattr(
# self, "weight_ih_l{}{}".format(layer, "_reverse")
# ).permute(1, 0),
# )
# gh_b = flow.matmul(
# hid_t_b,
# getattr(
# self, "weight_hh_l{}{}".format(layer, "_reverse")
# ).permute(1, 0),
# )
gi_b = flow.matmul(
x_t_b,
getattr(self, "weight_ih_l{}{}".format(layer, "_reverse")),
)
gh_b = flow.matmul(
hid_t_b,
getattr(self, "weight_hh_l{}{}".format(layer, "_reverse")),
)
if self.bias:
gi_b += getattr(self, "bias_ih_l{}{}".format(layer, "_reverse"))
gh_b += getattr(self, "bias_hh_l{}{}".format(layer, "_reverse"))
i_r_b, i_i_b, i_n_b = gi_b.chunk(3, dim=1)
h_r_b, h_i_b, h_n_b = gh_b.chunk(3, dim=1)
resetgate_b = flow.sigmoid(i_r_b + h_r_b)
inputgate_b = flow.sigmoid(i_i_b + h_i_b)
newgate_b = flow.tanh(i_n_b + resetgate_b * h_n_b)
hid_t_b = newgate_b + inputgate_b * (hid_t_b - newgate_b)
hidden_seq_b.insert(0, hid_t_b.unsqueeze(1))
hidden_seq_f = flow.cat(hidden_seq_f, dim=1)
if self.bidirectional:
hidden_seq_b = flow.cat(hidden_seq_b, dim=1)
if self.dropout != 0 and layer != self.num_layers - 1:
hidden_seq_f = self.drop(hidden_seq_f)
if self.bidirectional:
hidden_seq_b = self.drop(hidden_seq_b)
if self.bidirectional:
hidden_seq = flow.cat([hidden_seq_f, hidden_seq_b], dim=2)
else:
hidden_seq = hidden_seq_f
if self.bidirectional:
h_t = flow.cat([hid_t_f.unsqueeze(0), hid_t_b.unsqueeze(0)], dim=0)
else:
h_t = hid_t_f.unsqueeze(0)
layer_hidden.append(h_t)
h_t = flow.cat(layer_hidden, dim=0)
if self.batch_first == False:
hidden_seq = self.permute_tensor(hidden_seq)
return hidden_seq, h_t
class LSTM(nn.Module):
"""The interface is consistent with PyTorch.
The documentation is referenced from: https://pytorch.org/docs/stable/_modules/torch/nn/modules/rnn.html#LSTM
Applies a multi-layer long short-term memory (LSTM) RNN to an input sequence.
For each element in the input sequence, each layer computes the following
function:
.. math::
\begin{array}{ll} \\
i_t = \sigma(W_{ii} x_t + b_{ii} + W_{hi} h_{t-1} + b_{hi}) \\
f_t = \sigma(W_{if} x_t + b_{if} + W_{hf} h_{t-1} + b_{hf}) \\
g_t = \tanh(W_{ig} x_t + b_{ig} + W_{hg} h_{t-1} + b_{hg}) \\
o_t = \sigma(W_{io} x_t + b_{io} + W_{ho} h_{t-1} + b_{ho}) \\
c_t = f_t \odot c_{t-1} + i_t \odot g_t \\
h_t = o_t \odot \tanh(c_t) \\
\end{array}
where :math:`h_t` is the hidden state at time `t`, :math:`c_t` is the cell
state at time `t`, :math:`x_t` is the input at time `t`, :math:`h_{t-1}`
is the hidden state of the layer at time `t-1` or the initial hidden
state at time `0`, and :math:`i_t`, :math:`f_t`, :math:`g_t`,
:math:`o_t` are the input, forget, cell, and output gates, respectively.
:math:`\sigma` is the sigmoid function, and :math:`\odot` is the Hadamard product.
In a multilayer LSTM, the input :math:`x^{(l)}_t` of the :math:`l` -th layer
(:math:`l >= 2`) is the hidden state :math:`h^{(l-1)}_t` of the previous layer multiplied by
dropout :math:`\delta^{(l-1)}_t` where each :math:`\delta^{(l-1)}_t` is a Bernoulli random
variable which is :math:`0` with probability :attr:`dropout`.
If ``proj_size > 0`` is specified, LSTM with projections will be used. This changes
the LSTM cell in the following way. First, the dimension of :math:`h_t` will be changed from
``hidden_size`` to ``proj_size`` (dimensions of :math:`W_{hi}` will be changed accordingly).
Second, the output hidden state of each layer will be multiplied by a learnable projection
matrix: :math:`h_t = W_{hr}h_t`. Note that as a consequence of this, the output
of LSTM network will be of different shape as well. See Inputs/Outputs sections below for exact
dimensions of all variables. You can find more details in https://arxiv.org/abs/1402.1128.
Args:
input_size: The number of expected features in the input `x`
hidden_size: The number of features in the hidden state `h`
num_layers: Number of recurrent layers. E.g., setting ``num_layers=2``
would mean stacking two LSTMs together to form a `stacked LSTM`,
with the second LSTM taking in outputs of the first LSTM and
computing the final results. Default: 1
bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`.
Default: ``True``
batch_first: If ``True``, then the input and output tensors are provided
as `(batch, seq, feature)` instead of `(seq, batch, feature)`.
Note that this does not apply to hidden or cell states. See the
Inputs/Outputs sections below for details. Default: ``False``
dropout: If non-zero, introduces a `Dropout` layer on the outputs of each
LSTM layer except the last layer, with dropout probability equal to
:attr:`dropout`. Default: 0
bidirectional: If ``True``, becomes a bidirectional LSTM. Default: ``False``
proj_size: If ``> 0``, will use LSTM with projections of corresponding size. Default: 0
Inputs: input, (h_0, c_0)
* **input**: tensor of shape :math:`(L, N, H_{in})` when ``batch_first=False`` or
:math:`(N, L, H_{in})` when ``batch_first=True`` containing the features of
the input sequence.
* **h_0**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{out})` containing the
initial hidden state for each element in the batch.
Defaults to zeros if (h_0, c_0) is not provided.
* **c_0**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{cell})` containing the
initial cell state for each element in the batch.
Defaults to zeros if (h_0, c_0) is not provided.
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input\_size} \\
H_{cell} ={} & \text{hidden\_size} \\
H_{out} ={} & \text{proj\_size if } \text{proj\_size}>0 \text{ otherwise hidden\_size} \\
\end{aligned}
Outputs: output, (h_n, c_n)
* **output**: tensor of shape :math:`(L, N, D * H_{out})` when ``batch_first=False`` or
:math:`(N, L, D * H_{out})` when ``batch_first=True`` containing the output features
`(h_t)` from the last layer of the LSTM, for each `t`.
* **h_n**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{out})` containing the
final hidden state for each element in the batch.
* **c_n**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{cell})` containing the
final cell state for each element in the batch.
Attributes:
weight_ih_l[k] : the learnable input-hidden weights of the :math:`\text{k}^{th}` layer
`(W_ii|W_if|W_ig|W_io)`, of shape `(4*hidden_size, input_size)` for `k = 0`.
Otherwise, the shape is `(4*hidden_size, num_directions * hidden_size)`
weight_hh_l[k] : the learnable hidden-hidden weights of the :math:`\text{k}^{th}` layer
`(W_hi|W_hf|W_hg|W_ho)`, of shape `(4*hidden_size, hidden_size)`. If ``proj_size > 0``
was specified, the shape will be `(4*hidden_size, proj_size)`.
bias_ih_l[k] : the learnable input-hidden bias of the :math:`\text{k}^{th}` layer
`(b_ii|b_if|b_ig|b_io)`, of shape `(4*hidden_size)`
bias_hh_l[k] : the learnable hidden-hidden bias of the :math:`\text{k}^{th}` layer
`(b_hi|b_hf|b_hg|b_ho)`, of shape `(4*hidden_size)`
weight_hr_l[k] : the learnable projection weights of the :math:`\text{k}^{th}` layer
of shape `(proj_size, hidden_size)`. Only present when ``proj_size > 0`` was
specified.
.. note::
All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`
where :math:`k = \frac{1}{\text{hidden\_size}}`
.. note::
For bidirectional LSTMs, forward and backward are directions 0 and 1 respectively.
Example of splitting the output layers when ``batch_first=False``:
``output.view(seq_len, batch, num_directions, hidden_size)``.
# For example:
# .. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> rnn = flow.nn.LSTM(10, 20, 2)
>>> input = flow.tensor(np.random.randn(5, 3, 10), dtype=flow.float32)
>>> h0 = flow.tensor(np.random.randn(2, 3, 20), dtype=flow.float32)
>>> c0 = flow.tensor(np.random.randn(2, 3, 20), dtype=flow.float32)
>>> output, (hn, cn) = rnn(input, (h0, c0))
>>> output.size()
oneflow.Size([5, 3, 20])
"""
def __init__(
self,
input_size: int,
hidden_size: int,
num_layers: int = 1,
bias: bool = True,
batch_first: bool = False,
dropout: float = 0,
bidirectional: bool = False,
proj_size: int = 0,
):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.bias = bias
self.batch_first = batch_first
self.dropout = dropout
self.bidirectional = bidirectional
num_directions = 2 if bidirectional else 1
gate_size = 4 * hidden_size
self.proj_size = proj_size
self.drop = nn.Dropout(self.dropout)
if proj_size < 0:
raise ValueError(
"proj_size should be a positive integer or zero to disable projections"
)
if proj_size >= hidden_size:
raise ValueError("proj_size has to be smaller than hidden_size")
for layer in range(num_layers):
for direction in range(num_directions):
real_hidden_size = proj_size if proj_size > 0 else hidden_size
layer_input_size = (
input_size if layer == 0 else real_hidden_size * num_directions
)
# TODO:Modify after adding the stride attribute
# w_ih = flow.nn.Parameter(flow.Tensor(gate_size, layer_input_size))
# w_hh = flow.nn.Parameter(flow.Tensor(gate_size, real_hidden_size))
# b_ih = flow.nn.Parameter(flow.Tensor(gate_size))
# b_hh = flow.nn.Parameter(flow.Tensor(gate_size))
w_ih = flow.nn.Parameter(flow.Tensor(layer_input_size, gate_size))
w_hh = flow.nn.Parameter(flow.Tensor(real_hidden_size, gate_size))
b_ih = flow.nn.Parameter(flow.Tensor(gate_size))
b_hh = flow.nn.Parameter(flow.Tensor(gate_size))
layer_params = ()
if self.proj_size == 0:
if bias:
layer_params = (w_ih, w_hh, b_ih, b_hh)
else:
layer_params = (w_ih, w_hh)
else:
# TODO: Modify after adding the stride attribute
# w_hr = flow.nn.Parameter(flow.Tensor(proj_size, hidden_size))
w_hr = flow.nn.Parameter(flow.Tensor(hidden_size, proj_size))
if bias:
layer_params = (w_ih, w_hh, b_ih, b_hh, w_hr)
else:
layer_params = (w_ih, w_hh, w_hr)
suffix = "_reverse" if direction == 1 else ""
param_names = ["weight_ih_l{}{}", "weight_hh_l{}{}"]
if bias:
param_names += ["bias_ih_l{}{}", "bias_hh_l{}{}"]
if self.proj_size > 0:
param_names += ["weight_hr_l{}{}"]
param_names = [x.format(layer, suffix) for x in param_names]
for name, param in zip(param_names, layer_params):
setattr(self, name, param)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / sqrt(self.hidden_size)
for weight in self.parameters():
weight.uniform_(-stdv, stdv)
def permute_tensor(self, input):
return input.permute(1, 0, 2)
def forward(self, input, h_0=None):
if self.batch_first == False:
input = self.permute_tensor(input)
D = 2 if self.bidirectional else 1
num_layers = self.num_layers
batch_size, seq_len, _ = input.size()
if h_0 is None:
real_hidden_size = (
self.proj_size if self.proj_size > 0 else self.hidden_size
)
h_t = flow.zeros(
(D * num_layers, batch_size, real_hidden_size),
dtype=input.dtype,
device=input.device,
)
c_t = flow.zeros(
(D * num_layers, batch_size, self.hidden_size),
dtype=input.dtype,
device=input.device,
)
h_0 = (h_t, c_t)
else:
h_t, c_t = h_0
if self.bidirectional:
if h_0 is None:
h_t_f = h_t[:num_layers, :, :]
h_t_b = h_t[num_layers:, :, :]
c_t_f = c_t[:num_layers, :, :]
c_t_b = c_t[num_layers:, :, :]
else:
h_t_f = flow.cat(
[
h_t[l, :, :].unsqueeze(0)
for l in range(h_t.size(0))
if l % 2 == 0
],
dim=0,
)
h_t_b = flow.cat(
[
h_t[l, :, :].unsqueeze(0)
for l in range(h_t.size(0))
if l % 2 != 0
],
dim=0,
)
c_t_f = flow.cat(
[
c_t[l, :, :].unsqueeze(0)
for l in range(c_t.size(0))
if l % 2 == 0
],
dim=0,
)
c_t_b = flow.cat(
[
c_t[l, :, :].unsqueeze(0)
for l in range(c_t.size(0))
if l % 2 != 0
],
dim=0,
)
else:
h_t_f = h_t
c_t_f = c_t
layer_hidden = []
layer_cell = []
for layer in range(self.num_layers):
hidden_seq_f = []
if self.bidirectional:
hidden_seq_b = []
hid_t_f = h_t_f[layer, :, :]
h_c_t_f = c_t_f[layer, :, :]
if self.bidirectional:
hid_t_b = h_t_b[layer, :, :]
h_c_t_b = c_t_b[layer, :, :]
for t in range(seq_len):
if layer == 0:
x_t_f = input[:, t, :]
if self.bidirectional:
x_t_b = input[:, seq_len - 1 - t, :]
else:
x_t_f = hidden_seq[:, t, :]
if self.bidirectional:
x_t_b = hidden_seq[:, seq_len - 1 - t, :]
# TODO: Modify after adding the stride attribute
# gi_f = flow.matmul(
# x_t_f,
# getattr(self, "weight_ih_l{}{}".format(layer, "")).permute(1, 0),
# )
# gh_f = flow.matmul(
# hid_t_f,
# getattr(self, "weight_hh_l{}{}".format(layer, "")).permute(1, 0),
# )
gi_f = flow.matmul(
x_t_f, getattr(self, "weight_ih_l{}{}".format(layer, "")),
)
gh_f = flow.matmul(
hid_t_f, getattr(self, "weight_hh_l{}{}".format(layer, "")),
)
if self.bias:
gi_f += getattr(self, "bias_ih_l{}{}".format(layer, ""))
gh_f += getattr(self, "bias_hh_l{}{}".format(layer, ""))
gates_f = gi_f + gh_f
ingate_f, forgetgate_f, cellgate_f, outgate_f = gates_f.chunk(4, dim=1)
ingate_f = flow.sigmoid(ingate_f)
forgetgate_f = flow.sigmoid(forgetgate_f)
cellgate_f = flow.tanh(cellgate_f)
outgate_f = flow.sigmoid(outgate_f)
h_c_t_f = (forgetgate_f * h_c_t_f) + (ingate_f * cellgate_f)
hid_t_f = outgate_f * flow.tanh(h_c_t_f)
if self.proj_size > 0:
# TODO:Modify after adding the stride attribute
# hid_t_f = flow.matmul(
# hid_t_f,
# getattr(self, "weight_hr_l{}{}".format(layer, "")).permute(
# 1, 0
# ),
# )
hid_t_f = flow.matmul(
hid_t_f, getattr(self, "weight_hr_l{}{}".format(layer, ""))
)
hidden_seq_f.append(hid_t_f.unsqueeze(1))
if self.bidirectional:
# TODO:Modify after adding the stride attribute
# gi_b = flow.matmul(
# x_t_b,
# getattr(
# self, "weight_ih_l{}{}".format(layer, "_reverse")
# ).permute(1, 0),
# )
# gh_b = flow.matmul(
# hid_t_b,
# getattr(
# self, "weight_hh_l{}{}".format(layer, "_reverse")
# ).permute(1, 0),
# )
gi_b = flow.matmul(
x_t_b,
getattr(self, "weight_ih_l{}{}".format(layer, "_reverse")),
)
gh_b = flow.matmul(
hid_t_b,
getattr(self, "weight_hh_l{}{}".format(layer, "_reverse")),
)
if self.bias:
gi_b += getattr(self, "bias_ih_l{}{}".format(layer, "_reverse"))
gh_b += getattr(self, "bias_hh_l{}{}".format(layer, "_reverse"))
gates_b = gi_b + gh_b
ingate_b, forgetgate_b, cellgate_b, outgate_b = gates_b.chunk(
4, dim=1
)
ingate_b = flow.sigmoid(ingate_b)
forgetgate_b = flow.sigmoid(forgetgate_b)
cellgate_b = flow.tanh(cellgate_b)
outgate_b = flow.sigmoid(outgate_b)
h_c_t_b = (forgetgate_b * h_c_t_b) + (ingate_b * cellgate_b)
hid_t_b = outgate_b * flow.tanh(h_c_t_b)
if self.proj_size > 0:
# TODO:Modify after adding the stride attribute
# hid_t_b = flow.matmul(
# hid_t_b,
# getattr(
# self, "weight_hr_l{}{}".format(layer, "_reverse")
# ).permute(1, 0),
# )
hid_t_b = flow.matmul(
hid_t_b,
getattr(self, "weight_hr_l{}{}".format(layer, "_reverse")),
)
hidden_seq_b.insert(0, hid_t_b.unsqueeze(1))
hidden_seq_f = flow.cat(hidden_seq_f, dim=1)
if self.bidirectional:
hidden_seq_b = flow.cat(hidden_seq_b, dim=1)
if self.dropout != 0 and layer != self.num_layers - 1:
hidden_seq_f = self.drop(hidden_seq_f)
if self.bidirectional:
hidden_seq_b = self.drop(hidden_seq_b)
if self.bidirectional:
hidden_seq = flow.cat([hidden_seq_f, hidden_seq_b], dim=2)
else:
hidden_seq = hidden_seq_f
if self.bidirectional:
h_t = flow.cat([hid_t_f.unsqueeze(0), hid_t_b.unsqueeze(0)], dim=0)
c_t = flow.cat([h_c_t_f.unsqueeze(0), h_c_t_b.unsqueeze(0)], dim=0)
else:
h_t = hid_t_f.unsqueeze(0)
c_t = h_c_t_f.unsqueeze(0)
layer_hidden.append(h_t)
layer_cell.append(c_t)
h_t = flow.cat(layer_hidden, dim=0)
c_t = flow.cat(layer_cell, dim=0)
if self.batch_first == False:
hidden_seq = self.permute_tensor(hidden_seq)
return hidden_seq, (h_t, c_t)
if __name__ == "__main__":
import doctest
doctest.testmod(raise_on_error=True)
| [
"oneflow.nn.ReLU",
"oneflow.tanh",
"oneflow.nn.Tanh",
"oneflow.nn.Dropout",
"oneflow.sigmoid",
"oneflow.zeros",
"oneflow.Tensor",
"oneflow.cat"
] | [((46403, 46439), 'doctest.testmod', 'doctest.testmod', ([], {'raise_on_error': '(True)'}), '(raise_on_error=True)\n', (46418, 46439), False, 'import doctest\n'), ((6098, 6122), 'oneflow.nn.Dropout', 'nn.Dropout', (['self.dropout'], {}), '(self.dropout)\n', (6108, 6122), False, 'from oneflow import nn\n'), ((13311, 13340), 'oneflow.cat', 'flow.cat', (['layer_hidden'], {'dim': '(0)'}), '(layer_hidden, dim=0)\n', (13319, 13340), True, 'import oneflow as flow\n'), ((19483, 19507), 'oneflow.nn.Dropout', 'nn.Dropout', (['self.dropout'], {}), '(self.dropout)\n', (19493, 19507), False, 'from oneflow import nn\n'), ((27003, 27032), 'oneflow.cat', 'flow.cat', (['layer_hidden'], {'dim': '(0)'}), '(layer_hidden, dim=0)\n', (27011, 27032), True, 'import oneflow as flow\n'), ((35119, 35143), 'oneflow.nn.Dropout', 'nn.Dropout', (['self.dropout'], {}), '(self.dropout)\n', (35129, 35143), False, 'from oneflow import nn\n'), ((46143, 46172), 'oneflow.cat', 'flow.cat', (['layer_hidden'], {'dim': '(0)'}), '(layer_hidden, dim=0)\n', (46151, 46172), True, 'import oneflow as flow\n'), ((46187, 46214), 'oneflow.cat', 'flow.cat', (['layer_cell'], {'dim': '(0)'}), '(layer_cell, dim=0)\n', (46195, 46214), True, 'import oneflow as flow\n'), ((6187, 6196), 'oneflow.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (6194, 6196), False, 'from oneflow import nn\n'), ((8014, 8036), 'math.sqrt', 'sqrt', (['self.hidden_size'], {}), '(self.hidden_size)\n', (8018, 8036), False, 'from math import sqrt\n'), ((8491, 8594), 'oneflow.zeros', 'flow.zeros', (['(D * num_layers, batch_size, self.hidden_size)'], {'dtype': 'input.dtype', 'device': 'input.device'}), '((D * num_layers, batch_size, self.hidden_size), dtype=input.\n dtype, device=input.device)\n', (8501, 8594), True, 'import oneflow as flow\n'), ((12559, 12588), 'oneflow.cat', 'flow.cat', (['hidden_seq_f'], {'dim': '(1)'}), '(hidden_seq_f, dim=1)\n', (12567, 12588), True, 'import oneflow as flow\n'), ((21152, 21174), 'math.sqrt', 'sqrt', (['self.hidden_size'], {}), '(self.hidden_size)\n', (21156, 21174), False, 'from math import sqrt\n'), ((21628, 21731), 'oneflow.zeros', 'flow.zeros', (['(D * num_layers, batch_size, self.hidden_size)'], {'dtype': 'input.dtype', 'device': 'input.device'}), '((D * num_layers, batch_size, self.hidden_size), dtype=input.\n dtype, device=input.device)\n', (21638, 21731), True, 'import oneflow as flow\n'), ((26251, 26280), 'oneflow.cat', 'flow.cat', (['hidden_seq_f'], {'dim': '(1)'}), '(hidden_seq_f, dim=1)\n', (26259, 26280), True, 'import oneflow as flow\n'), ((37685, 37707), 'math.sqrt', 'sqrt', (['self.hidden_size'], {}), '(self.hidden_size)\n', (37689, 37707), False, 'from math import sqrt\n'), ((38283, 38386), 'oneflow.zeros', 'flow.zeros', (['(D * num_layers, batch_size, real_hidden_size)'], {'dtype': 'input.dtype', 'device': 'input.device'}), '((D * num_layers, batch_size, real_hidden_size), dtype=input.\n dtype, device=input.device)\n', (38293, 38386), True, 'import oneflow as flow\n'), ((38463, 38566), 'oneflow.zeros', 'flow.zeros', (['(D * num_layers, batch_size, self.hidden_size)'], {'dtype': 'input.dtype', 'device': 'input.device'}), '((D * num_layers, batch_size, self.hidden_size), dtype=input.\n dtype, device=input.device)\n', (38473, 38566), True, 'import oneflow as flow\n'), ((45229, 45258), 'oneflow.cat', 'flow.cat', (['hidden_seq_f'], {'dim': '(1)'}), '(hidden_seq_f, dim=1)\n', (45237, 45258), True, 'import oneflow as flow\n'), ((6262, 6271), 'oneflow.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (6269, 6271), False, 'from oneflow import nn\n'), ((12655, 12684), 'oneflow.cat', 'flow.cat', (['hidden_seq_b'], {'dim': '(1)'}), '(hidden_seq_b, dim=1)\n', (12663, 12684), True, 'import oneflow as flow\n'), ((12971, 13016), 'oneflow.cat', 'flow.cat', (['[hidden_seq_f, hidden_seq_b]'], {'dim': '(2)'}), '([hidden_seq_f, hidden_seq_b], dim=2)\n', (12979, 13016), True, 'import oneflow as flow\n'), ((24274, 24301), 'oneflow.sigmoid', 'flow.sigmoid', (['(i_r_f + h_r_f)'], {}), '(i_r_f + h_r_f)\n', (24286, 24301), True, 'import oneflow as flow\n'), ((24332, 24359), 'oneflow.sigmoid', 'flow.sigmoid', (['(i_i_f + h_i_f)'], {}), '(i_i_f + h_i_f)\n', (24344, 24359), True, 'import oneflow as flow\n'), ((24388, 24426), 'oneflow.tanh', 'flow.tanh', (['(i_n_f + resetgate_f * h_n_f)'], {}), '(i_n_f + resetgate_f * h_n_f)\n', (24397, 24426), True, 'import oneflow as flow\n'), ((26347, 26376), 'oneflow.cat', 'flow.cat', (['hidden_seq_b'], {'dim': '(1)'}), '(hidden_seq_b, dim=1)\n', (26355, 26376), True, 'import oneflow as flow\n'), ((26663, 26708), 'oneflow.cat', 'flow.cat', (['[hidden_seq_f, hidden_seq_b]'], {'dim': '(2)'}), '([hidden_seq_f, hidden_seq_b], dim=2)\n', (26671, 26708), True, 'import oneflow as flow\n'), ((41903, 41925), 'oneflow.sigmoid', 'flow.sigmoid', (['ingate_f'], {}), '(ingate_f)\n', (41915, 41925), True, 'import oneflow as flow\n'), ((41957, 41983), 'oneflow.sigmoid', 'flow.sigmoid', (['forgetgate_f'], {}), '(forgetgate_f)\n', (41969, 41983), True, 'import oneflow as flow\n'), ((42013, 42034), 'oneflow.tanh', 'flow.tanh', (['cellgate_f'], {}), '(cellgate_f)\n', (42022, 42034), True, 'import oneflow as flow\n'), ((42063, 42086), 'oneflow.sigmoid', 'flow.sigmoid', (['outgate_f'], {}), '(outgate_f)\n', (42075, 42086), True, 'import oneflow as flow\n'), ((45325, 45354), 'oneflow.cat', 'flow.cat', (['hidden_seq_b'], {'dim': '(1)'}), '(hidden_seq_b, dim=1)\n', (45333, 45354), True, 'import oneflow as flow\n'), ((45641, 45686), 'oneflow.cat', 'flow.cat', (['[hidden_seq_f, hidden_seq_b]'], {'dim': '(2)'}), '([hidden_seq_f, hidden_seq_b], dim=2)\n', (45649, 45686), True, 'import oneflow as flow\n'), ((7062, 7102), 'oneflow.Tensor', 'flow.Tensor', (['layer_input_size', 'gate_size'], {}), '(layer_input_size, gate_size)\n', (7073, 7102), True, 'import oneflow as flow\n'), ((7145, 7185), 'oneflow.Tensor', 'flow.Tensor', (['real_hidden_size', 'gate_size'], {}), '(real_hidden_size, gate_size)\n', (7156, 7185), True, 'import oneflow as flow\n'), ((7228, 7250), 'oneflow.Tensor', 'flow.Tensor', (['gate_size'], {}), '(gate_size)\n', (7239, 7250), True, 'import oneflow as flow\n'), ((7293, 7315), 'oneflow.Tensor', 'flow.Tensor', (['gate_size'], {}), '(gate_size)\n', (7304, 7315), True, 'import oneflow as flow\n'), ((20200, 20240), 'oneflow.Tensor', 'flow.Tensor', (['layer_input_size', 'gate_size'], {}), '(layer_input_size, gate_size)\n', (20211, 20240), True, 'import oneflow as flow\n'), ((20283, 20323), 'oneflow.Tensor', 'flow.Tensor', (['real_hidden_size', 'gate_size'], {}), '(real_hidden_size, gate_size)\n', (20294, 20323), True, 'import oneflow as flow\n'), ((20366, 20388), 'oneflow.Tensor', 'flow.Tensor', (['gate_size'], {}), '(gate_size)\n', (20377, 20388), True, 'import oneflow as flow\n'), ((20431, 20453), 'oneflow.Tensor', 'flow.Tensor', (['gate_size'], {}), '(gate_size)\n', (20442, 20453), True, 'import oneflow as flow\n'), ((25917, 25944), 'oneflow.sigmoid', 'flow.sigmoid', (['(i_r_b + h_r_b)'], {}), '(i_r_b + h_r_b)\n', (25929, 25944), True, 'import oneflow as flow\n'), ((25979, 26006), 'oneflow.sigmoid', 'flow.sigmoid', (['(i_i_b + h_i_b)'], {}), '(i_i_b + h_i_b)\n', (25991, 26006), True, 'import oneflow as flow\n'), ((26039, 26077), 'oneflow.tanh', 'flow.tanh', (['(i_n_b + resetgate_b * h_n_b)'], {}), '(i_n_b + resetgate_b * h_n_b)\n', (26048, 26077), True, 'import oneflow as flow\n'), ((36140, 36180), 'oneflow.Tensor', 'flow.Tensor', (['layer_input_size', 'gate_size'], {}), '(layer_input_size, gate_size)\n', (36151, 36180), True, 'import oneflow as flow\n'), ((36223, 36263), 'oneflow.Tensor', 'flow.Tensor', (['real_hidden_size', 'gate_size'], {}), '(real_hidden_size, gate_size)\n', (36234, 36263), True, 'import oneflow as flow\n'), ((36306, 36328), 'oneflow.Tensor', 'flow.Tensor', (['gate_size'], {}), '(gate_size)\n', (36317, 36328), True, 'import oneflow as flow\n'), ((36371, 36393), 'oneflow.Tensor', 'flow.Tensor', (['gate_size'], {}), '(gate_size)\n', (36382, 36393), True, 'import oneflow as flow\n'), ((42202, 42220), 'oneflow.tanh', 'flow.tanh', (['h_c_t_f'], {}), '(h_c_t_f)\n', (42211, 42220), True, 'import oneflow as flow\n'), ((44197, 44219), 'oneflow.sigmoid', 'flow.sigmoid', (['ingate_b'], {}), '(ingate_b)\n', (44209, 44219), True, 'import oneflow as flow\n'), ((44255, 44281), 'oneflow.sigmoid', 'flow.sigmoid', (['forgetgate_b'], {}), '(forgetgate_b)\n', (44267, 44281), True, 'import oneflow as flow\n'), ((44315, 44336), 'oneflow.tanh', 'flow.tanh', (['cellgate_b'], {}), '(cellgate_b)\n', (44324, 44336), True, 'import oneflow as flow\n'), ((44369, 44392), 'oneflow.sigmoid', 'flow.sigmoid', (['outgate_b'], {}), '(outgate_b)\n', (44381, 44392), True, 'import oneflow as flow\n'), ((36864, 36899), 'oneflow.Tensor', 'flow.Tensor', (['hidden_size', 'proj_size'], {}), '(hidden_size, proj_size)\n', (36875, 36899), True, 'import oneflow as flow\n'), ((44516, 44534), 'oneflow.tanh', 'flow.tanh', (['h_c_t_b'], {}), '(h_c_t_b)\n', (44525, 44534), True, 'import oneflow as flow\n')] |
import cv2
import numpy as np
import os
import sys
import time
from PIL import Image
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtPrintSupport import QPrintDialog, QPrinter
import oneflow as flow
import oneflow.typing as tp
from data.base_dataset import load_label2ndarray
import models.networks as networks
from options.test_options import TestOptions
import util.util as util
from ui.ui import Ui_Form
from ui.mouse_event import GraphicsScene
from ui_util.config import Config
color_list = [QColor(0, 0, 0), QColor(204, 0, 0), QColor(76, 153, 0), QColor(204, 204, 0), QColor(51, 51, 255), QColor(204, 0, 204), QColor(0, 255, 255), QColor(51, 255, 255), QColor(102, 51, 0), QColor(255, 0, 0), QColor(102, 204, 0), QColor(255, 255, 0), QColor(0, 0, 153), QColor(0, 0, 204), QColor(255, 51, 153), QColor(0, 204, 204), QColor(0, 51, 0), QColor(255, 153, 51), QColor(0, 204, 0)]
os.environ["CUDA_VISIBLE_DEVICES"] = str(0)
opt = TestOptions().parse()
opt.batchSize = 1
opt.gpu_nums = 1
opt.label_nc = 19
flow.config.gpu_device_num(opt.gpu_nums)
flow.env.init()
func_config = flow.FunctionConfig()
func_config.default_data_type(flow.float)
func_config.default_logical_view(flow.scope.consistent_view())
func_config.default_placement_scope(flow.scope.placement("gpu", "0:0"))
@flow.global_function("predict", func_config)
def TrainGenerators(
label: tp.Numpy.Placeholder((opt.batchSize, opt.label_nc, opt.loadSize, opt.loadSize), dtype = flow.float32),):
fake_image = networks.define_G(label, opt.output_nc, opt.ngf, opt.netG,
n_downsample_global=opt.n_downsample_global, n_blocks_global=opt.n_blocks_global,
n_blocks_local=opt.n_blocks_local, norm_type=opt.norm, trainable=False, reuse=True)
return fake_image
assert opt.load_pretrain != ""
flow.load_variables(flow.checkpoint.get(opt.load_pretrain))
class Ex(QWidget, Ui_Form):
def __init__(self, opt):
super(Ex, self).__init__()
self.setupUi(self)
self.show()
self.opt = opt
self.output_img = None
self.mat_img = None
self.mode = 0
self.size = 6
self.mask = None
self.mask_m = None
self.img = None
self.mouse_clicked = False
self.scene = GraphicsScene(self.mode, self.size)
self.graphicsView.setScene(self.scene)
self.graphicsView.setAlignment(Qt.AlignTop | Qt.AlignLeft)
self.graphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.graphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.result_scene = QGraphicsScene()
self.graphicsView_3.setScene(self.result_scene)
self.graphicsView_3.setAlignment(Qt.AlignTop | Qt.AlignLeft)
self.graphicsView_3.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.graphicsView_3.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.dlg = QColorDialog(self.graphicsView)
self.color = None
def open_mask(self):
fileName, _ = QFileDialog.getOpenFileName(self, "Open File",
QDir.currentPath())
if fileName:
mat_img = cv2.imread(fileName)
self.mask = mat_img.copy()
self.mask_m = mat_img
mat_img = mat_img.copy()
image = QImage(mat_img, 512, 512, QImage.Format_RGB888)
if image.isNull():
QMessageBox.information(self, "Image Viewer",
"Cannot load %s." % fileName)
return
for i in range(512):
for j in range(512):
r, g, b, a = image.pixelColor(i, j).getRgb()
image.setPixel(i, j, color_list[r].rgb())
pixmap = QPixmap()
pixmap.convertFromImage(image)
self.image = pixmap.scaled(self.graphicsView.size(), Qt.IgnoreAspectRatio)
self.scene.reset()
if len(self.scene.items())>0:
self.scene.reset_items()
self.scene.addPixmap(self.image)
def bg_mode(self):
self.scene.mode = 0
def skin_mode(self):
self.scene.mode = 1
def nose_mode(self):
self.scene.mode = 2
def eye_g_mode(self):
self.scene.mode = 3
def l_eye_mode(self):
self.scene.mode = 4
def r_eye_mode(self):
self.scene.mode = 5
def l_brow_mode(self):
self.scene.mode = 6
def r_brow_mode(self):
self.scene.mode = 7
def l_ear_mode(self):
self.scene.mode = 8
def r_ear_mode(self):
self.scene.mode = 9
def mouth_mode(self):
self.scene.mode = 10
def u_lip_mode(self):
self.scene.mode = 11
def l_lip_mode(self):
self.scene.mode = 12
def hair_mode(self):
self.scene.mode = 13
def hat_mode(self):
self.scene.mode = 14
def ear_r_mode(self):
self.scene.mode = 15
def neck_l_mode(self):
self.scene.mode = 16
def neck_mode(self):
self.scene.mode = 17
def cloth_mode(self):
self.scene.mode = 18
def increase(self):
if self.scene.size < 15:
self.scene.size += 1
def decrease(self):
if self.scene.size > 1:
self.scene.size -= 1
def edit(self):
print("fake")
for i in range(19):
self.mask_m = self.make_mask(self.mask_m, self.scene.mask_points[i], self.scene.size_points[i], i)
mask_m = self.mask_m.copy()
mask_m = cv2.cvtColor(mask_m, cv2.COLOR_BGR2GRAY)
mask_m = load_label2ndarray(mask_m, self.opt, False)
start_t = time.time()
label_one_hot_encoding = np.zeros((opt.batchSize, opt.label_nc, opt.loadSize, opt.loadSize), dtype=np.float)
util.scatter(label_one_hot_encoding, 1, mask_m.astype(np.int32), 1)
label_nd = label_one_hot_encoding
generated = TrainGenerators(label_nd).get()
end_t = time.time()
print('inference time : {}'.format(end_t-start_t))
result = util.tensor2im(generated.numpy()[0])
result = cv2.cvtColor(result, cv2.COLOR_BGR2RGB)
qim = QImage(result.data, result.shape[1], result.shape[0], result.strides[0], QImage.Format_RGB888)
if len(self.result_scene.items()) == 0:
self.result_scene.addPixmap(QPixmap.fromImage(qim))
elif len(self.result_scene.items())>0:
self.result_scene.removeItem(self.result_scene.items()[-1])
self.result_scene.addPixmap(QPixmap.fromImage(qim))
def make_mask(self, mask, pts, sizes, color):
if len(pts)>0:
for idx, pt in enumerate(pts):
cv2.line(mask,pt['prev'],pt['curr'],(color,color,color),sizes[idx])
return mask
def save_img(self):
if type(self.output_img):
fileName, _ = QFileDialog.getSaveFileName(self, "Save File",
QDir.currentPath())
cv2.imwrite(fileName+'.jpg',self.output_img)
def undo(self):
self.scene.undo()
def clear(self):
self.mask_m = self.mask.copy()
self.scene.reset_items()
self.scene.reset()
if type(self.image):
self.scene.addPixmap(self.image)
app = QApplication(sys.argv)
ex = Ex(opt)
sys.exit(app.exec_())
| [
"oneflow.env.init",
"oneflow.FunctionConfig",
"oneflow.scope.consistent_view",
"oneflow.global_function",
"oneflow.scope.placement",
"oneflow.config.gpu_device_num",
"oneflow.typing.Numpy.Placeholder",
"oneflow.checkpoint.get"
] | [((1058, 1098), 'oneflow.config.gpu_device_num', 'flow.config.gpu_device_num', (['opt.gpu_nums'], {}), '(opt.gpu_nums)\n', (1084, 1098), True, 'import oneflow as flow\n'), ((1099, 1114), 'oneflow.env.init', 'flow.env.init', ([], {}), '()\n', (1112, 1114), True, 'import oneflow as flow\n'), ((1129, 1150), 'oneflow.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (1148, 1150), True, 'import oneflow as flow\n'), ((1330, 1374), 'oneflow.global_function', 'flow.global_function', (['"""predict"""', 'func_config'], {}), "('predict', func_config)\n", (1350, 1374), True, 'import oneflow as flow\n'), ((1226, 1254), 'oneflow.scope.consistent_view', 'flow.scope.consistent_view', ([], {}), '()\n', (1252, 1254), True, 'import oneflow as flow\n'), ((1292, 1326), 'oneflow.scope.placement', 'flow.scope.placement', (['"""gpu"""', '"""0:0"""'], {}), "('gpu', '0:0')\n", (1312, 1326), True, 'import oneflow as flow\n'), ((1529, 1766), 'models.networks.define_G', 'networks.define_G', (['label', 'opt.output_nc', 'opt.ngf', 'opt.netG'], {'n_downsample_global': 'opt.n_downsample_global', 'n_blocks_global': 'opt.n_blocks_global', 'n_blocks_local': 'opt.n_blocks_local', 'norm_type': 'opt.norm', 'trainable': '(False)', 'reuse': '(True)'}), '(label, opt.output_nc, opt.ngf, opt.netG,\n n_downsample_global=opt.n_downsample_global, n_blocks_global=opt.\n n_blocks_global, n_blocks_local=opt.n_blocks_local, norm_type=opt.norm,\n trainable=False, reuse=True)\n', (1546, 1766), True, 'import models.networks as networks\n'), ((1892, 1930), 'oneflow.checkpoint.get', 'flow.checkpoint.get', (['opt.load_pretrain'], {}), '(opt.load_pretrain)\n', (1911, 1930), True, 'import oneflow as flow\n'), ((982, 995), 'options.test_options.TestOptions', 'TestOptions', ([], {}), '()\n', (993, 995), False, 'from options.test_options import TestOptions\n'), ((1407, 1511), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(opt.batchSize, opt.label_nc, opt.loadSize, opt.loadSize)'], {'dtype': 'flow.float32'}), '((opt.batchSize, opt.label_nc, opt.loadSize, opt.\n loadSize), dtype=flow.float32)\n', (1427, 1511), True, 'import oneflow.typing as tp\n'), ((2334, 2369), 'ui.mouse_event.GraphicsScene', 'GraphicsScene', (['self.mode', 'self.size'], {}), '(self.mode, self.size)\n', (2347, 2369), False, 'from ui.mouse_event import GraphicsScene\n'), ((5612, 5652), 'cv2.cvtColor', 'cv2.cvtColor', (['mask_m', 'cv2.COLOR_BGR2GRAY'], {}), '(mask_m, cv2.COLOR_BGR2GRAY)\n', (5624, 5652), False, 'import cv2\n'), ((5670, 5713), 'data.base_dataset.load_label2ndarray', 'load_label2ndarray', (['mask_m', 'self.opt', '(False)'], {}), '(mask_m, self.opt, False)\n', (5688, 5713), False, 'from data.base_dataset import load_label2ndarray\n'), ((5733, 5744), 'time.time', 'time.time', ([], {}), '()\n', (5742, 5744), False, 'import time\n'), ((5787, 5875), 'numpy.zeros', 'np.zeros', (['(opt.batchSize, opt.label_nc, opt.loadSize, opt.loadSize)'], {'dtype': 'np.float'}), '((opt.batchSize, opt.label_nc, opt.loadSize, opt.loadSize), dtype=\n np.float)\n', (5795, 5875), True, 'import numpy as np\n'), ((6075, 6086), 'time.time', 'time.time', ([], {}), '()\n', (6084, 6086), False, 'import time\n'), ((6218, 6257), 'cv2.cvtColor', 'cv2.cvtColor', (['result', 'cv2.COLOR_BGR2RGB'], {}), '(result, cv2.COLOR_BGR2RGB)\n', (6230, 6257), False, 'import cv2\n'), ((3223, 3243), 'cv2.imread', 'cv2.imread', (['fileName'], {}), '(fileName)\n', (3233, 3243), False, 'import cv2\n'), ((7070, 7117), 'cv2.imwrite', 'cv2.imwrite', (["(fileName + '.jpg')", 'self.output_img'], {}), "(fileName + '.jpg', self.output_img)\n", (7081, 7117), False, 'import cv2\n'), ((6798, 6871), 'cv2.line', 'cv2.line', (['mask', "pt['prev']", "pt['curr']", '(color, color, color)', 'sizes[idx]'], {}), "(mask, pt['prev'], pt['curr'], (color, color, color), sizes[idx])\n", (6806, 6871), False, 'import cv2\n')] |
import os
import oneflow as flow
import oneflow.nn as nn
from oneflow.utils.data import DataLoader
from oneflow.utils.vision import transforms
from torchvision.datasets.folder import ImageFolder
from tqdm import tqdm
import numpy as np
class ImageNetDataLoader(DataLoader):
def __init__(self, data_dir, split='train', image_size=224, batch_size=16, num_workers=8):
if split == 'train':
transform = transforms.Compose([
transforms.Resize((image_size, image_size)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
else:
transform = transforms.Compose([
transforms.Resize(256, interpolation=2),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
self.dataset = ImageFolder(root=os.path.join(data_dir, split), transform=transform)
super(ImageNetDataLoader, self).__init__(
dataset=self.dataset,
batch_size=batch_size,
shuffle=True if split == 'train' else False,
num_workers=num_workers)
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.transpose(-1, -2)
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].contiguous().view(-1).float().sum(0)
res.append(correct_k / batch_size * 100.0)
return res
def eval_flow_acc(model, data_dir, pretrained_path=None, batch_size=32, img_size=224, num_workers=8):
if pretrained_path:
state_dict = flow.load(pretrained_path)
model.load_state_dict(state_dict)
print("Load pretrained weights from {}".format(pretrained_path))
model.cuda()
data_loader = ImageNetDataLoader(
data_dir = data_dir,
image_size = img_size,
batch_size = batch_size,
num_workers = num_workers,
split='val'
)
total_batch = len(data_loader)
print("Start Evaluation")
acc1s = []
acc5s = []
model.eval()
with flow.no_grad():
pbar = tqdm(enumerate(data_loader), total=total_batch)
for batch_idx, (data, target) in pbar:
pbar.set_description("Batch {:05d}/{:05d}".format(batch_idx, total_batch))
data = data.to("cuda")
target = target.to("cuda")
pred_logits = model(data)
acc1, acc5 = accuracy(pred_logits, target, topk=(1, 5))
acc1s.append(acc1.item())
acc5s.append(acc5.item())
pbar.set_postfix(acc1=acc1.item(), acc5=acc5.item())
print("Evaluation on dataset {:s}, Acc@1: {:.4f}, Acc@5: {:.4f}".format("ImageNet", np.mean(acc1s), np.mean(acc5s)))
| [
"oneflow.utils.vision.transforms.CenterCrop",
"oneflow.utils.vision.transforms.Resize",
"oneflow.utils.vision.transforms.ToTensor",
"oneflow.load",
"oneflow.no_grad",
"oneflow.utils.vision.transforms.RandomHorizontalFlip",
"oneflow.utils.vision.transforms.Normalize"
] | [((1926, 1952), 'oneflow.load', 'flow.load', (['pretrained_path'], {}), '(pretrained_path)\n', (1935, 1952), True, 'import oneflow as flow\n'), ((2409, 2423), 'oneflow.no_grad', 'flow.no_grad', ([], {}), '()\n', (2421, 2423), True, 'import oneflow as flow\n'), ((3044, 3058), 'numpy.mean', 'np.mean', (['acc1s'], {}), '(acc1s)\n', (3051, 3058), True, 'import numpy as np\n'), ((3060, 3074), 'numpy.mean', 'np.mean', (['acc5s'], {}), '(acc5s)\n', (3067, 3074), True, 'import numpy as np\n'), ((1040, 1069), 'os.path.join', 'os.path.join', (['data_dir', 'split'], {}), '(data_dir, split)\n', (1052, 1069), False, 'import os\n'), ((461, 504), 'oneflow.utils.vision.transforms.Resize', 'transforms.Resize', (['(image_size, image_size)'], {}), '((image_size, image_size))\n', (478, 504), False, 'from oneflow.utils.vision import transforms\n'), ((522, 555), 'oneflow.utils.vision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (553, 555), False, 'from oneflow.utils.vision import transforms\n'), ((573, 594), 'oneflow.utils.vision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (592, 594), False, 'from oneflow.utils.vision import transforms\n'), ((612, 678), 'oneflow.utils.vision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (632, 678), False, 'from oneflow.utils.vision import transforms\n'), ((769, 808), 'oneflow.utils.vision.transforms.Resize', 'transforms.Resize', (['(256)'], {'interpolation': '(2)'}), '(256, interpolation=2)\n', (786, 808), False, 'from oneflow.utils.vision import transforms\n'), ((826, 852), 'oneflow.utils.vision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (847, 852), False, 'from oneflow.utils.vision import transforms\n'), ((870, 891), 'oneflow.utils.vision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (889, 891), False, 'from oneflow.utils.vision import transforms\n'), ((909, 975), 'oneflow.utils.vision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (929, 975), False, 'from oneflow.utils.vision import transforms\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 as flow
import oneflow.unittest
from test_util import GenArgList
import torch as torch_original
from oneflow.test_utils.automated_test_util import *
input_arr = np.array(
[
[-0.16046895, -1.03667831],
[-0.34974465, 0.26505867],
[-1.24111986, -0.53806001],
[1.72426331, 0.43572459],
],
dtype=np.float64,
)
def _test_weightnorm(test_case, device, dim):
model_flow = flow.nn.Linear(2, 4)
model_flow = model_flow.to(device)
with flow.no_grad():
for i in range(input_arr.shape[0]):
for j in range(input_arr.shape[1]):
model_flow.weight[i, j] = input_arr[i][j]
m_flow = flow.nn.utils.weight_norm(model_flow, name="weight", dim=dim)
model_torch = torch_original.nn.Linear(2, 4)
model_torch = model_torch.to(device)
with torch_original.no_grad():
for i in range(input_arr.shape[0]):
for j in range(input_arr.shape[1]):
model_torch.weight[i, j] = input_arr[i][j]
m_torch = torch_original.nn.utils.weight_norm(model_torch, name="weight", dim=dim)
if device == "cpu":
test_case.assertTrue(
np.allclose(
m_flow.weight_g.detach().numpy(),
m_torch.weight_g.detach().numpy(),
1e-05,
1e-05,
)
)
test_case.assertTrue(
np.allclose(
m_flow.weight_v.detach().numpy(),
m_torch.weight_v.detach().numpy(),
1e-05,
1e-05,
)
)
elif device == "gpu":
test_case.assertTrue(
np.allclose(
m_flow.weight_g.detach().cpu().numpy(),
m_torch.weight_g.detach().cpu().numpy(),
1e-05,
1e-05,
)
)
test_case.assertTrue(
np.allclose(
m_flow.weight_v.detach().numpy(),
m_torch.weight_v.detach().numpy(),
1e-05,
1e-05,
)
)
def _test_weightnorm_backward(test_case, device, dim):
linear = flow.nn.Linear(3, 8)
x = flow.tensor(
[
[-0.94630778, -0.83378579, -0.87060891],
[2.0289922, -0.28708987, -2.18369248],
[0.35217619, -0.67095644, -1.58943879],
[0.08086036, -1.81075924, 1.20752494],
[0.8901075, -0.49976737, -1.07153746],
[-0.44872912, -1.07275683, 0.06256855],
[-0.22556897, 0.74798368, 0.90416439],
[0.48339456, -2.32742195, -0.59321527],
],
dtype=flow.float32,
requires_grad=True,
)
flow.nn.init.constant_(linear.weight, 2.068758)
flow.nn.init.constant_(linear.bias, 0.23)
linear_wn = flow.nn.utils.weight_norm(linear, name="weight", dim=dim)
of_out = linear_wn(x)
of_out = of_out.sum()
of_out.backward()
np_grad = np.array(
[
[16.5501, 16.5501, 16.5501],
[16.5501, 16.5501, 16.5501],
[16.5501, 16.5501, 16.5501],
[16.5501, 16.5501, 16.5501],
[16.5501, 16.5501, 16.5501],
[16.5501, 16.5501, 16.5501],
[16.5501, 16.5501, 16.5501],
[16.5501, 16.5501, 16.5501],
]
)
test_case.assertTrue(np.allclose(np_grad, x.grad.numpy(), 0.0001, 0.0001))
@flow.unittest.skip_unless_1n1d()
class TestWeightNorm(flow.unittest.TestCase):
def test_weightnorm(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [
_test_weightnorm,
_test_weightnorm_backward,
]
arg_dict["device"] = ["cpu", "cuda"]
arg_dict["dim"] = [None, -2, -1, 0, 1]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
@autotest(n=10, auto_backward=True, check_graph=False)
def test_weight_norm_with_random_data(test_case):
device = random_device()
dim = random(-2, 2).to(int).value()
output = random(2, 6).to(int)
input = random(2, 6).to(int)
model_torch = torch.nn.Linear(output, input)
model_torch = model_torch.to(device)
m = torch.nn.utils.weight_norm(model_torch, name="weight", dim=dim)
return m.weight_g, m.weight_v
if __name__ == "__main__":
unittest.main()
| [
"oneflow.nn.init.constant_",
"oneflow.nn.Linear",
"oneflow.no_grad",
"oneflow.unittest.skip_unless_1n1d",
"oneflow.tensor",
"oneflow.nn.utils.weight_norm"
] | [((842, 984), 'numpy.array', 'np.array', (['[[-0.16046895, -1.03667831], [-0.34974465, 0.26505867], [-1.24111986, -\n 0.53806001], [1.72426331, 0.43572459]]'], {'dtype': 'np.float64'}), '([[-0.16046895, -1.03667831], [-0.34974465, 0.26505867], [-\n 1.24111986, -0.53806001], [1.72426331, 0.43572459]], dtype=np.float64)\n', (850, 984), True, 'import numpy as np\n'), ((4053, 4085), 'oneflow.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (4083, 4085), True, 'import oneflow as flow\n'), ((1095, 1115), 'oneflow.nn.Linear', 'flow.nn.Linear', (['(2)', '(4)'], {}), '(2, 4)\n', (1109, 1115), True, 'import oneflow as flow\n'), ((1343, 1404), 'oneflow.nn.utils.weight_norm', 'flow.nn.utils.weight_norm', (['model_flow'], {'name': '"""weight"""', 'dim': 'dim'}), "(model_flow, name='weight', dim=dim)\n", (1368, 1404), True, 'import oneflow as flow\n'), ((1424, 1454), 'torch.nn.Linear', 'torch_original.nn.Linear', (['(2)', '(4)'], {}), '(2, 4)\n', (1448, 1454), True, 'import torch as torch_original\n'), ((1696, 1768), 'torch.nn.utils.weight_norm', 'torch_original.nn.utils.weight_norm', (['model_torch'], {'name': '"""weight"""', 'dim': 'dim'}), "(model_torch, name='weight', dim=dim)\n", (1731, 1768), True, 'import torch as torch_original\n'), ((2806, 2826), 'oneflow.nn.Linear', 'flow.nn.Linear', (['(3)', '(8)'], {}), '(3, 8)\n', (2820, 2826), True, 'import oneflow as flow\n'), ((2835, 3230), 'oneflow.tensor', 'flow.tensor', (['[[-0.94630778, -0.83378579, -0.87060891], [2.0289922, -0.28708987, -\n 2.18369248], [0.35217619, -0.67095644, -1.58943879], [0.08086036, -\n 1.81075924, 1.20752494], [0.8901075, -0.49976737, -1.07153746], [-\n 0.44872912, -1.07275683, 0.06256855], [-0.22556897, 0.74798368, \n 0.90416439], [0.48339456, -2.32742195, -0.59321527]]'], {'dtype': 'flow.float32', 'requires_grad': '(True)'}), '([[-0.94630778, -0.83378579, -0.87060891], [2.0289922, -\n 0.28708987, -2.18369248], [0.35217619, -0.67095644, -1.58943879], [\n 0.08086036, -1.81075924, 1.20752494], [0.8901075, -0.49976737, -\n 1.07153746], [-0.44872912, -1.07275683, 0.06256855], [-0.22556897, \n 0.74798368, 0.90416439], [0.48339456, -2.32742195, -0.59321527]], dtype\n =flow.float32, requires_grad=True)\n', (2846, 3230), True, 'import oneflow as flow\n'), ((3348, 3395), 'oneflow.nn.init.constant_', 'flow.nn.init.constant_', (['linear.weight', '(2.068758)'], {}), '(linear.weight, 2.068758)\n', (3370, 3395), True, 'import oneflow as flow\n'), ((3400, 3441), 'oneflow.nn.init.constant_', 'flow.nn.init.constant_', (['linear.bias', '(0.23)'], {}), '(linear.bias, 0.23)\n', (3422, 3441), True, 'import oneflow as flow\n'), ((3459, 3516), 'oneflow.nn.utils.weight_norm', 'flow.nn.utils.weight_norm', (['linear'], {'name': '"""weight"""', 'dim': 'dim'}), "(linear, name='weight', dim=dim)\n", (3484, 3516), True, 'import oneflow as flow\n'), ((3607, 3864), 'numpy.array', 'np.array', (['[[16.5501, 16.5501, 16.5501], [16.5501, 16.5501, 16.5501], [16.5501, \n 16.5501, 16.5501], [16.5501, 16.5501, 16.5501], [16.5501, 16.5501, \n 16.5501], [16.5501, 16.5501, 16.5501], [16.5501, 16.5501, 16.5501], [\n 16.5501, 16.5501, 16.5501]]'], {}), '([[16.5501, 16.5501, 16.5501], [16.5501, 16.5501, 16.5501], [\n 16.5501, 16.5501, 16.5501], [16.5501, 16.5501, 16.5501], [16.5501, \n 16.5501, 16.5501], [16.5501, 16.5501, 16.5501], [16.5501, 16.5501, \n 16.5501], [16.5501, 16.5501, 16.5501]])\n', (3615, 3864), True, 'import numpy as np\n'), ((4999, 5014), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5012, 5014), False, 'import unittest\n'), ((1164, 1178), 'oneflow.no_grad', 'flow.no_grad', ([], {}), '()\n', (1176, 1178), True, 'import oneflow as flow\n'), ((1505, 1529), 'torch.no_grad', 'torch_original.no_grad', ([], {}), '()\n', (1527, 1529), True, 'import torch as torch_original\n'), ((4187, 4200), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4198, 4200), False, 'from collections import OrderedDict\n'), ((4424, 4444), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (4434, 4444), False, 'from test_util import GenArgList\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 os
import numpy as np
import time
import oneflow as flow
import oneflow.unittest
class TestBinaryFunctorError(flow.unittest.TestCase):
def test_add_inplace_runtime_error(test_case):
with test_case.assertRaises(RuntimeError) as context:
x = flow.ones((4, 4), dtype=flow.float32, requires_grad=True)
y = flow.ones((4, 4), dtype=flow.float32, requires_grad=True)
x.add_(y)
test_case.assertTrue(
"a leaf Tensor that requires grad is being used in an in-place operation"
in str(context.exception)
)
def test_add_broad_cast_runtime_error(test_case):
with test_case.assertRaises(RuntimeError) as context:
x = flow.ones((2, 3))
y = flow.ones((2, 4))
x.add_(y)
test_case.assertTrue(
"Can not expand shape (2,4) to (2,3)" in str(context.exception)
)
with test_case.assertRaises(RuntimeError) as context:
x = flow.ones((4, 4), dtype=flow.float32, requires_grad=True)
y = flow.ones((4, 4), dtype=flow.float32, requires_grad=True)
x.mul_(y)
test_case.assertTrue(
"a leaf Tensor that requires grad is being used in an in-place operation"
in str(context.exception)
)
with test_case.assertRaises(RuntimeError) as context:
x = flow.ones((2, 3))
y = flow.ones((2, 4))
x.mul_(y)
test_case.assertTrue(
"Can not expand shape (2,4) to (2,3)" in str(context.exception)
)
def test_div_inplace_runtime_error(test_case):
with test_case.assertRaises(RuntimeError) as context:
x = flow.ones((4, 4), dtype=flow.float32, requires_grad=True)
y = flow.ones((4, 4), dtype=flow.float32, requires_grad=True)
x.div_(y)
test_case.assertTrue(
"a leaf Tensor that requires grad is being used in an in-place operation"
in str(context.exception)
)
with test_case.assertRaises(RuntimeError) as context:
x = flow.ones((2, 3))
y = flow.ones((2, 4))
x.div_(y)
test_case.assertTrue(
"Can not expand shape (2,4) to (2,3)" in str(context.exception)
)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.ones"
] | [((2973, 2988), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2986, 2988), False, 'import unittest\n'), ((916, 973), 'oneflow.ones', 'flow.ones', (['(4, 4)'], {'dtype': 'flow.float32', 'requires_grad': '(True)'}), '((4, 4), dtype=flow.float32, requires_grad=True)\n', (925, 973), True, 'import oneflow as flow\n'), ((990, 1047), 'oneflow.ones', 'flow.ones', (['(4, 4)'], {'dtype': 'flow.float32', 'requires_grad': '(True)'}), '((4, 4), dtype=flow.float32, requires_grad=True)\n', (999, 1047), True, 'import oneflow as flow\n'), ((1367, 1384), 'oneflow.ones', 'flow.ones', (['(2, 3)'], {}), '((2, 3))\n', (1376, 1384), True, 'import oneflow as flow\n'), ((1401, 1418), 'oneflow.ones', 'flow.ones', (['(2, 4)'], {}), '((2, 4))\n', (1410, 1418), True, 'import oneflow as flow\n'), ((1636, 1693), 'oneflow.ones', 'flow.ones', (['(4, 4)'], {'dtype': 'flow.float32', 'requires_grad': '(True)'}), '((4, 4), dtype=flow.float32, requires_grad=True)\n', (1645, 1693), True, 'import oneflow as flow\n'), ((1710, 1767), 'oneflow.ones', 'flow.ones', (['(4, 4)'], {'dtype': 'flow.float32', 'requires_grad': '(True)'}), '((4, 4), dtype=flow.float32, requires_grad=True)\n', (1719, 1767), True, 'import oneflow as flow\n'), ((2033, 2050), 'oneflow.ones', 'flow.ones', (['(2, 3)'], {}), '((2, 3))\n', (2042, 2050), True, 'import oneflow as flow\n'), ((2067, 2084), 'oneflow.ones', 'flow.ones', (['(2, 4)'], {}), '((2, 4))\n', (2076, 2084), True, 'import oneflow as flow\n'), ((2353, 2410), 'oneflow.ones', 'flow.ones', (['(4, 4)'], {'dtype': 'flow.float32', 'requires_grad': '(True)'}), '((4, 4), dtype=flow.float32, requires_grad=True)\n', (2362, 2410), True, 'import oneflow as flow\n'), ((2427, 2484), 'oneflow.ones', 'flow.ones', (['(4, 4)'], {'dtype': 'flow.float32', 'requires_grad': '(True)'}), '((4, 4), dtype=flow.float32, requires_grad=True)\n', (2436, 2484), True, 'import oneflow as flow\n'), ((2750, 2767), 'oneflow.ones', 'flow.ones', (['(2, 3)'], {}), '((2, 3))\n', (2759, 2767), True, 'import oneflow as flow\n'), ((2784, 2801), 'oneflow.ones', 'flow.ones', (['(2, 4)'], {}), '((2, 4))\n', (2793, 2801), 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 unittest
import oneflow as flow
import oneflow.unittest
from oneflow.test_utils.automated_test_util import *
from oneflow.nn.common_types import _size_2_t
@flow.unittest.skip_unless_1n1d()
class TestUnfold(flow.unittest.TestCase):
@autotest(n=50, auto_backward=True, rtol=1e-4, atol=1e-4)
def test_unfold_with_random_data(test_case):
m = torch.nn.Unfold(
kernel_size=random(1, 3).to(_size_2_t),
dilation=random(1, 2).to(_size_2_t) | nothing(),
padding=random(0, 1).to(_size_2_t) | nothing(),
stride=random(1, 2).to(_size_2_t) | nothing(),
)
m.train(random())
device = random_device()
m.to(device)
x = random_pytorch_tensor(
ndim=4,
dim0=random(1, 5),
dim1=random(1, 5),
dim2=random(10, 20),
dim3=random(10, 20),
).to(device)
y = m(x)
return y
if __name__ == "__main__":
unittest.main()
| [
"oneflow.unittest.skip_unless_1n1d"
] | [((757, 789), 'oneflow.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (787, 789), True, 'import oneflow as flow\n'), ((1565, 1580), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1578, 1580), False, 'import unittest\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.arange,
"""
oneflow.arange(start: int = 0, end, step: int = 1, dtype: Optional[oneflow._oneflow_internal.dtype] = None, device: Optional[Union[oneflow._oneflow_internal.device, str]] = None, placement: Optional[oneflow._oneflow_internal.placement] = None, sbp: Optional[Union[oneflow._oneflow_internal.sbp.sbp, List[oneflow._oneflow_internal.sbp.sbp]]] = None, requires_grad: bool = False)
Returns a 1-D tensor of size :math:`\\left\\lfloor \\frac{\\text{end} - \\text{start}}{\\text{step}} \\right\\rfloor + 1`
with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is
the gap between two values in the tensor.
.. math::
\\text{out}_{i+1} = \\text{out}_i + \\text{step}.
Args:
start (int): the starting value for the set of points. Default: ``0``.
end (int): the ending value for the set of points
step (int): the gap between each pair of adjacent points. Default: ``1``.
Keyword args:
dtype(flow.dtype, optional): If `dtype` is not given, infer the `dtype` from the other input arguments. If any of start, end, or step are floating-point, the `dtype` is inferred to be the floating-point data type. Otherwise, the `dtype` is inferred to be `flow.int64`.
device(flow.device, optional): the desired device of returned tensor. Default: if None, uses the current device for the default tensor.
requires_grad(bool, optional): If autograd should record operations on the returned tensor. Default: `False`.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> y = flow.arange(0, 5)
>>> y
tensor([0, 1, 2, 3, 4], dtype=oneflow.int64)
""",
)
| [
"oneflow.framework.docstr.utils.add_docstr"
] | [((660, 2399), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.arange', '"""\n oneflow.arange(start: int = 0, end, step: int = 1, dtype: Optional[oneflow._oneflow_internal.dtype] = None, device: Optional[Union[oneflow._oneflow_internal.device, str]] = None, placement: Optional[oneflow._oneflow_internal.placement] = None, sbp: Optional[Union[oneflow._oneflow_internal.sbp.sbp, List[oneflow._oneflow_internal.sbp.sbp]]] = None, requires_grad: bool = False)\n\n Returns a 1-D tensor of size :math:`\\\\left\\\\lfloor \\\\frac{\\\\text{end} - \\\\text{start}}{\\\\text{step}} \\\\right\\\\rfloor + 1`\n with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is\n the gap between two values in the tensor.\n\n .. math::\n \\\\text{out}_{i+1} = \\\\text{out}_i + \\\\text{step}.\n\n Args:\n start (int): the starting value for the set of points. Default: ``0``.\n end (int): the ending value for the set of points\n step (int): the gap between each pair of adjacent points. Default: ``1``.\n\n Keyword args:\n dtype(flow.dtype, optional): If `dtype` is not given, infer the `dtype` from the other input arguments. If any of start, end, or step are floating-point, the `dtype` is inferred to be the floating-point data type. Otherwise, the `dtype` is inferred to be `flow.int64`.\n device(flow.device, optional): the desired device of returned tensor. Default: if None, uses the current device for the default tensor.\n requires_grad(bool, optional): If autograd should record operations on the returned tensor. Default: `False`.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n \n >>> y = flow.arange(0, 5)\n >>> y\n tensor([0, 1, 2, 3, 4], dtype=oneflow.int64)\n\n """'], {}), '(oneflow.arange,\n """\n oneflow.arange(start: int = 0, end, step: int = 1, dtype: Optional[oneflow._oneflow_internal.dtype] = None, device: Optional[Union[oneflow._oneflow_internal.device, str]] = None, placement: Optional[oneflow._oneflow_internal.placement] = None, sbp: Optional[Union[oneflow._oneflow_internal.sbp.sbp, List[oneflow._oneflow_internal.sbp.sbp]]] = None, requires_grad: bool = False)\n\n Returns a 1-D tensor of size :math:`\\\\left\\\\lfloor \\\\frac{\\\\text{end} - \\\\text{start}}{\\\\text{step}} \\\\right\\\\rfloor + 1`\n with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is\n the gap between two values in the tensor.\n\n .. math::\n \\\\text{out}_{i+1} = \\\\text{out}_i + \\\\text{step}.\n\n Args:\n start (int): the starting value for the set of points. Default: ``0``.\n end (int): the ending value for the set of points\n step (int): the gap between each pair of adjacent points. Default: ``1``.\n\n Keyword args:\n dtype(flow.dtype, optional): If `dtype` is not given, infer the `dtype` from the other input arguments. If any of start, end, or step are floating-point, the `dtype` is inferred to be the floating-point data type. Otherwise, the `dtype` is inferred to be `flow.int64`.\n device(flow.device, optional): the desired device of returned tensor. Default: if None, uses the current device for the default tensor.\n requires_grad(bool, optional): If autograd should record operations on the returned tensor. Default: `False`.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n \n >>> y = flow.arange(0, 5)\n >>> y\n tensor([0, 1, 2, 3, 4], dtype=oneflow.int64)\n\n """\n )\n', (670, 2399), False, 'from oneflow.framework.docstr.utils import add_docstr\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 import nn
from oneflow.nn import init
from libai.config import configurable
from libai.layers import (
Embedding,
LayerNorm,
LMLogits,
ParallelCrossEntropyLoss,
TransformerLayer,
VocabEmbedding,
)
from libai.utils import distributed as dist
from .utils import init_method_normal, scaled_init_method_normal
class CasualMask(nn.Module):
"""
Create a casual mask and combine it with the padding mask.
It will be used in gpt model and T5 decoder.
When in T5 decoder, the argument `layer_idx` should be set to first decoder layer index.
"""
def __init__(self, max_positions=1024, *, layer_idx=0):
super().__init__()
self.mask = flow.tril(
flow.ones(
(max_positions, max_positions),
dtype=flow.int8,
placement=dist.get_layer_placement(layer_idx),
sbp=dist.get_nd_sbp([flow.sbp.broadcast, flow.sbp.broadcast]),
)
)
def forward(self, input_ids, past_length=0, attention_mask=None):
bsz, tgt_len = input_ids.size()
casual_mask = self.mask[:tgt_len, :tgt_len]
if past_length > 0:
# in case past_key_values are used, we need to add a prefix ones mask to casual mask
casual_mask = flow.cat(
[flow.ones(tgt_len, past_length, dtype=flow.int8), casual_mask], dim=-1
)
casual_mask = (
casual_mask.unsqueeze(0).unsqueeze(1).expand(bsz, 1, tgt_len, tgt_len + past_length)
)
casual_mask = casual_mask.to_global(sbp=input_ids.sbp)
if attention_mask is not None:
assert attention_mask.dim() == 4, "please extend the attention mask first"
casual_mask = casual_mask * attention_mask
return casual_mask
class GPTModel(nn.Module):
"""GPT-2 language model. The output of the forward method is logits.
Args:
num_layers (int): The number of ``TransformerLayer`` in the gpt model.
vocab_size (int): The size of vocabulary file.
hidden_size (int): The size of hidden states.
ffn_hidden_size (int):
The size of intermediate layer in feed-forward network for each ``TransformerLayer``.
num_attention_heads (int):
The number of attention heads for each attention layer of ``TransformerLayer``.
max_seq_length (int, optional):
Max sequence length of input, defines the shape of Position Embeddings in GPTEmebedding.
Defaults to 1024.
embedding_dropout_prob (float, optional):
The dropout ratio for the output of GPTEmbedding Layer. Defaults to 0.0.
attention_dropout_prob (float, optional):
The dropout ratio for the output of each attention layer in ``TransformerLayer``.
Defaults to 0.0.
output_dropout_prob (float, optional):
The dropout ratio for the output for each TransformerLayer. Defaults to 0.0.
layernorm_epsilon (float, optional):
The epsilon of LayerNorm layer. Defaults to 1e-5.
initializer_range (float, optional):
Sigma of the normal distribution in the initialization method. Defaults to 0.02.
use_scaled_init_for_output_weights (bool, optional): Defaults to ``True``.
bias_gelu_fusion (bool, optional):
Whether or not to fuse the computing of bias and gelu. Defaults to ``False``.
bias_dropout_fusion (bool, optional):
Whether or not to fuse the computing of dropout and bias. Defaults to ``False``.
scale_mask_softmax_fusion (bool, optional):
Whether to fuse the computing of mask and softmax in attention layers.
Defaults to ``False``.
apply_query_key_layer_scaling (bool, optional):
Whether or not to use layer index related scaling in computing attention scores.
If ``True``, the scaling factor equals to sqrt(d) * (layer_index + 1).
Defaults to ``False``.
apply_residual_post_layernorm (bool, optional):
If set ``True``, use original BERT residual connection ordering otherwise use Megatron
BERT residual connection which is more stable when scaling model size introduced in
https://arxiv.org/pdf/1909.08053.pdf.
Default: ``False``.
amp_enabled (bool, optional):
Whether or not to set fp16 for embedding weight in T5 model. Defaults to ``False``.
"""
@configurable
def __init__(
self,
num_layers,
vocab_size,
hidden_size,
ffn_hidden_size,
num_attention_heads,
max_seq_length=1024,
embedding_dropout_prob=0.0,
attention_dropout_prob=0.0,
output_dropout_prob=0.0,
layernorm_epsilon=1e-5,
initializer_range=0.02,
use_scaled_init_for_output_weights=True,
bias_gelu_fusion=False,
bias_dropout_fusion=False,
scale_mask_softmax_fusion=False,
apply_query_key_layer_scaling=False,
apply_residual_post_layernorm=False,
amp_enabled=False,
):
super().__init__()
init_method = init_method_normal(sigma=initializer_range)
if use_scaled_init_for_output_weights:
output_layer_init_method = scaled_init_method_normal(initializer_range, num_layers)
else:
output_layer_init_method = init_method
self.embeddings = GPTEmbedding(
vocab_size,
hidden_size,
max_seq_length,
init_method=init_method,
embedding_dropout_prob=embedding_dropout_prob,
amp_enabled=amp_enabled,
)
self.casual_mask = CasualMask()
self.transformer = Transformer(
num_layers,
hidden_size,
ffn_hidden_size,
num_attention_heads,
attention_dropout_prob=attention_dropout_prob,
output_dropout_prob=output_dropout_prob,
layernorm_epsilon=layernorm_epsilon,
init_method=init_method,
output_layer_init_method=output_layer_init_method,
bias_gelu_fusion=bias_gelu_fusion,
bias_dropout_fusion=bias_dropout_fusion,
scale_mask_softmax_fusion=scale_mask_softmax_fusion,
apply_query_key_layer_scaling=apply_query_key_layer_scaling,
apply_residual_post_layernorm=apply_residual_post_layernorm,
)
self.lm_head = LMLogits(vocab_size, bias=False)
@classmethod
def from_config(cls, cfg):
return {
"num_layers": cfg.num_layers,
"vocab_size": cfg.vocab_size,
"hidden_size": cfg.hidden_size,
"ffn_hidden_size": cfg.ffn_hidden_size,
"num_attention_heads": cfg.num_attention_heads,
"max_seq_length": cfg.max_seq_length,
"embedding_dropout_prob": cfg.embedding_dropout_prob,
"attention_dropout_prob": cfg.attention_dropout_prob,
"output_dropout_prob": cfg.output_dropout_prob,
"layernorm_epsilon": cfg.layernorm_epsilon,
"initializer_range": cfg.initializer_range,
"use_scaled_init_for_output_weights": cfg.use_scaled_init_for_output_weights,
"bias_gelu_fusion": cfg.bias_gelu_fusion,
"bias_dropout_fusion": cfg.bias_dropout_fusion,
"scale_mask_softmax_fusion": cfg.scale_mask_softmax_fusion,
"apply_query_key_layer_scaling": cfg.apply_query_key_layer_scaling,
"apply_residual_post_layernorm": cfg.apply_residual_post_layernorm,
"amp_enabled": cfg.amp_enabled,
}
def forward(self, input_ids):
"""
Args:
input_ids (flow.LongTensor): Indices of input sequence tokens in vocabulary.
Returns:
flow.Tensor: logits
"""
input_embeds = self.embeddings(input_ids, 0)
attention_mask = self.casual_mask(input_ids, past_length=0)
transformer_output = self.transformer(input_embeds, attention_mask)
output = self.lm_head(transformer_output, self.embeddings.token_embeddings.weight)
return output
class GPTEmbedding(nn.Module):
def __init__(
self,
vocab_size,
hidden_size,
max_seq_length,
init_method=init.xavier_normal_,
embedding_dropout_prob=0.0,
amp_enabled=False,
):
super().__init__()
self.token_embeddings = VocabEmbedding(
vocab_size, hidden_size, init_method=init_method, amp_enabled=amp_enabled
)
self.position_embeddings = Embedding(
max_seq_length, hidden_size, init_method=init_method, amp_enabled=amp_enabled
)
self.dropout = nn.Dropout(embedding_dropout_prob)
self.position_ids = flow.arange(
max_seq_length,
dtype=flow.long,
sbp=dist.get_nd_sbp([flow.sbp.broadcast, flow.sbp.broadcast]),
placement=dist.get_layer_placement(0),
).unsqueeze(0)
def forward(self, input_ids, past_length=0):
bsz, seq_length = input_ids.size()
position_ids = self.position_ids[:, past_length : past_length + seq_length]
position_ids = position_ids.expand_as(input_ids).to_global(sbp=input_ids.sbp)
token_embeds = self.token_embeddings(input_ids)
position_embeds = self.position_embeddings(position_ids)
input_embeds = token_embeds + position_embeds
input_embeds = self.dropout(input_embeds)
return input_embeds
class Transformer(nn.Module):
def __init__(
self,
num_layers,
hidden_size,
ffn_hidden_size,
num_attention_heads,
attention_dropout_prob=0.0,
output_dropout_prob=0.0,
layernorm_epsilon=1e-5,
init_method=init.xavier_normal_,
output_layer_init_method=None,
bias_gelu_fusion=False,
bias_dropout_fusion=False,
scale_mask_softmax_fusion=False,
apply_query_key_layer_scaling=False,
apply_residual_post_layernorm=False,
):
super().__init__()
self.num_layers = num_layers
def build_layer(layer_number):
return TransformerLayer(
hidden_size,
ffn_hidden_size,
num_attention_heads,
attention_dropout_prob=attention_dropout_prob,
output_dropout_prob=output_dropout_prob,
layernorm_epsilon=layernorm_epsilon,
init_method=init_method,
output_layer_init_method=output_layer_init_method,
bias_gelu_fusion=bias_gelu_fusion,
bias_dropout_fusion=bias_dropout_fusion,
scale_mask_softmax_fusion=scale_mask_softmax_fusion,
apply_query_key_layer_scaling=apply_query_key_layer_scaling,
apply_residual_post_layernorm=apply_residual_post_layernorm,
layer_idx=layer_number,
)
self.layers = nn.ModuleList([build_layer(i) for i in range(self.num_layers)])
self.layernorm_f = LayerNorm(hidden_size, eps=layernorm_epsilon, layer_idx=-1)
def forward(self, hidden_states, attention_mask):
# hidden_states shape: (batch_size, seq_length, hidden_size)
# sbp: [S(0), B]
for i, layer in enumerate(self.layers):
hidden_states = layer(hidden_states, attention_mask)
output = self.layernorm_f(hidden_states)
return output
class GPTLoss(nn.Module):
def __init__(self) -> None:
super().__init__()
self.lm_loss = ParallelCrossEntropyLoss()
def forward(self, logits, lm_labels):
lm_loss = self.lm_loss(logits, lm_labels)
lm_loss = lm_loss.mean()
return {"lm_loss": lm_loss}
class GPTForPreTraining(nn.Module):
"""
GPT Model with classification head on top.
"""
def __init__(self, cfg) -> None:
super().__init__()
self.GPT_model = GPTModel(cfg)
self.loss_func = GPTLoss()
def forward(
self,
input_ids,
labels=None,
):
"""
Args:
input_ids (flow.LongTensor): Indices of input sequence tokens in vocabulary.
labels (flow.LongTensor, optional): Labels for computing language modeling loss.
None for evaluating. Defaults to None.
Returns:
dict:
A dict containing :code:`loss_value` or :code:`logits`
depending on training or evaluation.
:code:`{"masked_lm_loss": loss_value}` when training,
:code:`{"prediction_scores": logits}` when evaluating.
"""
logits = self.GPT_model(input_ids)
if labels is not None:
lm_loss = self.loss_func(logits, labels)
return lm_loss
else:
return {"prediction_scores": logits}
@staticmethod
def set_pipeline_stage_id(model: nn.Module):
dist_utils = dist.get_dist_util()
for module_block in model.modules():
if isinstance(module_block.origin, (GPTEmbedding, CasualMask)):
module_block.config.stage_id = dist_utils.get_layer_stage_id(0)
elif isinstance(module_block.origin, TransformerLayer):
module_block.config.stage_id = dist_utils.get_layer_stage_id(module_block.layer_idx)
elif isinstance(module_block.origin, (LMLogits, GPTLoss)):
module_block.config.stage_id = dist_utils.get_layer_stage_id(-1)
model.GPT_model.transformer.layernorm_f.config.stage_id = dist_utils.get_layer_stage_id(-1)
| [
"oneflow.nn.Dropout",
"oneflow.ones"
] | [((7148, 7180), 'libai.layers.LMLogits', 'LMLogits', (['vocab_size'], {'bias': '(False)'}), '(vocab_size, bias=False)\n', (7156, 7180), False, 'from libai.layers import Embedding, LayerNorm, LMLogits, ParallelCrossEntropyLoss, TransformerLayer, VocabEmbedding\n'), ((9158, 9251), 'libai.layers.VocabEmbedding', 'VocabEmbedding', (['vocab_size', 'hidden_size'], {'init_method': 'init_method', 'amp_enabled': 'amp_enabled'}), '(vocab_size, hidden_size, init_method=init_method,\n amp_enabled=amp_enabled)\n', (9172, 9251), False, 'from libai.layers import Embedding, LayerNorm, LMLogits, ParallelCrossEntropyLoss, TransformerLayer, VocabEmbedding\n'), ((9305, 9398), 'libai.layers.Embedding', 'Embedding', (['max_seq_length', 'hidden_size'], {'init_method': 'init_method', 'amp_enabled': 'amp_enabled'}), '(max_seq_length, hidden_size, init_method=init_method, amp_enabled\n =amp_enabled)\n', (9314, 9398), False, 'from libai.layers import Embedding, LayerNorm, LMLogits, ParallelCrossEntropyLoss, TransformerLayer, VocabEmbedding\n'), ((9439, 9473), 'oneflow.nn.Dropout', 'nn.Dropout', (['embedding_dropout_prob'], {}), '(embedding_dropout_prob)\n', (9449, 9473), False, 'from oneflow import nn\n'), ((11805, 11864), 'libai.layers.LayerNorm', 'LayerNorm', (['hidden_size'], {'eps': 'layernorm_epsilon', 'layer_idx': '(-1)'}), '(hidden_size, eps=layernorm_epsilon, layer_idx=-1)\n', (11814, 11864), False, 'from libai.layers import Embedding, LayerNorm, LMLogits, ParallelCrossEntropyLoss, TransformerLayer, VocabEmbedding\n'), ((12310, 12336), 'libai.layers.ParallelCrossEntropyLoss', 'ParallelCrossEntropyLoss', ([], {}), '()\n', (12334, 12336), False, 'from libai.layers import Embedding, LayerNorm, LMLogits, ParallelCrossEntropyLoss, TransformerLayer, VocabEmbedding\n'), ((13701, 13721), 'libai.utils.distributed.get_dist_util', 'dist.get_dist_util', ([], {}), '()\n', (13719, 13721), True, 'from libai.utils import distributed as dist\n'), ((10908, 11489), 'libai.layers.TransformerLayer', 'TransformerLayer', (['hidden_size', 'ffn_hidden_size', 'num_attention_heads'], {'attention_dropout_prob': 'attention_dropout_prob', 'output_dropout_prob': 'output_dropout_prob', 'layernorm_epsilon': 'layernorm_epsilon', 'init_method': 'init_method', 'output_layer_init_method': 'output_layer_init_method', 'bias_gelu_fusion': 'bias_gelu_fusion', 'bias_dropout_fusion': 'bias_dropout_fusion', 'scale_mask_softmax_fusion': 'scale_mask_softmax_fusion', 'apply_query_key_layer_scaling': 'apply_query_key_layer_scaling', 'apply_residual_post_layernorm': 'apply_residual_post_layernorm', 'layer_idx': 'layer_number'}), '(hidden_size, ffn_hidden_size, num_attention_heads,\n attention_dropout_prob=attention_dropout_prob, output_dropout_prob=\n output_dropout_prob, layernorm_epsilon=layernorm_epsilon, init_method=\n init_method, output_layer_init_method=output_layer_init_method,\n bias_gelu_fusion=bias_gelu_fusion, bias_dropout_fusion=\n bias_dropout_fusion, scale_mask_softmax_fusion=\n scale_mask_softmax_fusion, apply_query_key_layer_scaling=\n apply_query_key_layer_scaling, apply_residual_post_layernorm=\n apply_residual_post_layernorm, layer_idx=layer_number)\n', (10924, 11489), False, 'from libai.layers import Embedding, LayerNorm, LMLogits, ParallelCrossEntropyLoss, TransformerLayer, VocabEmbedding\n'), ((1490, 1525), 'libai.utils.distributed.get_layer_placement', 'dist.get_layer_placement', (['layer_idx'], {}), '(layer_idx)\n', (1514, 1525), True, 'from libai.utils import distributed as dist\n'), ((1547, 1604), 'libai.utils.distributed.get_nd_sbp', 'dist.get_nd_sbp', (['[flow.sbp.broadcast, flow.sbp.broadcast]'], {}), '([flow.sbp.broadcast, flow.sbp.broadcast])\n', (1562, 1604), True, 'from libai.utils import distributed as dist\n'), ((1971, 2019), 'oneflow.ones', 'flow.ones', (['tgt_len', 'past_length'], {'dtype': 'flow.int8'}), '(tgt_len, past_length, dtype=flow.int8)\n', (1980, 2019), True, 'import oneflow as flow\n'), ((9589, 9646), 'libai.utils.distributed.get_nd_sbp', 'dist.get_nd_sbp', (['[flow.sbp.broadcast, flow.sbp.broadcast]'], {}), '([flow.sbp.broadcast, flow.sbp.broadcast])\n', (9604, 9646), True, 'from libai.utils import distributed as dist\n'), ((9670, 9697), 'libai.utils.distributed.get_layer_placement', 'dist.get_layer_placement', (['(0)'], {}), '(0)\n', (9694, 9697), True, 'from libai.utils import distributed as dist\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_nllloss_none_backward(test_case, device):
x = np.array(
[
[0.88103855, 0.9908683, 0.6226845],
[0.53331435, 0.07999352, 0.8549948],
[0.25879037, 0.39530203, 0.698465],
[0.73427284, 0.63575995, 0.18827209],
[0.05689114, 0.0862954, 0.6325046],
]
).astype(np.float32)
y = np.array([0, 2, 1, 1, 0]).astype(np.int)
input = flow.Tensor(
x, dtype=flow.float32, device=flow.device(device), requires_grad=True
)
target = flow.Tensor(
y, dtype=flow.int64, device=flow.device(device), requires_grad=True
)
nll_loss = flow.nn.NLLLoss()
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
of_out = of_out.sum()
of_out.backward()
print(input.grad.numpy())
def _test_nllloss_mean(test_case, device):
x = np.array(
[
[0.88103855, 0.9908683, 0.6226845],
[0.53331435, 0.07999352, 0.8549948],
[0.25879037, 0.39530203, 0.698465],
[0.73427284, 0.63575995, 0.18827209],
[0.05689114, 0.0862954, 0.6325046],
]
).astype(np.float32)
y = np.array([0, 2, 1, 1, 0]).astype(np.int)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="mean")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_1d(input.numpy(), target.numpy(), reduction="mean")
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_sum(test_case, device):
x = np.array(
[
[0.88103855, 0.9908683, 0.6226845],
[0.53331435, 0.07999352, 0.8549948],
[0.25879037, 0.39530203, 0.698465],
[0.73427284, 0.63575995, 0.18827209],
[0.05689114, 0.0862954, 0.6325046],
]
).astype(np.float32)
y = np.array([0, 2, 1, 1, 0]).astype(np.int)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="sum")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_1d(input.numpy(), target.numpy(), reduction="sum")
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_segmentation_none(test_case, device):
x = np.array(
[[[[0.12, 0.36], [0.22, 0.66]], [[0.13, 0.34], [0.52, -0.96]]]]
).astype(np.float32)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
y = np.array([[[1, 0], [0, 1]]]).astype(np.int)
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss()
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_2d(input.numpy(), target.numpy())
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_segmentation_mean(test_case, device):
x = np.array(
[[[[0.12, 0.36], [0.22, 0.66]], [[0.13, 0.34], [0.52, -0.96]]]]
).astype(np.float32)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
y = np.array([[[1, 0], [0, 1]]]).astype(np.int)
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="mean")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_2d(input.numpy(), target.numpy(), reduction="mean")
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_segmentation_sum(test_case, device):
x = np.array(
[[[[0.12, 0.36], [0.22, 0.66]], [[0.13, 0.34], [0.52, -0.96]]]]
).astype(np.float32)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
y = np.array([[[1, 0], [0, 1]]]).astype(np.int)
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="sum")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_2d(input.numpy(), target.numpy(), reduction="sum")
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_bert_none(test_case, device):
x = np.array([[[0.12, 0.36, 0.22, 0.66], [0.13, 0.34, 0.52, -0.96]]]).astype(
np.float32
)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
y = np.array([[1, 0, 0, 1]]).astype(np.int)
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss()
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_bert(input.numpy(), target.numpy())
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_bert_mean(test_case, device):
x = np.array([[[0.12, 0.36, 0.22, 0.66], [0.13, 0.34, 0.52, -0.96]]]).astype(
np.float32
)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
y = np.array([[1, 0, 0, 1]]).astype(np.int)
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="mean")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_bert(input.numpy(), target.numpy(), reduction="mean")
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_bert_sum(test_case, device):
x = np.array([[[0.12, 0.36, 0.22, 0.66], [0.13, 0.34, 0.52, -0.96]]]).astype(
np.float32
)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
y = np.array([[1, 0, 0, 1]]).astype(np.int)
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="sum")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_bert(input.numpy(), target.numpy(), reduction="sum")
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestNLLLossModule(flow.unittest.TestCase):
def test_nllloss(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [
_test_nllloss_none_backward,
]
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.env.eager_execution_enabled",
"oneflow.experimental.nn.NLLLoss",
"oneflow.experimental.device"
] | [((1374, 1391), 'oneflow.experimental.nn.NLLLoss', 'flow.nn.NLLLoss', ([], {}), '()\n', (1389, 1391), True, 'import oneflow.experimental as flow\n'), ((2107, 2140), 'oneflow.experimental.nn.NLLLoss', 'flow.nn.NLLLoss', ([], {'reduction': '"""mean"""'}), "(reduction='mean')\n", (2122, 2140), True, 'import oneflow.experimental as flow\n'), ((2913, 2945), 'oneflow.experimental.nn.NLLLoss', 'flow.nn.NLLLoss', ([], {'reduction': '"""sum"""'}), "(reduction='sum')\n", (2928, 2945), True, 'import oneflow.experimental as flow\n'), ((3542, 3559), 'oneflow.experimental.nn.NLLLoss', 'flow.nn.NLLLoss', ([], {}), '()\n', (3557, 3559), True, 'import oneflow.experimental as flow\n'), ((4139, 4172), 'oneflow.experimental.nn.NLLLoss', 'flow.nn.NLLLoss', ([], {'reduction': '"""mean"""'}), "(reduction='mean')\n", (4154, 4172), True, 'import oneflow.experimental as flow\n'), ((4769, 4801), 'oneflow.experimental.nn.NLLLoss', 'flow.nn.NLLLoss', ([], {'reduction': '"""sum"""'}), "(reduction='sum')\n", (4784, 4801), True, 'import oneflow.experimental as flow\n'), ((5378, 5395), 'oneflow.experimental.nn.NLLLoss', 'flow.nn.NLLLoss', ([], {}), '()\n', (5393, 5395), True, 'import oneflow.experimental as flow\n'), ((5957, 5990), 'oneflow.experimental.nn.NLLLoss', 'flow.nn.NLLLoss', ([], {'reduction': '"""mean"""'}), "(reduction='mean')\n", (5972, 5990), True, 'import oneflow.experimental as flow\n'), ((6569, 6601), 'oneflow.experimental.nn.NLLLoss', 'flow.nn.NLLLoss', ([], {'reduction': '"""sum"""'}), "(reduction='sum')\n", (6584, 6601), True, 'import oneflow.experimental as flow\n'), ((7286, 7301), 'unittest.main', 'unittest.main', ([], {}), '()\n', (7299, 7301), False, 'import unittest\n'), ((7029, 7042), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (7040, 7042), False, 'from collections import OrderedDict\n'), ((7191, 7211), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (7201, 7211), False, 'from test_util import GenArgList\n'), ((6839, 6882), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (6880, 6882), True, 'import oneflow.experimental as flow\n'), ((794, 996), 'numpy.array', 'np.array', (['[[0.88103855, 0.9908683, 0.6226845], [0.53331435, 0.07999352, 0.8549948], [\n 0.25879037, 0.39530203, 0.698465], [0.73427284, 0.63575995, 0.18827209],\n [0.05689114, 0.0862954, 0.6325046]]'], {}), '([[0.88103855, 0.9908683, 0.6226845], [0.53331435, 0.07999352, \n 0.8549948], [0.25879037, 0.39530203, 0.698465], [0.73427284, 0.63575995,\n 0.18827209], [0.05689114, 0.0862954, 0.6325046]])\n', (802, 996), True, 'import numpy as np\n'), ((1100, 1125), 'numpy.array', 'np.array', (['[0, 2, 1, 1, 0]'], {}), '([0, 2, 1, 1, 0])\n', (1108, 1125), True, 'import numpy as np\n'), ((1204, 1223), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (1215, 1223), True, 'import oneflow.experimental as flow\n'), ((1313, 1332), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (1324, 1332), True, 'import oneflow.experimental as flow\n'), ((1595, 1797), 'numpy.array', 'np.array', (['[[0.88103855, 0.9908683, 0.6226845], [0.53331435, 0.07999352, 0.8549948], [\n 0.25879037, 0.39530203, 0.698465], [0.73427284, 0.63575995, 0.18827209],\n [0.05689114, 0.0862954, 0.6325046]]'], {}), '([[0.88103855, 0.9908683, 0.6226845], [0.53331435, 0.07999352, \n 0.8549948], [0.25879037, 0.39530203, 0.698465], [0.73427284, 0.63575995,\n 0.18827209], [0.05689114, 0.0862954, 0.6325046]])\n', (1603, 1797), True, 'import numpy as np\n'), ((1901, 1926), 'numpy.array', 'np.array', (['[0, 2, 1, 1, 0]'], {}), '([0, 2, 1, 1, 0])\n', (1909, 1926), True, 'import numpy as np\n'), ((1996, 2015), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (2007, 2015), True, 'import oneflow.experimental as flow\n'), ((2071, 2090), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (2082, 2090), True, 'import oneflow.experimental as flow\n'), ((2401, 2603), 'numpy.array', 'np.array', (['[[0.88103855, 0.9908683, 0.6226845], [0.53331435, 0.07999352, 0.8549948], [\n 0.25879037, 0.39530203, 0.698465], [0.73427284, 0.63575995, 0.18827209],\n [0.05689114, 0.0862954, 0.6325046]]'], {}), '([[0.88103855, 0.9908683, 0.6226845], [0.53331435, 0.07999352, \n 0.8549948], [0.25879037, 0.39530203, 0.698465], [0.73427284, 0.63575995,\n 0.18827209], [0.05689114, 0.0862954, 0.6325046]])\n', (2409, 2603), True, 'import numpy as np\n'), ((2707, 2732), 'numpy.array', 'np.array', (['[0, 2, 1, 1, 0]'], {}), '([0, 2, 1, 1, 0])\n', (2715, 2732), True, 'import numpy as np\n'), ((2802, 2821), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (2813, 2821), True, 'import oneflow.experimental as flow\n'), ((2877, 2896), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (2888, 2896), True, 'import oneflow.experimental as flow\n'), ((3219, 3292), 'numpy.array', 'np.array', (['[[[[0.12, 0.36], [0.22, 0.66]], [[0.13, 0.34], [0.52, -0.96]]]]'], {}), '([[[[0.12, 0.36], [0.22, 0.66]], [[0.13, 0.34], [0.52, -0.96]]]])\n', (3227, 3292), True, 'import numpy as np\n'), ((3380, 3399), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (3391, 3399), True, 'import oneflow.experimental as flow\n'), ((3409, 3437), 'numpy.array', 'np.array', (['[[[1, 0], [0, 1]]]'], {}), '([[[1, 0], [0, 1]]])\n', (3417, 3437), True, 'import numpy as np\n'), ((3506, 3525), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (3517, 3525), True, 'import oneflow.experimental as flow\n'), ((3816, 3889), 'numpy.array', 'np.array', (['[[[[0.12, 0.36], [0.22, 0.66]], [[0.13, 0.34], [0.52, -0.96]]]]'], {}), '([[[[0.12, 0.36], [0.22, 0.66]], [[0.13, 0.34], [0.52, -0.96]]]])\n', (3824, 3889), True, 'import numpy as np\n'), ((3977, 3996), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (3988, 3996), True, 'import oneflow.experimental as flow\n'), ((4006, 4034), 'numpy.array', 'np.array', (['[[[1, 0], [0, 1]]]'], {}), '([[[1, 0], [0, 1]]])\n', (4014, 4034), True, 'import numpy as np\n'), ((4103, 4122), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (4114, 4122), True, 'import oneflow.experimental as flow\n'), ((4446, 4519), 'numpy.array', 'np.array', (['[[[[0.12, 0.36], [0.22, 0.66]], [[0.13, 0.34], [0.52, -0.96]]]]'], {}), '([[[[0.12, 0.36], [0.22, 0.66]], [[0.13, 0.34], [0.52, -0.96]]]])\n', (4454, 4519), True, 'import numpy as np\n'), ((4607, 4626), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (4618, 4626), True, 'import oneflow.experimental as flow\n'), ((4636, 4664), 'numpy.array', 'np.array', (['[[[1, 0], [0, 1]]]'], {}), '([[[1, 0], [0, 1]]])\n', (4644, 4664), True, 'import numpy as np\n'), ((4733, 4752), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (4744, 4752), True, 'import oneflow.experimental as flow\n'), ((5067, 5132), 'numpy.array', 'np.array', (['[[[0.12, 0.36, 0.22, 0.66], [0.13, 0.34, 0.52, -0.96]]]'], {}), '([[[0.12, 0.36, 0.22, 0.66], [0.13, 0.34, 0.52, -0.96]]])\n', (5075, 5132), True, 'import numpy as np\n'), ((5220, 5239), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (5231, 5239), True, 'import oneflow.experimental as flow\n'), ((5249, 5273), 'numpy.array', 'np.array', (['[[1, 0, 0, 1]]'], {}), '([[1, 0, 0, 1]])\n', (5257, 5273), True, 'import numpy as np\n'), ((5342, 5361), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (5353, 5361), True, 'import oneflow.experimental as flow\n'), ((5646, 5711), 'numpy.array', 'np.array', (['[[[0.12, 0.36, 0.22, 0.66], [0.13, 0.34, 0.52, -0.96]]]'], {}), '([[[0.12, 0.36, 0.22, 0.66], [0.13, 0.34, 0.52, -0.96]]])\n', (5654, 5711), True, 'import numpy as np\n'), ((5799, 5818), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (5810, 5818), True, 'import oneflow.experimental as flow\n'), ((5828, 5852), 'numpy.array', 'np.array', (['[[1, 0, 0, 1]]'], {}), '([[1, 0, 0, 1]])\n', (5836, 5852), True, 'import numpy as np\n'), ((5921, 5940), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (5932, 5940), True, 'import oneflow.experimental as flow\n'), ((6258, 6323), 'numpy.array', 'np.array', (['[[[0.12, 0.36, 0.22, 0.66], [0.13, 0.34, 0.52, -0.96]]]'], {}), '([[[0.12, 0.36, 0.22, 0.66], [0.13, 0.34, 0.52, -0.96]]])\n', (6266, 6323), True, 'import numpy as np\n'), ((6411, 6430), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (6422, 6430), True, 'import oneflow.experimental as flow\n'), ((6440, 6464), 'numpy.array', 'np.array', (['[[1, 0, 0, 1]]'], {}), '([[1, 0, 0, 1]])\n', (6448, 6464), True, 'import numpy as np\n'), ((6533, 6552), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (6544, 6552), 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 os
import unittest
from collections import OrderedDict
from typing import Dict
import numpy as np
from test_util import GenArgList
import oneflow.compatible.single_client.unittest
from oneflow.compatible import single_client as flow
from oneflow.compatible.single_client import typing as tp
def _compare_margin_ranking_loss_with_np(
input1_shape,
input2_shape,
target_shape,
margin,
device_type,
machine_ids,
device_counts,
):
input1 = np.random.random(size=input1_shape).astype(np.float32)
input2 = np.random.random(size=input2_shape).astype(np.float32)
target = np.random.random(size=target_shape).astype(np.float32)
assert device_type in ["cpu", "gpu"]
flow.clear_default_session()
if device_type == "cpu":
flow.config.cpu_device_num(device_counts)
else:
flow.config.gpu_device_num(device_counts)
func_config = flow.FunctionConfig()
func_config.default_placement_scope(flow.scope.placement(device_type, machine_ids))
func_config.default_logical_view(flow.scope.consistent_view())
def np_margin_ranking_loss(np_input1, np_input2, np_target, np_margin):
np_target = np.broadcast_to(np_target, shape=np_input1.shape)
np_margin_loss = np.maximum(0, -(np_input1 - np_input2) * np_target + np_margin)
np_margin_loss_mean = np.mean(np_margin_loss)
np_margin_loss_sum = np.sum(np_margin_loss)
return {
"np_margin_ranking_loss": np_margin_loss,
"np_margin_ranking_loss_mean": np_margin_loss_mean,
"np_margin_ranking_loss_sum": np_margin_loss_sum,
}
np_out_marginloss_dict = np_margin_ranking_loss(input1, input2, target, margin)
def np_margin_ranking_diff(np_out, np_target):
_elem_cnt = np_out.size
if np_out.shape != np_target.shape:
np_target = np.broadcast_to(np_target, shape=np_out.shape)
_clip_zero_index = np.where(np_out > 0, 1, 0)
_np_grad = -np_target
return {"np_margin_ranking_grad_mean": _np_grad * _clip_zero_index / _elem_cnt}
np_grad_dict = np_margin_ranking_diff(
np_out_marginloss_dict["np_margin_ranking_loss"], target
)
def assert_prediction_grad(blob: tp.Numpy):
assert np.allclose(blob, np_grad_dict["np_margin_ranking_grad_mean"])
@flow.global_function(type="train", function_config=func_config)
def oneflow_marginloss(
of_input1: tp.Numpy.Placeholder(shape=input1.shape),
of_input2: tp.Numpy.Placeholder(shape=input2.shape),
of_target: tp.Numpy.Placeholder(shape=target.shape),
) -> Dict[str, tp.Numpy]:
with flow.scope.placement(device_type, "0:0"):
v = flow.get_variable(
shape=input1.shape,
dtype=flow.float32,
initializer=flow.constant_initializer(0),
name="x_var",
)
x_var = of_input1 + v
flow.watch_diff(x_var, assert_prediction_grad)
marginloss = flow.nn.MarginRankingLoss(
of_input1,
of_input2,
of_target,
margin=margin,
reduction="none",
name="of_marginloss",
)
marginloss_mean = flow.nn.MarginRankingLoss(
x_var,
of_input2,
of_target,
margin=margin,
reduction="mean",
name="of_marginloss_reduce_mean",
)
marginloss_sum = flow.nn.MarginRankingLoss(
of_input1,
of_input2,
of_target,
margin=margin,
reduction="sum",
name="of_marginloss_reduce_sum",
)
with flow.scope.placement(device_type, "0:0"):
flow.optimizer.SGD(
flow.optimizer.PiecewiseConstantScheduler([], [0.001]), momentum=0
).minimize(marginloss_mean)
return {
"of_margin_ranking_loss": marginloss,
"of_margin_ranking_loss_mean": marginloss_mean,
"of_margin_ranking_loss_sum": marginloss_sum,
}
of_out_marginloss_dict = oneflow_marginloss(input1, input2, target)
assert np.allclose(
of_out_marginloss_dict["of_margin_ranking_loss"],
np_out_marginloss_dict["np_margin_ranking_loss"],
)
assert np.allclose(
of_out_marginloss_dict["of_margin_ranking_loss_mean"],
np_out_marginloss_dict["np_margin_ranking_loss_mean"],
)
assert np.allclose(
of_out_marginloss_dict["of_margin_ranking_loss_sum"],
np_out_marginloss_dict["np_margin_ranking_loss_sum"],
)
def _gen_arg_dict(shape, target_shape, margin, device_type, machine_ids, device_counts):
arg_dict = OrderedDict()
arg_dict["input1_shape"] = [shape]
arg_dict["input2_shape"] = [shape]
arg_dict["target_shape"] = [target_shape]
arg_dict["margin"] = [margin]
arg_dict["device_type"] = [device_type]
arg_dict["machine_ids"] = [machine_ids]
arg_dict["device_counts"] = [device_counts]
return arg_dict
@flow.unittest.skip_unless_1n1d()
class Testmarginloss1n1d(flow.unittest.TestCase):
def test_margin_ranking_loss_cpu(test_case):
arg_dict = _gen_arg_dict(
shape=(3, 5),
target_shape=(3, 1),
margin=0.3,
device_type="cpu",
machine_ids="0:0",
device_counts=1,
)
for arg in GenArgList(arg_dict):
_compare_margin_ranking_loss_with_np(*arg)
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def test_margin_ranking_loss_gpu(test_case):
arg_dict = _gen_arg_dict(
shape=(4, 5),
target_shape=(4, 1),
margin=0.3,
device_type="gpu",
machine_ids="0:0",
device_counts=1,
)
for arg in GenArgList(arg_dict):
_compare_margin_ranking_loss_with_np(*arg)
@flow.unittest.skip_unless_1n2d()
class Testmarginloss1n2d(flow.unittest.TestCase):
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def test_margin_ranking_loss_1n2d(test_case):
arg_dict = _gen_arg_dict(
shape=(3, 3),
target_shape=(3, 1),
margin=0.3,
device_type="gpu",
machine_ids="0:0-1",
device_counts=2,
)
for arg in GenArgList(arg_dict):
_compare_margin_ranking_loss_with_np(*arg)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.compatible.single_client.clear_default_session",
"oneflow.compatible.single_client.watch_diff",
"oneflow.compatible.single_client.nn.MarginRankingLoss",
"oneflow.compatible.single_client.constant_initializer",
"oneflow.compatible.single_client.FunctionConfig",
"oneflow.compatible.single_client.unittest.skip_unless_1n2d",
"oneflow.compatible.single_client.optimizer.PiecewiseConstantScheduler",
"oneflow.compatible.single_client.typing.Numpy.Placeholder",
"oneflow.compatible.single_client.unittest.skip_unless_1n1d",
"oneflow.compatible.single_client.config.cpu_device_num",
"oneflow.compatible.single_client.config.gpu_device_num",
"oneflow.compatible.single_client.scope.placement",
"oneflow.compatible.single_client.scope.consistent_view",
"oneflow.compatible.single_client.global_function"
] | [((5632, 5664), 'oneflow.compatible.single_client.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (5662, 5664), True, 'from oneflow.compatible import single_client as flow\n'), ((6525, 6557), 'oneflow.compatible.single_client.unittest.skip_unless_1n2d', 'flow.unittest.skip_unless_1n2d', ([], {}), '()\n', (6555, 6557), True, 'from oneflow.compatible import single_client as flow\n'), ((1306, 1334), 'oneflow.compatible.single_client.clear_default_session', 'flow.clear_default_session', ([], {}), '()\n', (1332, 1334), True, 'from oneflow.compatible import single_client as flow\n'), ((1492, 1513), 'oneflow.compatible.single_client.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (1511, 1513), True, 'from oneflow.compatible import single_client as flow\n'), ((2922, 2985), 'oneflow.compatible.single_client.global_function', 'flow.global_function', ([], {'type': '"""train"""', 'function_config': 'func_config'}), "(type='train', function_config=func_config)\n", (2942, 2985), True, 'from oneflow.compatible import single_client as flow\n'), ((4750, 4865), 'numpy.allclose', 'np.allclose', (["of_out_marginloss_dict['of_margin_ranking_loss']", "np_out_marginloss_dict['np_margin_ranking_loss']"], {}), "(of_out_marginloss_dict['of_margin_ranking_loss'],\n np_out_marginloss_dict['np_margin_ranking_loss'])\n", (4761, 4865), True, 'import numpy as np\n'), ((4896, 5021), 'numpy.allclose', 'np.allclose', (["of_out_marginloss_dict['of_margin_ranking_loss_mean']", "np_out_marginloss_dict['np_margin_ranking_loss_mean']"], {}), "(of_out_marginloss_dict['of_margin_ranking_loss_mean'],\n np_out_marginloss_dict['np_margin_ranking_loss_mean'])\n", (4907, 5021), True, 'import numpy as np\n'), ((5052, 5175), 'numpy.allclose', 'np.allclose', (["of_out_marginloss_dict['of_margin_ranking_loss_sum']", "np_out_marginloss_dict['np_margin_ranking_loss_sum']"], {}), "(of_out_marginloss_dict['of_margin_ranking_loss_sum'],\n np_out_marginloss_dict['np_margin_ranking_loss_sum'])\n", (5063, 5175), True, 'import numpy as np\n'), ((5301, 5314), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (5312, 5314), False, 'from collections import OrderedDict\n'), ((7087, 7102), 'unittest.main', 'unittest.main', ([], {}), '()\n', (7100, 7102), False, 'import unittest\n'), ((1372, 1413), 'oneflow.compatible.single_client.config.cpu_device_num', 'flow.config.cpu_device_num', (['device_counts'], {}), '(device_counts)\n', (1398, 1413), True, 'from oneflow.compatible import single_client as flow\n'), ((1432, 1473), 'oneflow.compatible.single_client.config.gpu_device_num', 'flow.config.gpu_device_num', (['device_counts'], {}), '(device_counts)\n', (1458, 1473), True, 'from oneflow.compatible import single_client as flow\n'), ((1554, 1600), 'oneflow.compatible.single_client.scope.placement', 'flow.scope.placement', (['device_type', 'machine_ids'], {}), '(device_type, machine_ids)\n', (1574, 1600), True, 'from oneflow.compatible import single_client as flow\n'), ((1639, 1667), 'oneflow.compatible.single_client.scope.consistent_view', 'flow.scope.consistent_view', ([], {}), '()\n', (1665, 1667), True, 'from oneflow.compatible import single_client as flow\n'), ((1766, 1815), 'numpy.broadcast_to', 'np.broadcast_to', (['np_target'], {'shape': 'np_input1.shape'}), '(np_target, shape=np_input1.shape)\n', (1781, 1815), True, 'import numpy as np\n'), ((1841, 1904), 'numpy.maximum', 'np.maximum', (['(0)', '(-(np_input1 - np_input2) * np_target + np_margin)'], {}), '(0, -(np_input1 - np_input2) * np_target + np_margin)\n', (1851, 1904), True, 'import numpy as np\n'), ((1935, 1958), 'numpy.mean', 'np.mean', (['np_margin_loss'], {}), '(np_margin_loss)\n', (1942, 1958), True, 'import numpy as np\n'), ((1988, 2010), 'numpy.sum', 'np.sum', (['np_margin_loss'], {}), '(np_margin_loss)\n', (1994, 2010), True, 'import numpy as np\n'), ((2529, 2555), 'numpy.where', 'np.where', (['(np_out > 0)', '(1)', '(0)'], {}), '(np_out > 0, 1, 0)\n', (2537, 2555), True, 'import numpy as np\n'), ((2853, 2915), 'numpy.allclose', 'np.allclose', (['blob', "np_grad_dict['np_margin_ranking_grad_mean']"], {}), "(blob, np_grad_dict['np_margin_ranking_grad_mean'])\n", (2864, 2915), True, 'import numpy as np\n'), ((3533, 3579), 'oneflow.compatible.single_client.watch_diff', 'flow.watch_diff', (['x_var', 'assert_prediction_grad'], {}), '(x_var, assert_prediction_grad)\n', (3548, 3579), True, 'from oneflow.compatible import single_client as flow\n'), ((3601, 3718), 'oneflow.compatible.single_client.nn.MarginRankingLoss', 'flow.nn.MarginRankingLoss', (['of_input1', 'of_input2', 'of_target'], {'margin': 'margin', 'reduction': '"""none"""', 'name': '"""of_marginloss"""'}), "(of_input1, of_input2, of_target, margin=margin,\n reduction='none', name='of_marginloss')\n", (3626, 3718), True, 'from oneflow.compatible import single_client as flow\n'), ((3824, 3949), 'oneflow.compatible.single_client.nn.MarginRankingLoss', 'flow.nn.MarginRankingLoss', (['x_var', 'of_input2', 'of_target'], {'margin': 'margin', 'reduction': '"""mean"""', 'name': '"""of_marginloss_reduce_mean"""'}), "(x_var, of_input2, of_target, margin=margin,\n reduction='mean', name='of_marginloss_reduce_mean')\n", (3849, 3949), True, 'from oneflow.compatible import single_client as flow\n'), ((4054, 4181), 'oneflow.compatible.single_client.nn.MarginRankingLoss', 'flow.nn.MarginRankingLoss', (['of_input1', 'of_input2', 'of_target'], {'margin': 'margin', 'reduction': '"""sum"""', 'name': '"""of_marginloss_reduce_sum"""'}), "(of_input1, of_input2, of_target, margin=margin,\n reduction='sum', name='of_marginloss_reduce_sum')\n", (4079, 4181), True, 'from oneflow.compatible import single_client as flow\n'), ((6001, 6021), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (6011, 6021), False, 'from test_util import GenArgList\n'), ((6445, 6465), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (6455, 6465), False, 'from test_util import GenArgList\n'), ((6100, 6134), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (6109, 6134), False, 'import os\n'), ((6977, 6997), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (6987, 6997), False, 'from test_util import GenArgList\n'), ((6629, 6663), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (6638, 6663), False, 'import os\n'), ((1070, 1105), 'numpy.random.random', 'np.random.random', ([], {'size': 'input1_shape'}), '(size=input1_shape)\n', (1086, 1105), True, 'import numpy as np\n'), ((1138, 1173), 'numpy.random.random', 'np.random.random', ([], {'size': 'input2_shape'}), '(size=input2_shape)\n', (1154, 1173), True, 'import numpy as np\n'), ((1206, 1241), 'numpy.random.random', 'np.random.random', ([], {'size': 'target_shape'}), '(size=target_shape)\n', (1222, 1241), True, 'import numpy as np\n'), ((2455, 2501), 'numpy.broadcast_to', 'np.broadcast_to', (['np_target'], {'shape': 'np_out.shape'}), '(np_target, shape=np_out.shape)\n', (2470, 2501), True, 'import numpy as np\n'), ((3033, 3073), 'oneflow.compatible.single_client.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', ([], {'shape': 'input1.shape'}), '(shape=input1.shape)\n', (3053, 3073), True, 'from oneflow.compatible.single_client import typing as tp\n'), ((3094, 3134), 'oneflow.compatible.single_client.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', ([], {'shape': 'input2.shape'}), '(shape=input2.shape)\n', (3114, 3134), True, 'from oneflow.compatible.single_client import typing as tp\n'), ((3155, 3195), 'oneflow.compatible.single_client.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', ([], {'shape': 'target.shape'}), '(shape=target.shape)\n', (3175, 3195), True, 'from oneflow.compatible.single_client import typing as tp\n'), ((3240, 3280), 'oneflow.compatible.single_client.scope.placement', 'flow.scope.placement', (['device_type', '"""0:0"""'], {}), "(device_type, '0:0')\n", (3260, 3280), True, 'from oneflow.compatible import single_client as flow\n'), ((4274, 4314), 'oneflow.compatible.single_client.scope.placement', 'flow.scope.placement', (['device_type', '"""0:0"""'], {}), "(device_type, '0:0')\n", (4294, 4314), True, 'from oneflow.compatible import single_client as flow\n'), ((3417, 3445), 'oneflow.compatible.single_client.constant_initializer', 'flow.constant_initializer', (['(0)'], {}), '(0)\n', (3442, 3445), True, 'from oneflow.compatible import single_client as flow\n'), ((4364, 4418), 'oneflow.compatible.single_client.optimizer.PiecewiseConstantScheduler', 'flow.optimizer.PiecewiseConstantScheduler', (['[]', '[0.001]'], {}), '([], [0.001])\n', (4405, 4418), True, 'from oneflow.compatible import single_client 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.
"""
# ###################################################################
# alexnet.py
# Usage:
# Single Node: python alexnet.py -g 1
# -g gpu number
# Multi Nodes: python alexnet.py -g 8 -m -n "192.168.1.15,192.168.1.16"
# -g gpu number
# -m run on multi nodes
# -n IP addresses of nodes, seperated by comma
# ###################################################################
import argparse
import oneflow as flow
DATA_DIR = "/dataset/imagenet_1k/oneflow/30/train"
parser = argparse.ArgumentParser(description="flags for multi-node and resource")
parser.add_argument("-i", "--iter_num", type=int, default=10, required=False)
parser.add_argument("-g", "--gpu_num_per_node", type=int, default=1, required=False)
parser.add_argument(
"-m", "--multinode", default=False, action="store_true", required=False
)
parser.add_argument("-n", "--node_list", type=str, default=None, required=False)
parser.add_argument("-e", "--eval_dir", type=str, default=DATA_DIR, required=False)
parser.add_argument("-t", "--train_dir", type=str, default=DATA_DIR, required=False)
parser.add_argument("-load", "--model_load_dir", type=str, default="", required=False)
parser.add_argument(
"-save", "--model_save_dir", type=str, default="./checkpoints", required=False
)
args = parser.parse_args()
def _data_load_layer(data_dir):
rgb_mean = [123.68, 116.78, 103.94]
ofrecord = flow.data.ofrecord_reader(
data_dir, batch_size=12, data_part_num=8, name="decode",
)
image = flow.data.ofrecord_image_decoder(ofrecord, "encoded", color_space="RGB")
label = flow.data.ofrecord_raw_decoder(
ofrecord, "class/label", shape=(), dtype=flow.int32
)
rsz = flow.image.resize(image, resize_x=227, resize_y=227, color_space="RGB")
normal = flow.image.crop_mirror_normalize(
rsz,
color_space="RGB",
output_layout="NCHW",
mean=rgb_mean,
output_dtype=flow.float,
)
return label, normal
def _conv2d_layer(
name,
input,
filters,
kernel_size=3,
strides=1,
padding="SAME",
data_format="NCHW",
dilation_rate=1,
activation="Relu",
use_bias=False,
weight_initializer=flow.random_uniform_initializer(),
bias_initializer=None,
):
weight_shape = (filters, input.shape[1], kernel_size, kernel_size)
weight = flow.get_variable(
name + "-weight",
shape=weight_shape,
dtype=input.dtype,
initializer=weight_initializer,
)
output = flow.nn.conv2d(
input, weight, strides, padding, data_format, dilation_rate, name=name
)
if use_bias:
bias = flow.get_variable(
name + "-bias",
shape=(filters,),
dtype=input.dtype,
initializer=bias_initializer,
)
output = flow.nn.bias_add(output, bias, data_format)
if activation is not None:
if activation == "Relu":
output = flow.math.relu(output)
else:
raise NotImplementedError
return output
def alexnet(images, labels):
conv1 = _conv2d_layer(
"conv1", images, filters=64, kernel_size=11, strides=4, padding="VALID"
)
pool1 = flow.nn.avg_pool2d(conv1, 3, 2, "VALID", "NCHW", name="pool1")
conv2 = _conv2d_layer("conv2", pool1, filters=192, kernel_size=5)
pool2 = flow.nn.avg_pool2d(conv2, 3, 2, "VALID", "NCHW", name="pool2")
conv3 = _conv2d_layer("conv3", pool2, filters=384)
conv4 = _conv2d_layer("conv4", conv3, filters=384)
conv5 = _conv2d_layer("conv5", conv4, filters=256)
pool5 = flow.nn.avg_pool2d(conv5, 3, 2, "VALID", "NCHW", name="pool5")
if len(pool5.shape) > 2:
pool5 = flow.reshape(pool5, shape=(pool5.shape[0], -1))
fc1 = flow.layers.dense(
inputs=pool5,
units=4096,
activation=flow.math.relu,
use_bias=False,
kernel_initializer=flow.random_uniform_initializer(),
bias_initializer=False,
trainable=True,
name="fc1",
)
dropout1 = flow.nn.dropout(fc1, rate=0.5)
fc2 = flow.layers.dense(
inputs=dropout1,
units=4096,
activation=flow.math.relu,
use_bias=False,
kernel_initializer=flow.random_uniform_initializer(),
bias_initializer=False,
trainable=True,
name="fc2",
)
dropout2 = flow.nn.dropout(fc2, rate=0.5)
fc3 = flow.layers.dense(
inputs=dropout2,
units=1001,
activation=None,
use_bias=False,
kernel_initializer=flow.random_uniform_initializer(),
bias_initializer=False,
trainable=True,
name="fc3",
)
# loss function
loss = flow.nn.sparse_softmax_cross_entropy_with_logits(
labels, fc3, name="softmax_loss"
)
return loss
# train job
@flow.global_function
def alexnet_train_job():
# set hyper parameter
flow.config.train.primary_lr(0.00001)
flow.config.train.model_update_conf(dict(naive_conf={}))
# load data
(labels, images) = _data_load_layer(args.train_dir)
# construct network
loss = alexnet(images, labels)
# set loss
flow.losses.add_loss(loss)
return loss
# inference job
@flow.global_function
def alexnet_eval_job():
# load data
(labels, images) = _data_load_layer(args.eval_dir)
# construct inference network
loss = alexnet(images, labels)
return loss
def main():
# set running mode
flow.config.gpu_device_num(args.gpu_num_per_node)
flow.config.ctrl_port(9788)
flow.config.default_data_type(flow.float)
# set multi nodes mode port
if args.multinode:
flow.config.ctrl_port(12138)
nodes = []
for n in args.node_list.strip().split(","):
addr_dict = {}
addr_dict["addr"] = n
nodes.append(addr_dict)
flow.config.machine(nodes)
# load/initialize model
check_point = flow.train.CheckPoint()
if not args.model_load_dir:
check_point.init()
else:
check_point.load(args.model_load_dir)
# training iter
print("{:>12} {:>12} {:>12}".format("iter", "loss type", "loss value"))
for i in range(args.iter_num):
fmt_str = "{:>12} {:>12} {:>12.10f}"
# print training log
train_loss = alexnet_train_job().get().mean()
print(fmt_str.format(i, "train loss:", train_loss))
# print inference log
if (i + 1) % 10 == 0:
eval_loss = alexnet_eval_job().get().mean()
print(fmt_str.format(i, "eval loss:", eval_loss))
# save model
if (i + 1) % 100 == 0:
check_point.save(args.model_save_dir + str(i))
if __name__ == "__main__":
main()
| [
"oneflow.image.crop_mirror_normalize",
"oneflow.config.train.primary_lr",
"oneflow.math.relu",
"oneflow.get_variable",
"oneflow.data.ofrecord_image_decoder",
"oneflow.random_uniform_initializer",
"oneflow.nn.bias_add",
"oneflow.reshape",
"oneflow.config.default_data_type",
"oneflow.image.resize",
"oneflow.nn.sparse_softmax_cross_entropy_with_logits",
"oneflow.losses.add_loss",
"oneflow.config.machine",
"oneflow.nn.avg_pool2d",
"oneflow.train.CheckPoint",
"oneflow.config.ctrl_port",
"oneflow.config.gpu_device_num",
"oneflow.nn.conv2d",
"oneflow.nn.dropout",
"oneflow.data.ofrecord_raw_decoder",
"oneflow.data.ofrecord_reader"
] | [((1131, 1203), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""flags for multi-node and resource"""'}), "(description='flags for multi-node and resource')\n", (1154, 1203), False, 'import argparse\n'), ((2025, 2112), 'oneflow.data.ofrecord_reader', 'flow.data.ofrecord_reader', (['data_dir'], {'batch_size': '(12)', 'data_part_num': '(8)', 'name': '"""decode"""'}), "(data_dir, batch_size=12, data_part_num=8, name=\n 'decode')\n", (2050, 2112), True, 'import oneflow as flow\n'), ((2135, 2207), 'oneflow.data.ofrecord_image_decoder', 'flow.data.ofrecord_image_decoder', (['ofrecord', '"""encoded"""'], {'color_space': '"""RGB"""'}), "(ofrecord, 'encoded', color_space='RGB')\n", (2167, 2207), True, 'import oneflow as flow\n'), ((2220, 2308), 'oneflow.data.ofrecord_raw_decoder', 'flow.data.ofrecord_raw_decoder', (['ofrecord', '"""class/label"""'], {'shape': '()', 'dtype': 'flow.int32'}), "(ofrecord, 'class/label', shape=(), dtype=\n flow.int32)\n", (2250, 2308), True, 'import oneflow as flow\n'), ((2328, 2399), 'oneflow.image.resize', 'flow.image.resize', (['image'], {'resize_x': '(227)', 'resize_y': '(227)', 'color_space': '"""RGB"""'}), "(image, resize_x=227, resize_y=227, color_space='RGB')\n", (2345, 2399), True, 'import oneflow as flow\n'), ((2413, 2536), 'oneflow.image.crop_mirror_normalize', 'flow.image.crop_mirror_normalize', (['rsz'], {'color_space': '"""RGB"""', 'output_layout': '"""NCHW"""', 'mean': 'rgb_mean', 'output_dtype': 'flow.float'}), "(rsz, color_space='RGB', output_layout=\n 'NCHW', mean=rgb_mean, output_dtype=flow.float)\n", (2445, 2536), True, 'import oneflow as flow\n'), ((2824, 2857), 'oneflow.random_uniform_initializer', 'flow.random_uniform_initializer', ([], {}), '()\n', (2855, 2857), True, 'import oneflow as flow\n'), ((2973, 3083), 'oneflow.get_variable', 'flow.get_variable', (["(name + '-weight')"], {'shape': 'weight_shape', 'dtype': 'input.dtype', 'initializer': 'weight_initializer'}), "(name + '-weight', shape=weight_shape, dtype=input.dtype,\n initializer=weight_initializer)\n", (2990, 3083), True, 'import oneflow as flow\n'), ((3132, 3222), 'oneflow.nn.conv2d', 'flow.nn.conv2d', (['input', 'weight', 'strides', 'padding', 'data_format', 'dilation_rate'], {'name': 'name'}), '(input, weight, strides, padding, data_format, dilation_rate,\n name=name)\n', (3146, 3222), True, 'import oneflow as flow\n'), ((3823, 3885), 'oneflow.nn.avg_pool2d', 'flow.nn.avg_pool2d', (['conv1', '(3)', '(2)', '"""VALID"""', '"""NCHW"""'], {'name': '"""pool1"""'}), "(conv1, 3, 2, 'VALID', 'NCHW', name='pool1')\n", (3841, 3885), True, 'import oneflow as flow\n'), ((3970, 4032), 'oneflow.nn.avg_pool2d', 'flow.nn.avg_pool2d', (['conv2', '(3)', '(2)', '"""VALID"""', '"""NCHW"""'], {'name': '"""pool2"""'}), "(conv2, 3, 2, 'VALID', 'NCHW', name='pool2')\n", (3988, 4032), True, 'import oneflow as flow\n'), ((4214, 4276), 'oneflow.nn.avg_pool2d', 'flow.nn.avg_pool2d', (['conv5', '(3)', '(2)', '"""VALID"""', '"""NCHW"""'], {'name': '"""pool5"""'}), "(conv5, 3, 2, 'VALID', 'NCHW', name='pool5')\n", (4232, 4276), True, 'import oneflow as flow\n'), ((4662, 4692), 'oneflow.nn.dropout', 'flow.nn.dropout', (['fc1'], {'rate': '(0.5)'}), '(fc1, rate=0.5)\n', (4677, 4692), True, 'import oneflow as flow\n'), ((4987, 5017), 'oneflow.nn.dropout', 'flow.nn.dropout', (['fc2'], {'rate': '(0.5)'}), '(fc2, rate=0.5)\n', (5002, 5017), True, 'import oneflow as flow\n'), ((5318, 5405), 'oneflow.nn.sparse_softmax_cross_entropy_with_logits', 'flow.nn.sparse_softmax_cross_entropy_with_logits', (['labels', 'fc3'], {'name': '"""softmax_loss"""'}), "(labels, fc3, name=\n 'softmax_loss')\n", (5366, 5405), True, 'import oneflow as flow\n'), ((5523, 5558), 'oneflow.config.train.primary_lr', 'flow.config.train.primary_lr', (['(1e-05)'], {}), '(1e-05)\n', (5551, 5558), True, 'import oneflow as flow\n'), ((5775, 5801), 'oneflow.losses.add_loss', 'flow.losses.add_loss', (['loss'], {}), '(loss)\n', (5795, 5801), True, 'import oneflow as flow\n'), ((6082, 6131), 'oneflow.config.gpu_device_num', 'flow.config.gpu_device_num', (['args.gpu_num_per_node'], {}), '(args.gpu_num_per_node)\n', (6108, 6131), True, 'import oneflow as flow\n'), ((6136, 6163), 'oneflow.config.ctrl_port', 'flow.config.ctrl_port', (['(9788)'], {}), '(9788)\n', (6157, 6163), True, 'import oneflow as flow\n'), ((6168, 6209), 'oneflow.config.default_data_type', 'flow.config.default_data_type', (['flow.float'], {}), '(flow.float)\n', (6197, 6209), True, 'import oneflow as flow\n'), ((6553, 6576), 'oneflow.train.CheckPoint', 'flow.train.CheckPoint', ([], {}), '()\n', (6574, 6576), True, 'import oneflow as flow\n'), ((3265, 3369), 'oneflow.get_variable', 'flow.get_variable', (["(name + '-bias')"], {'shape': '(filters,)', 'dtype': 'input.dtype', 'initializer': 'bias_initializer'}), "(name + '-bias', shape=(filters,), dtype=input.dtype,\n initializer=bias_initializer)\n", (3282, 3369), True, 'import oneflow as flow\n'), ((3442, 3485), 'oneflow.nn.bias_add', 'flow.nn.bias_add', (['output', 'bias', 'data_format'], {}), '(output, bias, data_format)\n', (3458, 3485), True, 'import oneflow as flow\n'), ((4323, 4370), 'oneflow.reshape', 'flow.reshape', (['pool5'], {'shape': '(pool5.shape[0], -1)'}), '(pool5, shape=(pool5.shape[0], -1))\n', (4335, 4370), True, 'import oneflow as flow\n'), ((6274, 6302), 'oneflow.config.ctrl_port', 'flow.config.ctrl_port', (['(12138)'], {}), '(12138)\n', (6295, 6302), True, 'import oneflow as flow\n'), ((6479, 6505), 'oneflow.config.machine', 'flow.config.machine', (['nodes'], {}), '(nodes)\n', (6498, 6505), True, 'import oneflow as flow\n'), ((3572, 3594), 'oneflow.math.relu', 'flow.math.relu', (['output'], {}), '(output)\n', (3586, 3594), True, 'import oneflow as flow\n'), ((4529, 4562), 'oneflow.random_uniform_initializer', 'flow.random_uniform_initializer', ([], {}), '()\n', (4560, 4562), True, 'import oneflow as flow\n'), ((4854, 4887), 'oneflow.random_uniform_initializer', 'flow.random_uniform_initializer', ([], {}), '()\n', (4885, 4887), True, 'import oneflow as flow\n'), ((5169, 5202), 'oneflow.random_uniform_initializer', 'flow.random_uniform_initializer', ([], {}), '()\n', (5200, 5202), 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 os
import math
import argparse
from datetime import datetime
import config as configs
from config import str2bool
import oneflow as flow
from squad import SQuAD
from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig
from squad_util import RawResult, gen_eval_predict_json
parser = configs.get_parser()
parser.add_argument('--num_epochs', type=int, default=3, help='number of epochs')
parser.add_argument("--train_data_dir", type=str, default=None)
parser.add_argument("--train_example_num", type=int, default=88614,
help="example number in dataset")
parser.add_argument("--batch_size_per_device", type=int, default=32)
parser.add_argument("--train_data_part_num", type=int, default=1,
help="data part number in dataset")
parser.add_argument("--eval_data_dir", type=str, default=None)
parser.add_argument("--eval_example_num", type=int, default=10833,
help="example number in dataset")
parser.add_argument("--eval_batch_size_per_device", type=int, default=64)
parser.add_argument("--eval_data_part_num", type=int, default=1,
help="data part number in dataset")
# post eval
parser.add_argument("--output_dir", type=str, default='squad_output', help='folder for output file')
parser.add_argument("--doc_stride", type=int, default=128)
parser.add_argument("--max_seq_length", type=int, default=384)
parser.add_argument("--max_query_length", type=int, default=64)
parser.add_argument("--vocab_file", type=str,
help="The vocabulary file that the BERT model was trained on.")
parser.add_argument("--predict_file", type=str,
help="SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json")
parser.add_argument("--n_best_size", type=int, default=20,
help="The total number of n-best predictions to generate in the nbest_predictions.json output file.")
parser.add_argument("--max_answer_length", type=int, default=30,
help="The maximum length of an answer that can be generated. This is needed \
because the start and end predictions are not conditioned on one another.")
parser.add_argument("--verbose_logging", type=str2bool, default='False',
help="If true, all of the warnings related to data processing will be printed. \
A number of warnings are expected for a normal SQuAD evaluation.")
parser.add_argument("--version_2_with_negative", type=str2bool, default='False',
help="If true, the SQuAD examples contain some that do not have an answer.")
parser.add_argument("--null_score_diff_threshold", type=float, default=0.0,
help="If null_score - best_non_null is greater than the threshold predict null.")
args = parser.parse_args()
batch_size = args.num_nodes * args.gpu_num_per_node * args.batch_size_per_device
eval_batch_size = args.num_nodes * args.gpu_num_per_node * args.eval_batch_size_per_device
epoch_size = math.ceil(args.train_example_num / batch_size)
num_eval_steps = math.ceil(args.eval_example_num / eval_batch_size)
args.iter_num = epoch_size * args.num_epochs
args.predict_batch_size = eval_batch_size
configs.print_args(args)
def SquadDecoder(data_dir, batch_size, data_part_num, seq_length, is_train=True):
with flow.scope.placement("cpu", "0:0"):
ofrecord = flow.data.ofrecord_reader(data_dir,
batch_size=batch_size,
data_part_num=data_part_num,
random_shuffle = is_train,
shuffle_after_epoch=is_train)
blob_confs = {}
def _blob_conf(name, shape, dtype=flow.int32):
blob_confs[name] = flow.data.OFRecordRawDecoder(ofrecord, name, shape=shape, dtype=dtype)
_blob_conf("input_ids", [seq_length])
_blob_conf("input_mask", [seq_length])
_blob_conf("segment_ids", [seq_length])
if is_train:
_blob_conf("start_positions", [1])
_blob_conf("end_positions", [1])
else:
_blob_conf("unique_ids", [1])
return blob_confs
if args.do_train:
@flow.global_function(type='train', function_config=GetFunctionConfig(args))
def SquadFinetuneJob():
hidden_size = 64 * args.num_attention_heads # , H = 64, size per head
intermediate_size = hidden_size * 4
decoders = SquadDecoder(args.train_data_dir, batch_size, args.train_data_part_num, args.seq_length)
start_logits, end_logits = SQuAD(
decoders['input_ids'],
decoders['input_mask'],
decoders['segment_ids'],
args.vocab_size,
seq_length=args.seq_length,
hidden_size=hidden_size,
num_hidden_layers=args.num_hidden_layers,
num_attention_heads=args.num_attention_heads,
intermediate_size=intermediate_size,
hidden_act="gelu",
hidden_dropout_prob=args.hidden_dropout_prob,
attention_probs_dropout_prob=args.attention_probs_dropout_prob,
max_position_embeddings=args.max_position_embeddings,
type_vocab_size=args.type_vocab_size,
initializer_range=0.02,
)
def _ComputeLoss(logits, positions):
logits = flow.reshape(logits, [-1, args.seq_length])
probs = flow.nn.softmax(logits)
pre_example_loss = flow.nn.sparse_cross_entropy(labels=positions, prediction=probs)
return pre_example_loss
start_loss = _ComputeLoss(start_logits, decoders['start_positions'])
end_loss = _ComputeLoss(end_logits, decoders['end_positions'])
total_loss = 0.5*(start_loss + end_loss)
flow.losses.add_loss(total_loss)
opt = CreateOptimizer(args)
opt.minimize(total_loss)
return {'total_loss': total_loss}
if args.do_eval:
@flow.global_function(type='predict')
def SquadDevJob():
hidden_size = 64 * args.num_attention_heads # , H = 64, size per head
intermediate_size = hidden_size * 4
decoders = SquadDecoder(args.eval_data_dir, eval_batch_size, args.eval_data_part_num, args.seq_length,
is_train=False)
start_logits, end_logits = SQuAD(
decoders['input_ids'],
decoders['input_mask'],
decoders['segment_ids'],
args.vocab_size,
seq_length=args.seq_length,
hidden_size=hidden_size,
num_hidden_layers=args.num_hidden_layers,
num_attention_heads=args.num_attention_heads,
intermediate_size=intermediate_size,
hidden_act="gelu",
hidden_dropout_prob=args.hidden_dropout_prob,
attention_probs_dropout_prob=args.attention_probs_dropout_prob,
max_position_embeddings=args.max_position_embeddings,
type_vocab_size=args.type_vocab_size,
initializer_range=0.02,
)
return decoders['unique_ids'], start_logits, end_logits
def main():
flow.config.gpu_device_num(args.gpu_num_per_node)
flow.env.log_dir(args.log_dir)
InitNodes(args)
if args.do_train or args.do_eval:
snapshot = Snapshot(args.model_save_dir, args.model_load_dir)
if args.do_train:
summary = Summary(args.log_dir, args)
for epoch in range(args.num_epochs):
metric = Metric(desc='train', print_steps=args.loss_print_every_n_iter, summary=summary,
batch_size=batch_size, keys=['total_loss'])
for step in range(epoch_size):
SquadFinetuneJob().async_get(metric.metric_cb(step, epoch=epoch))
if args.save_last_snapshot:
snapshot.save("last_snapshot")
if args.do_eval:
assert os.path.isdir(args.eval_data_dir)
all_results = []
for step in range(num_eval_steps):
unique_ids, start_positions, end_positions = SquadDevJob().get()
unique_ids = unique_ids.numpy()
start_positions = start_positions.numpy()
end_positions = end_positions.numpy()
for unique_id, start_position, end_position in zip(unique_ids, start_positions, end_positions):
all_results.append(RawResult(
unique_id = int(unique_id[0]),
start_logits = start_position.flatten().tolist(),
end_logits = end_position.flatten().tolist(),
))
if step % args.loss_print_every_n_iter == 0:
print("{}/{}, num of results:{}".format(step, num_eval_steps, len(all_results)))
print("last uid:", unique_id[0])
gen_eval_predict_json(args, all_results)
if __name__ == "__main__":
main()
| [
"oneflow.global_function",
"oneflow.data.OFRecordRawDecoder",
"oneflow.nn.sparse_cross_entropy",
"oneflow.reshape",
"oneflow.nn.softmax",
"oneflow.env.log_dir",
"oneflow.losses.add_loss",
"oneflow.scope.placement",
"oneflow.config.gpu_device_num",
"oneflow.data.ofrecord_reader"
] | [((917, 937), 'config.get_parser', 'configs.get_parser', ([], {}), '()\n', (935, 937), True, 'import config as configs\n'), ((3513, 3559), 'math.ceil', 'math.ceil', (['(args.train_example_num / batch_size)'], {}), '(args.train_example_num / batch_size)\n', (3522, 3559), False, 'import math\n'), ((3577, 3627), 'math.ceil', 'math.ceil', (['(args.eval_example_num / eval_batch_size)'], {}), '(args.eval_example_num / eval_batch_size)\n', (3586, 3627), False, 'import math\n'), ((3715, 3739), 'config.print_args', 'configs.print_args', (['args'], {}), '(args)\n', (3733, 3739), True, 'import config as configs\n'), ((6522, 6558), 'oneflow.global_function', 'flow.global_function', ([], {'type': '"""predict"""'}), "(type='predict')\n", (6542, 6558), True, 'import oneflow as flow\n'), ((7705, 7754), 'oneflow.config.gpu_device_num', 'flow.config.gpu_device_num', (['args.gpu_num_per_node'], {}), '(args.gpu_num_per_node)\n', (7731, 7754), True, 'import oneflow as flow\n'), ((7759, 7789), 'oneflow.env.log_dir', 'flow.env.log_dir', (['args.log_dir'], {}), '(args.log_dir)\n', (7775, 7789), True, 'import oneflow as flow\n'), ((7795, 7810), 'util.InitNodes', 'InitNodes', (['args'], {}), '(args)\n', (7804, 7810), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig\n'), ((3832, 3866), 'oneflow.scope.placement', 'flow.scope.placement', (['"""cpu"""', '"""0:0"""'], {}), "('cpu', '0:0')\n", (3852, 3866), True, 'import oneflow as flow\n'), ((3887, 4034), 'oneflow.data.ofrecord_reader', 'flow.data.ofrecord_reader', (['data_dir'], {'batch_size': 'batch_size', 'data_part_num': 'data_part_num', 'random_shuffle': 'is_train', 'shuffle_after_epoch': 'is_train'}), '(data_dir, batch_size=batch_size, data_part_num=\n data_part_num, random_shuffle=is_train, shuffle_after_epoch=is_train)\n', (3912, 4034), True, 'import oneflow as flow\n'), ((5136, 5685), 'squad.SQuAD', 'SQuAD', (["decoders['input_ids']", "decoders['input_mask']", "decoders['segment_ids']", 'args.vocab_size'], {'seq_length': 'args.seq_length', 'hidden_size': 'hidden_size', 'num_hidden_layers': 'args.num_hidden_layers', 'num_attention_heads': 'args.num_attention_heads', 'intermediate_size': 'intermediate_size', 'hidden_act': '"""gelu"""', 'hidden_dropout_prob': 'args.hidden_dropout_prob', 'attention_probs_dropout_prob': 'args.attention_probs_dropout_prob', 'max_position_embeddings': 'args.max_position_embeddings', 'type_vocab_size': 'args.type_vocab_size', 'initializer_range': '(0.02)'}), "(decoders['input_ids'], decoders['input_mask'], decoders['segment_ids'\n ], args.vocab_size, seq_length=args.seq_length, hidden_size=hidden_size,\n num_hidden_layers=args.num_hidden_layers, num_attention_heads=args.\n num_attention_heads, intermediate_size=intermediate_size, hidden_act=\n 'gelu', hidden_dropout_prob=args.hidden_dropout_prob,\n attention_probs_dropout_prob=args.attention_probs_dropout_prob,\n max_position_embeddings=args.max_position_embeddings, type_vocab_size=\n args.type_vocab_size, initializer_range=0.02)\n", (5141, 5685), False, 'from squad import SQuAD\n'), ((6351, 6383), 'oneflow.losses.add_loss', 'flow.losses.add_loss', (['total_loss'], {}), '(total_loss)\n', (6371, 6383), True, 'import oneflow as flow\n'), ((6398, 6419), 'util.CreateOptimizer', 'CreateOptimizer', (['args'], {}), '(args)\n', (6413, 6419), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig\n'), ((6909, 7458), 'squad.SQuAD', 'SQuAD', (["decoders['input_ids']", "decoders['input_mask']", "decoders['segment_ids']", 'args.vocab_size'], {'seq_length': 'args.seq_length', 'hidden_size': 'hidden_size', 'num_hidden_layers': 'args.num_hidden_layers', 'num_attention_heads': 'args.num_attention_heads', 'intermediate_size': 'intermediate_size', 'hidden_act': '"""gelu"""', 'hidden_dropout_prob': 'args.hidden_dropout_prob', 'attention_probs_dropout_prob': 'args.attention_probs_dropout_prob', 'max_position_embeddings': 'args.max_position_embeddings', 'type_vocab_size': 'args.type_vocab_size', 'initializer_range': '(0.02)'}), "(decoders['input_ids'], decoders['input_mask'], decoders['segment_ids'\n ], args.vocab_size, seq_length=args.seq_length, hidden_size=hidden_size,\n num_hidden_layers=args.num_hidden_layers, num_attention_heads=args.\n num_attention_heads, intermediate_size=intermediate_size, hidden_act=\n 'gelu', hidden_dropout_prob=args.hidden_dropout_prob,\n attention_probs_dropout_prob=args.attention_probs_dropout_prob,\n max_position_embeddings=args.max_position_embeddings, type_vocab_size=\n args.type_vocab_size, initializer_range=0.02)\n", (6914, 7458), False, 'from squad import SQuAD\n'), ((7869, 7919), 'util.Snapshot', 'Snapshot', (['args.model_save_dir', 'args.model_load_dir'], {}), '(args.model_save_dir, args.model_load_dir)\n', (7877, 7919), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig\n'), ((7961, 7988), 'util.Summary', 'Summary', (['args.log_dir', 'args'], {}), '(args.log_dir, args)\n', (7968, 7988), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig\n'), ((8455, 8488), 'os.path.isdir', 'os.path.isdir', (['args.eval_data_dir'], {}), '(args.eval_data_dir)\n', (8468, 8488), False, 'import os\n'), ((9376, 9416), 'squad_util.gen_eval_predict_json', 'gen_eval_predict_json', (['args', 'all_results'], {}), '(args, all_results)\n', (9397, 9416), False, 'from squad_util import RawResult, gen_eval_predict_json\n'), ((4322, 4392), 'oneflow.data.OFRecordRawDecoder', 'flow.data.OFRecordRawDecoder', (['ofrecord', 'name'], {'shape': 'shape', 'dtype': 'dtype'}), '(ofrecord, name, shape=shape, dtype=dtype)\n', (4350, 4392), True, 'import oneflow as flow\n'), ((5916, 5959), 'oneflow.reshape', 'flow.reshape', (['logits', '[-1, args.seq_length]'], {}), '(logits, [-1, args.seq_length])\n', (5928, 5959), True, 'import oneflow as flow\n'), ((5980, 6003), 'oneflow.nn.softmax', 'flow.nn.softmax', (['logits'], {}), '(logits)\n', (5995, 6003), True, 'import oneflow as flow\n'), ((6035, 6099), 'oneflow.nn.sparse_cross_entropy', 'flow.nn.sparse_cross_entropy', ([], {'labels': 'positions', 'prediction': 'probs'}), '(labels=positions, prediction=probs)\n', (6063, 6099), True, 'import oneflow as flow\n'), ((4807, 4830), 'util.GetFunctionConfig', 'GetFunctionConfig', (['args'], {}), '(args)\n', (4824, 4830), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig\n'), ((8055, 8183), 'util.Metric', 'Metric', ([], {'desc': '"""train"""', 'print_steps': 'args.loss_print_every_n_iter', 'summary': 'summary', 'batch_size': 'batch_size', 'keys': "['total_loss']"}), "(desc='train', print_steps=args.loss_print_every_n_iter, summary=\n summary, batch_size=batch_size, keys=['total_loss'])\n", (8061, 8183), False, 'from util import Snapshot, Summary, InitNodes, Metric, CreateOptimizer, GetFunctionConfig\n')] |
import oneflow as flow
import oneflow.nn as nn
import sys, os
sys.path.append(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
)
from vgg.models.vgg import vgg19_bn, vgg16_bn, vgg19, vgg16
model_dict = {
"vgg16": vgg16,
"vgg19": vgg19,
"vgg16_bn": vgg16_bn,
"vgg19_bn": vgg19_bn,
}
class GeneratorLoss(nn.Module):
def __init__(self, path):
super(GeneratorLoss, self).__init__()
vgg = model_dict["vgg16"]()
loss_network = nn.Sequential(*list(vgg.features)[:31]).eval()
for param in loss_network.parameters():
param.requires_grad = False
pretrain_models = flow.load(path)
loss_network.load_state_dict(
{
k.replace("features.", ""): v
for k, v in pretrain_models.items()
if "features" in k
}
)
loss_network.to("cuda")
self.loss_network = loss_network
self.mse_loss = nn.MSELoss()
self.tv_loss = TVLoss()
def forward(self, out_labels, out_images, target_images):
# Adversarial Loss
adversarial_loss = flow.mean(1 - out_labels)
# Perception Loss
perception_loss = self.mse_loss(
self.loss_network(out_images), self.loss_network(target_images)
)
# Image Loss
image_loss = self.mse_loss(out_images, target_images)
# TV Loss
tv_loss = self.tv_loss(out_images)
return (
image_loss
+ 0.001 * adversarial_loss
+ 0.006 * perception_loss
+ 2e-8 * tv_loss
)
class TVLoss(nn.Module):
def __init__(self, tv_loss_weight=1):
super(TVLoss, self).__init__()
self.tv_loss_weight = tv_loss_weight
def forward(self, x):
batch_size = x.size()[0]
h_x = x.size()[2]
w_x = x.size()[3]
count_h = self.tensor_size(x[:, :, 1:, :])
count_w = self.tensor_size(x[:, :, :, 1:])
h_tv = flow.pow((x[:, :, 1:, :] - x[:, :, : h_x - 1, :]), 2).sum()
w_tv = flow.pow((x[:, :, :, 1:] - x[:, :, :, : w_x - 1]), 2).sum()
return self.tv_loss_weight * 2 * (h_tv / count_h + w_tv / count_w) / batch_size
@staticmethod
def tensor_size(t):
return t.size()[1] * t.size()[2] * t.size()[3]
class BCELoss(nn.Module):
def __init__(self, reduction: str = "mean", reduce=True) -> None:
super().__init__()
if reduce is not None and not reduce:
raise ValueError("Argument reduce is not supported yet")
assert reduction in [
"none",
"mean",
"sum",
None,
], "only 'sum', 'mean' and 'none' supported by now"
self.reduction = reduction
def forward(self, input, target, weight=None):
assert (
input.shape == target.shape
), "The Input shape must be the same as Target shape"
_cross_entropy_loss = flow.negative(
target * flow.log(input) + (1 - target) * flow.log(1 - input)
)
if weight is not None:
assert (
weight.shape == input.shape
), "The weight shape must be the same as Input shape"
_weighted_loss = weight * _cross_entropy_loss
else:
_weighted_loss = _cross_entropy_loss
if self.reduction == "mean":
return flow.mean(_weighted_loss)
elif self.reduction == "sum":
return flow.sum(_weighted_loss)
else:
return _weighted_loss
| [
"oneflow.mean",
"oneflow.sum",
"oneflow.load",
"oneflow.log",
"oneflow.nn.MSELoss",
"oneflow.pow"
] | [((664, 679), 'oneflow.load', 'flow.load', (['path'], {}), '(path)\n', (673, 679), True, 'import oneflow as flow\n'), ((986, 998), 'oneflow.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (996, 998), True, 'import oneflow.nn as nn\n'), ((1148, 1173), 'oneflow.mean', 'flow.mean', (['(1 - out_labels)'], {}), '(1 - out_labels)\n', (1157, 1173), True, 'import oneflow as flow\n'), ((3415, 3440), 'oneflow.mean', 'flow.mean', (['_weighted_loss'], {}), '(_weighted_loss)\n', (3424, 3440), True, 'import oneflow as flow\n'), ((132, 158), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (148, 158), False, 'import sys, os\n'), ((2009, 2059), 'oneflow.pow', 'flow.pow', (['(x[:, :, 1:, :] - x[:, :, :h_x - 1, :])', '(2)'], {}), '(x[:, :, 1:, :] - x[:, :, :h_x - 1, :], 2)\n', (2017, 2059), True, 'import oneflow as flow\n'), ((2084, 2134), 'oneflow.pow', 'flow.pow', (['(x[:, :, :, 1:] - x[:, :, :, :w_x - 1])', '(2)'], {}), '(x[:, :, :, 1:] - x[:, :, :, :w_x - 1], 2)\n', (2092, 2134), True, 'import oneflow as flow\n'), ((3498, 3522), 'oneflow.sum', 'flow.sum', (['_weighted_loss'], {}), '(_weighted_loss)\n', (3506, 3522), True, 'import oneflow as flow\n'), ((3011, 3026), 'oneflow.log', 'flow.log', (['input'], {}), '(input)\n', (3019, 3026), True, 'import oneflow as flow\n'), ((3044, 3063), 'oneflow.log', 'flow.log', (['(1 - input)'], {}), '(1 - input)\n', (3052, 3063), True, 'import oneflow as flow\n')] |
# import tensorflow as tf
import oneflow as flow
import numpy as np
class JointsMSELoss(object):
def __init__(self):
super(JointsMSELoss, self).__init__()
def call(self, y_pred, target, target_weight):
batch_size = y_pred.shape[0]
num_of_joints = y_pred.shape[-1]
pred = flow.reshape(x=y_pred, shape=(batch_size, -1, num_of_joints))
heatmap_pred_list = []
for i in range(num_of_joints):
tensor = flow.slice(pred, begin=[None, None, i*1], size=[None, None, 1])
heatmap_pred_list.append(tensor)
gt = flow.reshape(x=target, shape=(batch_size, -1, num_of_joints))
heatmap_gt_list = []
for i in range(num_of_joints):
tensor = flow.slice(gt, begin=[None, None, i*1], size=[None, None, 1])
heatmap_gt_list.append(tensor)
loss = 0.0
for i in range(num_of_joints):
heatmap_pred = flow.squeeze(heatmap_pred_list[i])
heatmap_gt = flow.squeeze(heatmap_gt_list[i])
y_true = heatmap_pred * flow.reshape(flow.slice(target_weight, begin=[None,i*1, None], size=[None,1,None]),[batch_size,1])
y_pred = heatmap_gt * flow.reshape(flow.slice(target_weight, begin=[None,i*1, None], size=[None,1,None]),[batch_size,1])
loss += 0.5 * flow.nn.MSELoss(y_true, y_pred, reduction="mean")
return loss / num_of_joints
| [
"oneflow.nn.MSELoss",
"oneflow.reshape",
"oneflow.slice",
"oneflow.squeeze"
] | [((314, 375), 'oneflow.reshape', 'flow.reshape', ([], {'x': 'y_pred', 'shape': '(batch_size, -1, num_of_joints)'}), '(x=y_pred, shape=(batch_size, -1, num_of_joints))\n', (326, 375), True, 'import oneflow as flow\n'), ((596, 657), 'oneflow.reshape', 'flow.reshape', ([], {'x': 'target', 'shape': '(batch_size, -1, num_of_joints)'}), '(x=target, shape=(batch_size, -1, num_of_joints))\n', (608, 657), True, 'import oneflow as flow\n'), ((466, 531), 'oneflow.slice', 'flow.slice', (['pred'], {'begin': '[None, None, i * 1]', 'size': '[None, None, 1]'}), '(pred, begin=[None, None, i * 1], size=[None, None, 1])\n', (476, 531), True, 'import oneflow as flow\n'), ((746, 809), 'oneflow.slice', 'flow.slice', (['gt'], {'begin': '[None, None, i * 1]', 'size': '[None, None, 1]'}), '(gt, begin=[None, None, i * 1], size=[None, None, 1])\n', (756, 809), True, 'import oneflow as flow\n'), ((935, 969), 'oneflow.squeeze', 'flow.squeeze', (['heatmap_pred_list[i]'], {}), '(heatmap_pred_list[i])\n', (947, 969), True, 'import oneflow as flow\n'), ((995, 1027), 'oneflow.squeeze', 'flow.squeeze', (['heatmap_gt_list[i]'], {}), '(heatmap_gt_list[i])\n', (1007, 1027), True, 'import oneflow as flow\n'), ((1325, 1374), 'oneflow.nn.MSELoss', 'flow.nn.MSELoss', (['y_true', 'y_pred'], {'reduction': '"""mean"""'}), "(y_true, y_pred, reduction='mean')\n", (1340, 1374), True, 'import oneflow as flow\n'), ((1078, 1152), 'oneflow.slice', 'flow.slice', (['target_weight'], {'begin': '[None, i * 1, None]', 'size': '[None, 1, None]'}), '(target_weight, begin=[None, i * 1, None], size=[None, 1, None])\n', (1088, 1152), True, 'import oneflow as flow\n'), ((1212, 1286), 'oneflow.slice', 'flow.slice', (['target_weight'], {'begin': '[None, i * 1, None]', 'size': '[None, 1, None]'}), '(target_weight, begin=[None, i * 1, None], size=[None, 1, None])\n', (1222, 1286), 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 random
import os
import struct
import cv2
import numpy as np
import oneflow.core.record.record_pb2 as record_pb
class OFRecordDataset(object):
def __init__(
self,
data_dir,
num_data_parts,
part_name_suffix_length,
batch_size,
shuffle_data_part,
):
self.data_dir_ = data_dir
self.num_data_parts_ = num_data_parts
self.part_name_suffix_length_ = part_name_suffix_length
self.batch_size_ = batch_size
self.epoch_cnt_ = 0
self.cur_data_part_idx_ = 0
self.shuffle_data_part_ = shuffle_data_part
self.reader_ = None
self.num_read_batchs_ = 0
@property
def batch_size(self):
return self.batch_size_
@batch_size.setter
def batch_size(self, bs):
self.batch_size_ = bs
@property
def num_read_batchs(self):
return self.num_read_batchs_
def __del__(self):
if self.reader_ is not None:
self.reader_.close()
def __iter__(self):
self._gen_data_part_seq()
self._open_data_part_file()
while True:
yield self._read_one_batch()
def load_batchs(self, num_batchs):
image_list = []
label_list = []
for i, (image_array, label_array) in enumerate(self):
if i >= num_batchs:
break
image_list.append(image_array)
label_list.append(label_array)
return image_list, label_list
def parse_record(self, record):
raise NotImplementedError
def collate(self, batch):
raise NotImplementedError
def reset(self):
self.epoch_cnt_ = 0
self.cur_data_part_idx_ = 0
if self.reader_ is not None:
self.reader_.close()
self.num_read_batchs_ = 0
def _move_to_next_data_part(self):
self.cur_data_part_idx_ += 1
if self.cur_data_part_idx_ >= len(self.data_part_seq_):
self.epoch_cnt_ += 1
self._gen_data_part_seq()
self._open_data_part_file()
def _gen_data_part_seq(self):
data_part_name_pattern = (
r"part-{:0" + str(self.part_name_suffix_length_) + r"d}"
)
self.data_part_seq_ = [
data_part_name_pattern.format(i) for i in range(self.num_data_parts_)
]
if self.shuffle_data_part_:
random.shuffle(self.data_part_seq_)
def _open_data_part_file(self):
if self.reader_ is not None:
self.reader_.close()
data_part_file_path = os.path.join(
self.data_dir_, self.data_part_seq_[self.cur_data_part_idx_]
)
self.reader_ = open(data_part_file_path, "rb")
def _read_one_batch(self):
assert self.reader_ is not None
batch = []
for i in range(self.batch_size_):
record_head = self.reader_.read(8)
if record_head is None or len(record_head) != 8:
self._move_to_next_data_part()
break
record = record_pb.OFRecord()
record_byte_size = struct.unpack("q", record_head)[0]
record.ParseFromString(self.reader_.read(record_byte_size))
batch.append(self.parse_record(record))
self.num_read_batchs_ += 1
return self.collate(batch)
class ImageNetRecordDataset(OFRecordDataset):
def __init__(
self,
data_dir="/dataset/ImageNet/ofrecord/validation",
num_data_parts=256,
part_name_suffix_length=5,
batch_size=4,
shuffle_data_part=False,
image_resize_size=224,
data_format="NCHW",
):
super().__init__(
data_dir,
num_data_parts,
part_name_suffix_length,
batch_size,
shuffle_data_part,
)
self.image_resize_size_ = image_resize_size
self.data_format_ = data_format
def parse_record(self, record):
image_raw_bytes = record.feature["encoded"].bytes_list.value[0]
image = cv2.imdecode(
np.frombuffer(image_raw_bytes, np.uint8), cv2.IMREAD_COLOR
).astype(np.float32)
image = self.preprocess_image(image)
label = record.feature["class/label"].int32_list.value[0]
return (image, label)
def collate(self, batch):
batched_image = np.stack([data[0] for data in batch], axis=0)
batched_label = np.array([data[1] for data in batch], dtype=np.int32)
return batched_image, batched_label
def preprocess_image(self, image):
# resize
image = cv2.resize(image, (self.image_resize_size_, self.image_resize_size_))
# bgr to rgb (opencv decoded image is bgr format)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# normalize
norm_rgb_mean = np.array([123.68, 116.779, 103.939], dtype=np.float32)
norm_rgb_std = np.array([58.393, 57.12, 57.375], dtype=np.float32)
image = (image - norm_rgb_mean) / norm_rgb_std
# NHWC to NCHW
if self.data_format_ == "NCHW":
assert image.shape[2] == 3
image = np.transpose(image, (2, 0, 1))
elif self.data_format_ == "NHWC":
assert image.shape[2] == 3
else:
raise ValueError("Unsupported image data format")
return np.ascontiguousarray(image)
class FaceEmoreRecordDataset(OFRecordDataset):
def __init__(
self,
data_dir="/dataset/insightface/train_ofrecord/faces_emore",
num_data_parts=256,
part_name_suffix_length=1,
batch_size=4,
shuffle_data_part=False,
image_width=112,
image_height=112,
color_space="RGB",
data_format="NCHW",
):
super().__init__(
data_dir,
num_data_parts,
part_name_suffix_length,
batch_size,
shuffle_data_part,
)
self.image_width_ = image_width
self.image_height_ = image_height
self.color_space_ = color_space
self.data_format_ = data_format
def parse_record(self, record):
image_raw_bytes = record.feature["encoded"].bytes_list.value[0]
image = cv2.imdecode(
np.frombuffer(image_raw_bytes, np.uint8), cv2.IMREAD_COLOR
).astype(np.float32)
image = self.preprocess_image(image)
issame = record.feature["issame"].int32_list.value[0]
return (image, issame)
def preprocess_image(self, image):
# resize
image = cv2.resize(image, (self.image_height_, self.image_width_))
# bgr to rgb (opencv decoded image is bgr format)
if self.color_space_ == "RGB":
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# NHWC to NCHW
if self.data_format_ == "NCHW":
assert image.shape[2] == 3
image = np.transpose(image, (2, 0, 1))
elif self.data_format_ == "NHWC":
assert image.shape[2] == 3
else:
raise ValueError("Unsupported image data format")
return image
def collate(self, batch):
image = np.stack([data[0] for data in batch], axis=0)
issame = np.array([data[1] for data in batch], dtype=np.int32)
return image, issame
| [
"oneflow.core.record.record_pb2.OFRecord"
] | [((3155, 3229), 'os.path.join', 'os.path.join', (['self.data_dir_', 'self.data_part_seq_[self.cur_data_part_idx_]'], {}), '(self.data_dir_, self.data_part_seq_[self.cur_data_part_idx_])\n', (3167, 3229), False, 'import os\n'), ((4949, 4994), 'numpy.stack', 'np.stack', (['[data[0] for data in batch]'], {'axis': '(0)'}), '([data[0] for data in batch], axis=0)\n', (4957, 4994), True, 'import numpy as np\n'), ((5019, 5072), 'numpy.array', 'np.array', (['[data[1] for data in batch]'], {'dtype': 'np.int32'}), '([data[1] for data in batch], dtype=np.int32)\n', (5027, 5072), True, 'import numpy as np\n'), ((5190, 5259), 'cv2.resize', 'cv2.resize', (['image', '(self.image_resize_size_, self.image_resize_size_)'], {}), '(image, (self.image_resize_size_, self.image_resize_size_))\n', (5200, 5259), False, 'import cv2\n'), ((5334, 5372), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (5346, 5372), False, 'import cv2\n'), ((5417, 5471), 'numpy.array', 'np.array', (['[123.68, 116.779, 103.939]'], {'dtype': 'np.float32'}), '([123.68, 116.779, 103.939], dtype=np.float32)\n', (5425, 5471), True, 'import numpy as np\n'), ((5495, 5546), 'numpy.array', 'np.array', (['[58.393, 57.12, 57.375]'], {'dtype': 'np.float32'}), '([58.393, 57.12, 57.375], dtype=np.float32)\n', (5503, 5546), True, 'import numpy as np\n'), ((5928, 5955), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['image'], {}), '(image)\n', (5948, 5955), True, 'import numpy as np\n'), ((7126, 7184), 'cv2.resize', 'cv2.resize', (['image', '(self.image_height_, self.image_width_)'], {}), '(image, (self.image_height_, self.image_width_))\n', (7136, 7184), False, 'import cv2\n'), ((7719, 7764), 'numpy.stack', 'np.stack', (['[data[0] for data in batch]'], {'axis': '(0)'}), '([data[0] for data in batch], axis=0)\n', (7727, 7764), True, 'import numpy as np\n'), ((7782, 7835), 'numpy.array', 'np.array', (['[data[1] for data in batch]'], {'dtype': 'np.int32'}), '([data[1] for data in batch], dtype=np.int32)\n', (7790, 7835), True, 'import numpy as np\n'), ((2981, 3016), 'random.shuffle', 'random.shuffle', (['self.data_part_seq_'], {}), '(self.data_part_seq_)\n', (2995, 3016), False, 'import random\n'), ((3640, 3660), 'oneflow.core.record.record_pb2.OFRecord', 'record_pb.OFRecord', ([], {}), '()\n', (3658, 3660), True, 'import oneflow.core.record.record_pb2 as record_pb\n'), ((5724, 5754), 'numpy.transpose', 'np.transpose', (['image', '(2, 0, 1)'], {}), '(image, (2, 0, 1))\n', (5736, 5754), True, 'import numpy as np\n'), ((7302, 7340), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (7314, 7340), False, 'import cv2\n'), ((7463, 7493), 'numpy.transpose', 'np.transpose', (['image', '(2, 0, 1)'], {}), '(image, (2, 0, 1))\n', (7475, 7493), True, 'import numpy as np\n'), ((3692, 3723), 'struct.unpack', 'struct.unpack', (['"""q"""', 'record_head'], {}), "('q', record_head)\n", (3705, 3723), False, 'import struct\n'), ((4665, 4705), 'numpy.frombuffer', 'np.frombuffer', (['image_raw_bytes', 'np.uint8'], {}), '(image_raw_bytes, np.uint8)\n', (4678, 4705), True, 'import numpy as np\n'), ((6827, 6867), 'numpy.frombuffer', 'np.frombuffer', (['image_raw_bytes', 'np.uint8'], {}), '(image_raw_bytes, np.uint8)\n', (6840, 6867), True, 'import numpy as np\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 os
import sys
import unittest
import numpy as np
import oneflow as flow
import oneflow.unittest
rank = flow.env.get_rank()
def _graph_debug(test_case, v_level=0, ranks=None, max_py_stack_depth=2):
class DebugGraph(flow.nn.Graph):
def __init__(self):
super().__init__()
self.m = flow.nn.Linear(3, 3)
def build(self, x):
return x
d_g = DebugGraph()
d_g.debug(v_level, ranks=ranks, max_py_stack_depth=max_py_stack_depth)
if ranks is None:
rank_list = [0]
elif isinstance(ranks, int):
rank_list = [ranks]
elif isinstance(ranks, list):
rank_list = ranks
if (
-1 in rank_list or rank in rank_list
) and v_level >= 0: # v_level == -1 means debug mode is closed
test_case.assertTrue(d_g._debug)
test_case.assertTrue(d_g.m._debug)
print(f"ranks {ranks} rank {rank} debug is opened.")
else:
test_case.assertTrue(not d_g._debug)
test_case.assertTrue(not d_g.m._debug)
print(f"ranks {ranks} rank {rank} debug is closed.")
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
@flow.unittest.skip_unless_1n4d()
class TestGraphDebug(oneflow.unittest.TestCase):
def test_graph_debug_rank_null(test_case):
_graph_debug(test_case)
def test_graph_debug_rank_0(test_case):
_graph_debug(test_case, ranks=0)
def test_graph_debug_rank_1(test_case):
_graph_debug(test_case, ranks=1)
def test_graph_debug_rank_1_and_2(test_case):
_graph_debug(test_case, ranks=[1, 2])
def test_graph_debug_rank_all(test_case):
_graph_debug(test_case, ranks=-1)
def test_graph_debug_mode_closed(test_case):
_graph_debug(test_case, v_level=-1)
def test_graph_debug_mode_opened(test_case):
_graph_debug(test_case, v_level=0)
def test_graph_debug_max_py_stack_depth_2(test_case):
_graph_debug(test_case, max_py_stack_depth=2)
def test_graph_debug_max_py_stack_depth_8(test_case):
_graph_debug(test_case, max_py_stack_depth=8)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.nn.Linear",
"oneflow.env.get_rank",
"oneflow.unittest.skip_unless_1n4d"
] | [((703, 722), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (720, 722), True, 'import oneflow as flow\n'), ((1764, 1796), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (1794, 1796), True, 'import oneflow as flow\n'), ((1704, 1738), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (1713, 1738), False, 'import os\n'), ((2729, 2744), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2742, 2744), False, 'import unittest\n'), ((916, 936), 'oneflow.nn.Linear', 'flow.nn.Linear', (['(3)', '(3)'], {}), '(3, 3)\n', (930, 936), True, 'import oneflow as flow\n')] |
import os
import shutil
import sys
from time import time
import oneflow as flow
import oneflow.nn as nn
import flowvision
MODEL_ROOT = os.path.join(os.getcwd(), "repos")
CONFIG_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.pbtxt")
DEVICE = "cuda:0"
class MyGraph(nn.Graph):
def __init__(self, model):
super().__init__()
self.model = model
def build(self, *input):
return self.model(*input)
def export_models(model_names, image):
for model_name in model_names:
try:
model = getattr(flowvision.models, model_name)()
model.to(DEVICE)
model.eval()
graph = MyGraph(model)
# start ticking
out = model(image)
s = out.shape
t0 = time()
out = model(image)
s = out.shape
t1 = time()
out = graph(image)
s = out.shape
t2 = time()
out = graph(image)
s = out.shape
t3 = time()
print(model_name, "Model forward time: ", t1 - t0,
"Graph compile time: ", t2 - t1,
"Graph forward time: ", t3 - t2)
model_dir = os.path.join(MODEL_ROOT, model_name + "_repo", model_name, "1", "model")
config_dest = os.path.join(MODEL_ROOT, model_name + "_repo", model_name, "config.pbtxt")
os.makedirs(model_dir, exist_ok=True)
shutil.copyfile(CONFIG_FILE, config_dest)
flow.save(graph, model_dir)
except Exception as e:
print(model_name, " cannot forward or convert to graph: ", e)
if __name__ == "__main__":
if len(sys.argv) != 2:
print('usage: python3 models.py "model_names"')
exit()
model_names = sys.argv[1].split()
image = flow.randn(1, 3, 224, 224).to(DEVICE)
export_models(model_names, image)
| [
"oneflow.save",
"oneflow.randn"
] | [((150, 161), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (159, 161), False, 'import os\n'), ((215, 241), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (231, 241), False, 'import os\n'), ((804, 810), 'time.time', 'time', ([], {}), '()\n', (808, 810), False, 'from time import time\n'), ((885, 891), 'time.time', 'time', ([], {}), '()\n', (889, 891), False, 'from time import time\n'), ((966, 972), 'time.time', 'time', ([], {}), '()\n', (970, 972), False, 'from time import time\n'), ((1047, 1053), 'time.time', 'time', ([], {}), '()\n', (1051, 1053), False, 'from time import time\n'), ((1268, 1340), 'os.path.join', 'os.path.join', (['MODEL_ROOT', "(model_name + '_repo')", 'model_name', '"""1"""', '"""model"""'], {}), "(MODEL_ROOT, model_name + '_repo', model_name, '1', 'model')\n", (1280, 1340), False, 'import os\n'), ((1367, 1441), 'os.path.join', 'os.path.join', (['MODEL_ROOT', "(model_name + '_repo')", 'model_name', '"""config.pbtxt"""'], {}), "(MODEL_ROOT, model_name + '_repo', model_name, 'config.pbtxt')\n", (1379, 1441), False, 'import os\n'), ((1454, 1491), 'os.makedirs', 'os.makedirs', (['model_dir'], {'exist_ok': '(True)'}), '(model_dir, exist_ok=True)\n', (1465, 1491), False, 'import os\n'), ((1504, 1545), 'shutil.copyfile', 'shutil.copyfile', (['CONFIG_FILE', 'config_dest'], {}), '(CONFIG_FILE, config_dest)\n', (1519, 1545), False, 'import shutil\n'), ((1558, 1585), 'oneflow.save', 'flow.save', (['graph', 'model_dir'], {}), '(graph, model_dir)\n', (1567, 1585), True, 'import oneflow as flow\n'), ((1868, 1894), 'oneflow.randn', 'flow.randn', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (1878, 1894), 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 inspect
import typing # This unused import is needed
from typing import Dict, Optional, Tuple, Any, Union
import random as random_util
import os
import oneflow.experimental as flow
import torch
import numpy as np
rng = np.random.default_rng()
default_generators = {}
def data_generator(annotation):
def register_data_generator(func):
default_generators[annotation] = func
return func
return register_data_generator
@data_generator(bool)
def _random_bool():
val = random_util.choice([True, False])
return val, val
@data_generator(torch.Tensor)
def _random_tensor():
return random_tensor()(None)
def random_tensor(ndim=None, dim0=1, dim1=None, dim2=None, dim3=None, dim4=None):
assert ndim is None or 1 <= ndim <= 5
if ndim is None:
ndim = rng.integers(low=1, high=6)
shape = rng.integers(low=1, high=8, size=ndim)
if dim0 is not None:
shape[0] = dim0
if ndim >= 2 and dim1 is not None:
shape[1] = dim1
if ndim >= 3 and dim2 is not None:
shape[2] = dim2
if ndim >= 4 and dim3 is not None:
shape[3] = dim3
if ndim == 5 and dim4 is not None:
shape[4] = dim4
def generator(_):
np_arr = rng.random(shape)
return flow.Tensor(np_arr), torch.Tensor(np_arr)
return generator
def choose(x):
def generator(_):
val = random_util.choice(x)
return val, val
return generator
def random(low, high):
def generator(annotation):
if hasattr(annotation, "__origin__"):
# PyTorch _size_2_t and similar types are defined by type variables,
# leading to unexpected __args__ and __origin__
#
# _size_2_t = Union[T, Tuple[T, T]][int]
# _size_2_t.__origin__
# >> typing.Union[~T, typing.Tuple[~T, ~T]]
#
# So recreate a new annotation object by repr and eval
#
# _size_2_t
# >> typing.Union[int, typing.Tuple[int, int]]
# _size_2_t_new = eval(repr(annotation))
# _size_2_t_new.__origin__
# >> typing.Union
annotation = eval(repr(annotation))
if annotation.__origin__ is Union:
x = random_util.choice(annotation.__args__)
return generator(x)
if annotation.__origin__ is Tuple:
t = [generator(x) for x in annotation.__args__]
return zip(*t)
else:
raise NotImplementedError(
f"Not implemented annotation {annotation} in random, type(annotation.__origin__) is {type(annotation.__origin__)}"
)
if annotation == int:
val = int(rng.integers(low, high))
elif annotation == float:
val = float(rng.random() * (high - low) + low)
else:
raise NotImplementedError(
f"Not implemented annotation {annotation} in random"
)
return val, val
return generator
def constant(val):
def generator(_):
return val, val
return generator
def test_module_against_pytorch(
test_case,
module_class_name,
extra_annotations: Optional[Dict[str, Any]] = None,
extra_generators: Optional[Dict[str, Any]] = None,
device: str = "cuda",
training: bool = True,
backward: bool = True,
rtol=1e-4,
atol=1e-5,
n=20,
pytorch_module_class_name=None,
):
assert device in ["cuda", "cpu"]
if not training:
assert not backward
if extra_annotations is None:
extra_annotations = {}
if extra_generators is None:
extra_generators = {}
if pytorch_module_class_name is None:
pytorch_module_class_name = module_class_name
verbose = os.getenv("ONEFLOW_TEST_VERBOSE") is not None
torch_module_class = eval(f"torch.{pytorch_module_class_name}")
spec = inspect.getfullargspec(torch_module_class)
annotations = spec.annotations
annotations.update(extra_annotations)
if "return" in annotations:
del annotations["return"]
args = (set(spec.args) | set(spec.kwonlyargs)) - {"self"}
assert args == set(
annotations.keys()
), f"args = {args}, annotations = {annotations.keys()}"
annotations.update({"input": torch.Tensor})
def has_default(name):
if name in spec.args:
return (len(spec.args) - spec.args.index(name)) <= len(spec.defaults)
else:
assert name in spec.kwonlyargs
return (len(spec.kwonlyargs) - spec.kwonlyargs.index(name)) <= len(
spec.kwonlydefaults
)
def generate(name):
annotation = annotations[name]
if name in extra_generators:
return extra_generators[name](annotation)
return default_generators[annotation]()
while n > 0:
flow_attr_dict = {}
torch_attr_dict = {}
for name in args:
if has_default(name):
if rng.random() < 1 / 3:
continue
flow_data, torch_data = generate(name)
flow_attr_dict[name] = flow_data
torch_attr_dict[name] = torch_data
if verbose:
print(f"attr = {torch_attr_dict}, device = {device}")
flow_input_original, torch_input_original = generate("input")
flow_input_original.requires_grad_(backward)
torch_input_original.requires_grad_(backward)
flow_input, torch_input = (
flow_input_original.to(device),
torch_input_original.to(device),
)
try:
torch_module = torch_module_class(**torch_attr_dict)
torch_module = torch_module.to(device)
torch_module.train(training)
torch_res = torch_module(torch_input)
loss = torch_res.sum()
loss.backward()
state_dict = torch_module.state_dict()
state_dict = {k: v.detach().cpu().numpy() for k, v in state_dict.items()}
except Exception as e:
if verbose:
print(f"PyTorch error: {e}")
# The random generated test data is not always valid,
# so just skip when PyTorch raises an exception
continue
flow_module_class = eval(f"flow.{module_class_name}")
flow_module = flow_module_class(**flow_attr_dict)
flow_module = flow_module.to(device)
flow_module.train(training)
flow_module.load_state_dict(state_dict)
flow_res = flow_module(flow_input)
loss = flow_res.sum()
loss.backward()
def allclose_or_fail(flow_tensor, torch_tensor):
is_allclose = np.allclose(
flow_tensor.numpy(),
torch_tensor.detach().cpu().numpy(),
rtol=rtol,
atol=atol,
)
test_case.assertTrue(
is_allclose,
f"flow_tensor = {flow_tensor},\ntorch_tensor = {torch_tensor},\nattr_dict = {torch_attr_dict}",
)
allclose_or_fail(flow_res, torch_res)
allclose_or_fail(flow_input_original.grad, torch_input_original.grad)
flow_parameters = dict(flow_module.named_parameters())
for name, torch_param in torch_module.named_parameters():
flow_param = flow_parameters[name]
allclose_or_fail(flow_param.grad, torch_param.grad)
n -= 1
__all__ = [
"random_tensor",
"random",
"choose",
"constant",
"test_module_against_pytorch",
]
| [
"oneflow.experimental.Tensor"
] | [((820, 843), 'numpy.random.default_rng', 'np.random.default_rng', ([], {}), '()\n', (841, 843), True, 'import numpy as np\n'), ((1098, 1131), 'random.choice', 'random_util.choice', (['[True, False]'], {}), '([True, False])\n', (1116, 1131), True, 'import random as random_util\n'), ((4522, 4564), 'inspect.getfullargspec', 'inspect.getfullargspec', (['torch_module_class'], {}), '(torch_module_class)\n', (4544, 4564), False, 'import inspect\n'), ((1971, 1992), 'random.choice', 'random_util.choice', (['x'], {}), '(x)\n', (1989, 1992), True, 'import random as random_util\n'), ((4396, 4429), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_VERBOSE"""'], {}), "('ONEFLOW_TEST_VERBOSE')\n", (4405, 4429), False, 'import os\n'), ((1854, 1873), 'oneflow.experimental.Tensor', 'flow.Tensor', (['np_arr'], {}), '(np_arr)\n', (1865, 1873), True, 'import oneflow.experimental as flow\n'), ((1875, 1895), 'torch.Tensor', 'torch.Tensor', (['np_arr'], {}), '(np_arr)\n', (1887, 1895), False, 'import torch\n'), ((2855, 2894), 'random.choice', 'random_util.choice', (['annotation.__args__'], {}), '(annotation.__args__)\n', (2873, 2894), True, 'import random as random_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.
"""
import unittest
import os
import numpy as np
from oneflow.compatible import single_client as flow
from oneflow.compatible.single_client import typing as oft
from collections import OrderedDict
from test_util import GenArgList
import test_global_storage
from test_util import type_name_to_flow_type
from test_util import type_name_to_np_type
def compare_with_np(device_type, label_type, num_classes, num_sample, batch_size):
assert device_type in ["gpu", "cpu"]
flow.clear_default_session()
if device_type == "cpu":
flow.config.gpu_device_num(0)
flow.config.cpu_device_num(4)
else:
flow.config.gpu_device_num(4)
func_config = flow.FunctionConfig()
func_config.default_data_type(flow.float)
func_config.indexed_slices_optimizer_conf(dict(include_op_names=dict(op_name=[])))
@flow.global_function(type="train", function_config=func_config)
def PartialFcJob(
labels: oft.Numpy.Placeholder(
(batch_size,), dtype=type_name_to_flow_type[label_type]
)
):
with flow.scope.placement(device_type, "0:0"):
x = flow.get_variable(
"x-weight",
shape=(num_classes, 128),
dtype=flow.float,
initializer=flow.random_uniform_initializer(minval=-10, maxval=10),
trainable=True,
)
with flow.scope.placement(device_type, "0:0-3"):
lebels_distribute = flow.distribute.broadcast()
weight_distribute = flow.distribute.split(0)
(
maped_label,
sampled_label,
sampled_weight,
) = flow.distributed_partial_fc_sample(
weight=x.with_distribute(weight_distribute),
label=labels.with_distribute(lebels_distribute),
num_sample=num_sample,
)
with flow.scope.placement(device_type, "0:0"):
sampled_weight = flow.identity(sampled_weight)
loss = flow.math.square(sampled_weight)
flow.optimizer.SGD(
flow.optimizer.PiecewiseConstantScheduler([], [1e-4]), momentum=0
).minimize(loss)
flow.watch(x, test_global_storage.Setter("x"))
flow.watch_diff(x, test_global_storage.Setter("x_diff"))
flow.watch_diff(
sampled_weight, test_global_storage.Setter("sampled_weight_diff")
)
return x, maped_label, sampled_label, sampled_weight
# fake labels
labels = np.random.randint(0, num_classes, size=(batch_size,)).astype(
type_name_to_np_type[label_type]
)
# OneFlow
weight, maped_label, sampled_label, sampled_weight = PartialFcJob(labels).get()
gpu_num = 4
device_class_num = num_classes // gpu_num
device_num_sample = num_sample // gpu_num
global_sample_labels_list = []
np_mapped_label = []
label_map = {}
for i in range(gpu_num):
lower = i * device_class_num
upper = (i + 1) * device_class_num
condition = (labels >= lower) & (labels < upper)
local_label = labels[condition]
local_label = np.unique(local_label).astype(np.int32)
idx_start = int(i * device_num_sample)
idx_end = int((i + 1) * device_num_sample)
local_sample_labels = sampled_label[idx_start:idx_end]
global_sample_labels = local_sample_labels
global_sample_labels_list.append(global_sample_labels)
assert (
np.all((local_sample_labels >= lower) & (local_sample_labels < upper))
== True
)
assert len(local_sample_labels) == len(np.unique(local_sample_labels))
assert (
np.array_equal(local_label, global_sample_labels[0 : len(local_label)])
== True
)
for j in range(len(global_sample_labels)):
label_map[global_sample_labels[j]] = j + idx_start
for i in range(len(labels)):
np_mapped_label.append(label_map[labels[i]])
assert np.array_equal(np.array(np_mapped_label), maped_label.numpy()) == True
global_sample_label = np.array(global_sample_labels_list).flatten().astype(np.int32)
np_sample_weight = weight[global_sample_label]
assert np.array_equal(sampled_weight.numpy(), np_sample_weight) == True
sampled_weight_diff = test_global_storage.Get("sampled_weight_diff")
np_weight_diff = np.zeros(weight.shape)
for i in range(len(global_sample_label)):
np_weight_diff[global_sample_label[i]] = sampled_weight_diff[i]
x_diff = test_global_storage.Get("x_diff")
assert np.array_equal(test_global_storage.Get("x_diff"), np_weight_diff) == True
flow.clear_default_session()
@flow.unittest.skip_unless_1n4d()
class TestPartialFc(flow.unittest.TestCase):
def test_partial_fc1(test_case):
arg_dict = OrderedDict()
arg_dict["device_type"] = ["gpu"]
arg_dict["label_type"] = ["int32"]
arg_dict["num_classes"] = [85744]
arg_dict["num_sample"] = [8600]
arg_dict["batch_size"] = [512]
for arg in GenArgList(arg_dict):
compare_with_np(*arg)
def test_partial_fc2(test_case):
arg_dict = OrderedDict()
arg_dict["device_type"] = ["gpu"]
arg_dict["label_type"] = ["int32"]
arg_dict["num_classes"] = [200]
arg_dict["num_sample"] = [64]
arg_dict["batch_size"] = [32]
for arg in GenArgList(arg_dict):
compare_with_np(*arg)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.compatible.single_client.clear_default_session",
"oneflow.compatible.single_client.random_uniform_initializer",
"oneflow.compatible.single_client.identity",
"oneflow.compatible.single_client.unittest.skip_unless_1n4d",
"oneflow.compatible.single_client.FunctionConfig",
"oneflow.compatible.single_client.optimizer.PiecewiseConstantScheduler",
"oneflow.compatible.single_client.distribute.broadcast",
"oneflow.compatible.single_client.typing.Numpy.Placeholder",
"oneflow.compatible.single_client.config.cpu_device_num",
"oneflow.compatible.single_client.math.square",
"oneflow.compatible.single_client.config.gpu_device_num",
"oneflow.compatible.single_client.scope.placement",
"oneflow.compatible.single_client.distribute.split",
"oneflow.compatible.single_client.global_function"
] | [((5278, 5306), 'oneflow.compatible.single_client.clear_default_session', 'flow.clear_default_session', ([], {}), '()\n', (5304, 5306), True, 'from oneflow.compatible import single_client as flow\n'), ((5310, 5342), 'oneflow.compatible.single_client.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (5340, 5342), True, 'from oneflow.compatible import single_client as flow\n'), ((1062, 1090), 'oneflow.compatible.single_client.clear_default_session', 'flow.clear_default_session', ([], {}), '()\n', (1088, 1090), True, 'from oneflow.compatible import single_client as flow\n'), ((1262, 1283), 'oneflow.compatible.single_client.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (1281, 1283), True, 'from oneflow.compatible import single_client as flow\n'), ((1423, 1486), 'oneflow.compatible.single_client.global_function', 'flow.global_function', ([], {'type': '"""train"""', 'function_config': 'func_config'}), "(type='train', function_config=func_config)\n", (1443, 1486), True, 'from oneflow.compatible import single_client as flow\n'), ((4932, 4978), 'test_global_storage.Get', 'test_global_storage.Get', (['"""sampled_weight_diff"""'], {}), "('sampled_weight_diff')\n", (4955, 4978), False, 'import test_global_storage\n'), ((5001, 5023), 'numpy.zeros', 'np.zeros', (['weight.shape'], {}), '(weight.shape)\n', (5009, 5023), True, 'import numpy as np\n'), ((5156, 5189), 'test_global_storage.Get', 'test_global_storage.Get', (['"""x_diff"""'], {}), "('x_diff')\n", (5179, 5189), False, 'import test_global_storage\n'), ((6119, 6134), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6132, 6134), False, 'import unittest\n'), ((1128, 1157), 'oneflow.compatible.single_client.config.gpu_device_num', 'flow.config.gpu_device_num', (['(0)'], {}), '(0)\n', (1154, 1157), True, 'from oneflow.compatible import single_client as flow\n'), ((1166, 1195), 'oneflow.compatible.single_client.config.cpu_device_num', 'flow.config.cpu_device_num', (['(4)'], {}), '(4)\n', (1192, 1195), True, 'from oneflow.compatible import single_client as flow\n'), ((1214, 1243), 'oneflow.compatible.single_client.config.gpu_device_num', 'flow.config.gpu_device_num', (['(4)'], {}), '(4)\n', (1240, 1243), True, 'from oneflow.compatible import single_client as flow\n'), ((5444, 5457), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (5455, 5457), False, 'from collections import OrderedDict\n'), ((5683, 5703), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (5693, 5703), False, 'from test_util import GenArgList\n'), ((5796, 5809), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (5807, 5809), False, 'from collections import OrderedDict\n'), ((6030, 6050), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (6040, 6050), False, 'from test_util import GenArgList\n'), ((1525, 1603), 'oneflow.compatible.single_client.typing.Numpy.Placeholder', 'oft.Numpy.Placeholder', (['(batch_size,)'], {'dtype': 'type_name_to_flow_type[label_type]'}), '((batch_size,), dtype=type_name_to_flow_type[label_type])\n', (1546, 1603), True, 'from oneflow.compatible.single_client import typing as oft\n'), ((1646, 1686), 'oneflow.compatible.single_client.scope.placement', 'flow.scope.placement', (['device_type', '"""0:0"""'], {}), "(device_type, '0:0')\n", (1666, 1686), True, 'from oneflow.compatible import single_client as flow\n'), ((1970, 2012), 'oneflow.compatible.single_client.scope.placement', 'flow.scope.placement', (['device_type', '"""0:0-3"""'], {}), "(device_type, '0:0-3')\n", (1990, 2012), True, 'from oneflow.compatible import single_client as flow\n'), ((2046, 2073), 'oneflow.compatible.single_client.distribute.broadcast', 'flow.distribute.broadcast', ([], {}), '()\n', (2071, 2073), True, 'from oneflow.compatible import single_client as flow\n'), ((2106, 2130), 'oneflow.compatible.single_client.distribute.split', 'flow.distribute.split', (['(0)'], {}), '(0)\n', (2127, 2130), True, 'from oneflow.compatible import single_client as flow\n'), ((2481, 2521), 'oneflow.compatible.single_client.scope.placement', 'flow.scope.placement', (['device_type', '"""0:0"""'], {}), "(device_type, '0:0')\n", (2501, 2521), True, 'from oneflow.compatible import single_client as flow\n'), ((2552, 2581), 'oneflow.compatible.single_client.identity', 'flow.identity', (['sampled_weight'], {}), '(sampled_weight)\n', (2565, 2581), True, 'from oneflow.compatible import single_client as flow\n'), ((2601, 2633), 'oneflow.compatible.single_client.math.square', 'flow.math.square', (['sampled_weight'], {}), '(sampled_weight)\n', (2617, 2633), True, 'from oneflow.compatible import single_client as flow\n'), ((3124, 3177), 'numpy.random.randint', 'np.random.randint', (['(0)', 'num_classes'], {'size': '(batch_size,)'}), '(0, num_classes, size=(batch_size,))\n', (3141, 3177), True, 'import numpy as np\n'), ((4094, 4164), 'numpy.all', 'np.all', (['((local_sample_labels >= lower) & (local_sample_labels < upper))'], {}), '((local_sample_labels >= lower) & (local_sample_labels < upper))\n', (4100, 4164), True, 'import numpy as np\n'), ((4632, 4657), 'numpy.array', 'np.array', (['np_mapped_label'], {}), '(np_mapped_label)\n', (4640, 4657), True, 'import numpy as np\n'), ((5217, 5250), 'test_global_storage.Get', 'test_global_storage.Get', (['"""x_diff"""'], {}), "('x_diff')\n", (5240, 5250), False, 'import test_global_storage\n'), ((2804, 2835), 'test_global_storage.Setter', 'test_global_storage.Setter', (['"""x"""'], {}), "('x')\n", (2830, 2835), False, 'import test_global_storage\n'), ((2868, 2904), 'test_global_storage.Setter', 'test_global_storage.Setter', (['"""x_diff"""'], {}), "('x_diff')\n", (2894, 2904), False, 'import test_global_storage\n'), ((2967, 3016), 'test_global_storage.Setter', 'test_global_storage.Setter', (['"""sampled_weight_diff"""'], {}), "('sampled_weight_diff')\n", (2993, 3016), False, 'import test_global_storage\n'), ((3748, 3770), 'numpy.unique', 'np.unique', (['local_label'], {}), '(local_label)\n', (3757, 3770), True, 'import numpy as np\n'), ((4242, 4272), 'numpy.unique', 'np.unique', (['local_sample_labels'], {}), '(local_sample_labels)\n', (4251, 4272), True, 'import numpy as np\n'), ((1855, 1909), 'oneflow.compatible.single_client.random_uniform_initializer', 'flow.random_uniform_initializer', ([], {'minval': '(-10)', 'maxval': '(10)'}), '(minval=-10, maxval=10)\n', (1886, 1909), True, 'from oneflow.compatible import single_client as flow\n'), ((4715, 4750), 'numpy.array', 'np.array', (['global_sample_labels_list'], {}), '(global_sample_labels_list)\n', (4723, 4750), True, 'import numpy as np\n'), ((2682, 2737), 'oneflow.compatible.single_client.optimizer.PiecewiseConstantScheduler', 'flow.optimizer.PiecewiseConstantScheduler', (['[]', '[0.0001]'], {}), '([], [0.0001])\n', (2723, 2737), True, 'from oneflow.compatible import single_client as flow\n')] |
import oneflow as flow
def multi_scale_discriminator(input, trainable=True):
num_d = 2
get_intermediate_featuers = True
results = []
for i in range(num_d):
with flow.scope.namespace('multi_scale_discriminator'+str(i)):
out = n_layer_discriminator(input, trainable=trainable)
if not get_intermediate_featuers:
out = [out]
results.append(out)
input = flow.nn.avg_pool2d(input, ksize=3, strides=2, padding='SAME')
return results
def n_layer_discriminator(input, trainable=True):
init = flow.xavier_uniform_initializer()
reg = flow.regularizers
nf = 64
n_layer_d = 4
get_intermediate_featuers = True
results = [input]
out = flow.layers.conv2d(input, nf, kernel_size=4, strides=2, padding='SAME', trainable=trainable, name='D_n_1', kernel_initializer=init)
out = flow.nn.leaky_relu(out, 2e-1)
results.append(out)
nf = min(nf * 2, 512)
out = flow.layers.conv2d(out, nf, kernel_size=4, strides=2, padding='SAME', trainable=trainable, name='D_n_2', kernel_initializer=init)
out = flow.nn.InstanceNorm2d(out, name='D_n_I_1', affine=False)
out = flow.nn.leaky_relu(out, 2e-1)
results.append(out)
nf = min(nf * 2, 512)
out = flow.layers.conv2d(out, nf, kernel_size=4, strides=2, padding='SAME', trainable=trainable, name='D_n_3', kernel_initializer=init)
out = flow.nn.InstanceNorm2d(out, name='D_n_I_2', affine=False)
out = flow.nn.leaky_relu(out, 2e-1)
results.append(out)
nf = min(nf * 2, 512)
out = flow.layers.conv2d(out, nf, kernel_size=4, strides=1, padding='SAME', trainable=trainable, name='D_n_4', kernel_initializer=init)
out = flow.nn.InstanceNorm2d(out, name='D_n_I_3', affine=False)
out = flow.nn.leaky_relu(out, 2e-1)
results.append(out)
out = flow.layers.conv2d(out, 1, kernel_size=4, strides=1, padding='SAME', trainable=trainable, name='D_n_5', kernel_initializer=init)
results.append(out)
if get_intermediate_featuers:
return results[1:]
else:
return results[-1] | [
"oneflow.xavier_uniform_initializer",
"oneflow.layers.conv2d",
"oneflow.nn.leaky_relu",
"oneflow.nn.InstanceNorm2d",
"oneflow.nn.avg_pool2d"
] | [((585, 618), 'oneflow.xavier_uniform_initializer', 'flow.xavier_uniform_initializer', ([], {}), '()\n', (616, 618), True, 'import oneflow as flow\n'), ((747, 882), 'oneflow.layers.conv2d', 'flow.layers.conv2d', (['input', 'nf'], {'kernel_size': '(4)', 'strides': '(2)', 'padding': '"""SAME"""', 'trainable': 'trainable', 'name': '"""D_n_1"""', 'kernel_initializer': 'init'}), "(input, nf, kernel_size=4, strides=2, padding='SAME',\n trainable=trainable, name='D_n_1', kernel_initializer=init)\n", (765, 882), True, 'import oneflow as flow\n'), ((889, 917), 'oneflow.nn.leaky_relu', 'flow.nn.leaky_relu', (['out', '(0.2)'], {}), '(out, 0.2)\n', (907, 917), True, 'import oneflow as flow\n'), ((980, 1113), 'oneflow.layers.conv2d', 'flow.layers.conv2d', (['out', 'nf'], {'kernel_size': '(4)', 'strides': '(2)', 'padding': '"""SAME"""', 'trainable': 'trainable', 'name': '"""D_n_2"""', 'kernel_initializer': 'init'}), "(out, nf, kernel_size=4, strides=2, padding='SAME',\n trainable=trainable, name='D_n_2', kernel_initializer=init)\n", (998, 1113), True, 'import oneflow as flow\n'), ((1120, 1177), 'oneflow.nn.InstanceNorm2d', 'flow.nn.InstanceNorm2d', (['out'], {'name': '"""D_n_I_1"""', 'affine': '(False)'}), "(out, name='D_n_I_1', affine=False)\n", (1142, 1177), True, 'import oneflow as flow\n'), ((1188, 1216), 'oneflow.nn.leaky_relu', 'flow.nn.leaky_relu', (['out', '(0.2)'], {}), '(out, 0.2)\n', (1206, 1216), True, 'import oneflow as flow\n'), ((1279, 1412), 'oneflow.layers.conv2d', 'flow.layers.conv2d', (['out', 'nf'], {'kernel_size': '(4)', 'strides': '(2)', 'padding': '"""SAME"""', 'trainable': 'trainable', 'name': '"""D_n_3"""', 'kernel_initializer': 'init'}), "(out, nf, kernel_size=4, strides=2, padding='SAME',\n trainable=trainable, name='D_n_3', kernel_initializer=init)\n", (1297, 1412), True, 'import oneflow as flow\n'), ((1419, 1476), 'oneflow.nn.InstanceNorm2d', 'flow.nn.InstanceNorm2d', (['out'], {'name': '"""D_n_I_2"""', 'affine': '(False)'}), "(out, name='D_n_I_2', affine=False)\n", (1441, 1476), True, 'import oneflow as flow\n'), ((1487, 1515), 'oneflow.nn.leaky_relu', 'flow.nn.leaky_relu', (['out', '(0.2)'], {}), '(out, 0.2)\n', (1505, 1515), True, 'import oneflow as flow\n'), ((1578, 1711), 'oneflow.layers.conv2d', 'flow.layers.conv2d', (['out', 'nf'], {'kernel_size': '(4)', 'strides': '(1)', 'padding': '"""SAME"""', 'trainable': 'trainable', 'name': '"""D_n_4"""', 'kernel_initializer': 'init'}), "(out, nf, kernel_size=4, strides=1, padding='SAME',\n trainable=trainable, name='D_n_4', kernel_initializer=init)\n", (1596, 1711), True, 'import oneflow as flow\n'), ((1718, 1775), 'oneflow.nn.InstanceNorm2d', 'flow.nn.InstanceNorm2d', (['out'], {'name': '"""D_n_I_3"""', 'affine': '(False)'}), "(out, name='D_n_I_3', affine=False)\n", (1740, 1775), True, 'import oneflow as flow\n'), ((1786, 1814), 'oneflow.nn.leaky_relu', 'flow.nn.leaky_relu', (['out', '(0.2)'], {}), '(out, 0.2)\n', (1804, 1814), True, 'import oneflow as flow\n'), ((1851, 1983), 'oneflow.layers.conv2d', 'flow.layers.conv2d', (['out', '(1)'], {'kernel_size': '(4)', 'strides': '(1)', 'padding': '"""SAME"""', 'trainable': 'trainable', 'name': '"""D_n_5"""', 'kernel_initializer': 'init'}), "(out, 1, kernel_size=4, strides=1, padding='SAME',\n trainable=trainable, name='D_n_5', kernel_initializer=init)\n", (1869, 1983), True, 'import oneflow as flow\n'), ((440, 501), 'oneflow.nn.avg_pool2d', 'flow.nn.avg_pool2d', (['input'], {'ksize': '(3)', 'strides': '(2)', 'padding': '"""SAME"""'}), "(input, ksize=3, strides=2, padding='SAME')\n", (458, 501), 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.to_consistent,
"""
to_consistent(input, placement=None, sbp=None, grad_sbp=None) -> Tensor
Cast a local tensor to consistent tensor or cast a
consistent tensor to another consistent tensor with
different sbp or placement
Args:
input (Tensor): the input tensor.
placement (flow.placement, optional): the desired placement of returned consistent tensor. Default: if None, the input tensor must be consistent one and use its own placement.
sbp (flow.sbp.sbp or tuple of flow.sbp.sbp, optional): the desired sbp descriptor of returned consistent tensor. Default: if None, the input tensor must be consistent one and use its own sbp.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> np_arr = np.array([0.5, 0.6, 0.7]).astype(np.float32)
>>> input = flow.Tensor(np_arr)
>>> placement = flow.placement("cpu", {0:range(1)})
>>> output_tensor = input.to_consistent(placement, [flow.sbp.split(0)])
>>> output_tensor.is_consistent
True
""",
)
add_docstr(
oneflow.to_local,
"""
to_local(input) -> Tensor
Returns the local tensor of a consistent tensor.
Args:
input (Tensor): the input tensor.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> np_arr = np.array([0.5, 0.6, 0.7]).astype(np.float32)
>>> input = flow.tensor(np_arr, dtype=flow.float32)
>>> placement = flow.placement("cpu", {0:range(1)})
>>> consistent_tensor = input.to_consistent(placement, [flow.sbp.split(0)])
>>> consistent_tensor.to_local()
tensor([0.5000, 0.6000, 0.7000], dtype=oneflow.float32)
""",
)
| [
"oneflow.framework.docstr.utils.add_docstr"
] | [((660, 1784), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.to_consistent', '"""\n to_consistent(input, placement=None, sbp=None, grad_sbp=None) -> Tensor\n\n Cast a local tensor to consistent tensor or cast a\n consistent tensor to another consistent tensor with\n different sbp or placement\n\n\n Args:\n input (Tensor): the input tensor.\n placement (flow.placement, optional): the desired placement of returned consistent tensor. Default: if None, the input tensor must be consistent one and use its own placement.\n sbp (flow.sbp.sbp or tuple of flow.sbp.sbp, optional): the desired sbp descriptor of returned consistent tensor. Default: if None, the input tensor must be consistent one and use its own sbp.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n >>> np_arr = np.array([0.5, 0.6, 0.7]).astype(np.float32)\n >>> input = flow.Tensor(np_arr)\n >>> placement = flow.placement("cpu", {0:range(1)})\n >>> output_tensor = input.to_consistent(placement, [flow.sbp.split(0)])\n >>> output_tensor.is_consistent\n True\n """'], {}), '(oneflow.to_consistent,\n """\n to_consistent(input, placement=None, sbp=None, grad_sbp=None) -> Tensor\n\n Cast a local tensor to consistent tensor or cast a\n consistent tensor to another consistent tensor with\n different sbp or placement\n\n\n Args:\n input (Tensor): the input tensor.\n placement (flow.placement, optional): the desired placement of returned consistent tensor. Default: if None, the input tensor must be consistent one and use its own placement.\n sbp (flow.sbp.sbp or tuple of flow.sbp.sbp, optional): the desired sbp descriptor of returned consistent tensor. Default: if None, the input tensor must be consistent one and use its own sbp.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n >>> np_arr = np.array([0.5, 0.6, 0.7]).astype(np.float32)\n >>> input = flow.Tensor(np_arr)\n >>> placement = flow.placement("cpu", {0:range(1)})\n >>> output_tensor = input.to_consistent(placement, [flow.sbp.split(0)])\n >>> output_tensor.is_consistent\n True\n """\n )\n', (670, 1784), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((1788, 2464), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.to_local', '"""\n to_local(input) -> Tensor\n\n Returns the local tensor of a consistent tensor.\n\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n >>> np_arr = np.array([0.5, 0.6, 0.7]).astype(np.float32)\n >>> input = flow.tensor(np_arr, dtype=flow.float32)\n >>> placement = flow.placement("cpu", {0:range(1)})\n >>> consistent_tensor = input.to_consistent(placement, [flow.sbp.split(0)])\n >>> consistent_tensor.to_local()\n tensor([0.5000, 0.6000, 0.7000], dtype=oneflow.float32)\n """'], {}), '(oneflow.to_local,\n """\n to_local(input) -> Tensor\n\n Returns the local tensor of a consistent tensor.\n\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n >>> np_arr = np.array([0.5, 0.6, 0.7]).astype(np.float32)\n >>> input = flow.tensor(np_arr, dtype=flow.float32)\n >>> placement = flow.placement("cpu", {0:range(1)})\n >>> consistent_tensor = input.to_consistent(placement, [flow.sbp.split(0)])\n >>> consistent_tensor.to_local()\n tensor([0.5000, 0.6000, 0.7000], dtype=oneflow.float32)\n """\n )\n', (1798, 2464), 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 unittest
from collections import OrderedDict
import numpy as np
import oneflow as flow
import os
import oneflow.unittest
from test_util import GenArgList
def _test_eager_boxing_with_non_overlapping_placement_p_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1]})
x = tensor.to_consistent(placement, flow.sbp.partial_sum)
new_placement = flow.placement(out_device, {0: [2, 3]})
y = x.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[6, 16], [9, 17], [7, 13], [12, 16],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[15, 27], [19, 5], [11, 9], [15, 4],], dtype=np.float32,),
)
)
def _test_eager_boxing_with_non_overlapping_placement_b_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1]})
x = tensor.to_consistent(placement, flow.sbp.broadcast)
new_placement = flow.placement(out_device, {0: [2, 3]})
y = x.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[4, 6], [6, 8], [3, 7], [6, 8],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[5, 20], [9, 0], [5, 0], [9, 0],], dtype=np.float32,),
)
)
def _test_eager_boxing_with_non_overlapping_placement_s0_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
new_placement = flow.placement(out_device, {0: [2, 3]})
y = x.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8],],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[
[5, 20],
[9, 0],
[5, 0],
[9, 0],
[10, 7],
[10, 5],
[6, 9],
[6, 4],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_non_overlapping_placement_s1_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [2, 3]})
z = y.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8],],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[5, 20],
[9, 0],
[5, 0],
[9, 0],
[10, 7],
[10, 5],
[6, 9],
[6, 4],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_non_overlapping_placement_s1_to_s0(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [2, 3]})
z = y.to_consistent(new_placement, flow.sbp.split(0))
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0],],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4],],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_non_overlapping_placement_s1_to_b(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [2, 3]})
z = y.to_consistent(new_placement, flow.sbp.broadcast)
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 5, 20],
[6, 8, 9, 0],
[3, 7, 5, 0],
[6, 8, 9, 0],
[2, 10, 10, 7],
[3, 9, 10, 5],
[4, 6, 6, 9],
[6, 8, 6, 4],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 5, 20],
[6, 8, 9, 0],
[3, 7, 5, 0],
[6, 8, 9, 0],
[2, 10, 10, 7],
[3, 9, 10, 5],
[4, 6, 6, 9],
[6, 8, 6, 4],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_non_overlapping_placement_s1_to_p(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [2, 3]})
z = y.to_consistent(new_placement, flow.sbp.partial_sum)
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 0, 0],
[6, 8, 0, 0],
[3, 7, 0, 0],
[6, 8, 0, 0],
[2, 10, 0, 0],
[3, 9, 0, 0],
[4, 6, 0, 0],
[6, 8, 0, 0],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[0, 0, 5, 20],
[0, 0, 9, 0],
[0, 0, 5, 0],
[0, 0, 9, 0],
[0, 0, 10, 7],
[0, 0, 10, 5],
[0, 0, 6, 9],
[0, 0, 6, 4],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_overlapping_placement_p_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.partial_sum)
new_placement = flow.placement(out_device, {0: [2, 3]})
y = x.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[15, 20], [16, 19], [13, 16], [15, 23],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[20, 35], [28, 10], [20, 11], [20, 12],], dtype=np.float32,),
)
)
def _test_eager_boxing_with_overlapping_placement_b_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.broadcast)
new_placement = flow.placement(out_device, {0: [2, 3]})
y = x.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[4, 6], [6, 8], [3, 7], [6, 8],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[5, 20], [9, 0], [5, 0], [9, 0],], dtype=np.float32,),
)
)
def _test_eager_boxing_with_overlapping_placement_s0_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
new_placement = flow.placement(out_device, {0: [2, 3]})
y = x.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[
[4, 6],
[6, 8],
[3, 7],
[6, 8],
[2, 10],
[3, 9],
[4, 6],
[6, 8],
[9, 4],
[7, 2],
[6, 3],
[3, 7],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[
[5, 20],
[9, 0],
[5, 0],
[9, 0],
[10, 7],
[10, 5],
[6, 9],
[6, 4],
[5, 8],
[9, 5],
[9, 2],
[5, 8],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_overlapping_placement_s1_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [2, 3]})
z = y.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 5],
[6, 8, 9],
[3, 7, 5],
[6, 8, 9],
[2, 10, 10],
[3, 9, 10],
[4, 6, 6],
[6, 8, 6],
[9, 4, 5],
[7, 2, 9],
[6, 3, 9],
[3, 7, 5],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[20, 8, 9],
[0, 4, 6],
[0, 3, 5],
[0, 8, 7],
[7, 10, 3],
[5, 5, 6],
[9, 8, 6],
[4, 5, 3],
[8, 9, 6],
[5, 4, 1],
[2, 5, 2],
[8, 9, 3],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_overlapping_placement_s1_to_s0(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [2, 3]})
z = y.to_consistent(new_placement, flow.sbp.split(0))
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_overlapping_placement_s1_to_b(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [2, 3]})
z = y.to_consistent(new_placement, flow.sbp.broadcast)
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_overlapping_placement_s1_to_p(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [2, 3]})
z = y.to_consistent(new_placement, flow.sbp.partial_sum)
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 0, 0, 0, 0],
[6, 8, 0, 0, 0, 0],
[3, 7, 0, 0, 0, 0],
[6, 8, 0, 0, 0, 0],
[2, 10, 0, 0, 0, 0],
[3, 9, 0, 0, 0, 0],
[4, 6, 0, 0, 0, 0],
[6, 8, 0, 0, 0, 0],
[9, 4, 0, 0, 0, 0],
[7, 2, 0, 0, 0, 0],
[6, 3, 0, 0, 0, 0],
[3, 7, 0, 0, 0, 0],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[0, 0, 5, 20, 8, 9],
[0, 0, 9, 0, 4, 6],
[0, 0, 5, 0, 3, 5],
[0, 0, 9, 0, 8, 7],
[0, 0, 10, 7, 10, 3],
[0, 0, 10, 5, 5, 6],
[0, 0, 6, 9, 8, 6],
[0, 0, 6, 4, 5, 3],
[0, 0, 5, 8, 9, 6],
[0, 0, 9, 5, 4, 1],
[0, 0, 9, 2, 5, 2],
[0, 0, 5, 8, 9, 3],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_in_placement_contain_out_placement_p_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.partial_sum)
new_placement = flow.placement(out_device, {0: [1, 3]})
y = x.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, new_placement)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[15, 20], [16, 19], [13, 16], [15, 23],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[20, 35], [28, 10], [20, 11], [20, 12],], dtype=np.float32,),
)
)
def _test_eager_boxing_with_in_placement_contain_out_placement_b_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.broadcast)
new_placement = flow.placement(out_device, {0: [1, 3]})
y = x.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, new_placement)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[4, 6], [6, 8], [3, 7], [6, 8],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[5, 20], [9, 0], [5, 0], [9, 0],], dtype=np.float32,),
)
)
def _test_eager_boxing_with_in_placement_contain_out_placement_s0_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
new_placement = flow.placement(out_device, {0: [1, 3]})
y = x.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, new_placement)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[
[4, 6],
[6, 8],
[3, 7],
[6, 8],
[2, 10],
[3, 9],
[4, 6],
[6, 8],
[9, 4],
[7, 2],
[6, 3],
[3, 7],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[
[5, 20],
[9, 0],
[5, 0],
[9, 0],
[10, 7],
[10, 5],
[6, 9],
[6, 4],
[5, 8],
[9, 5],
[9, 2],
[5, 8],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_in_placement_contain_out_placement_s1_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 2, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.broadcast)
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [1, 3]})
z = y.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array([[4, 6], [6, 8], [3, 7], [6, 8],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array([[5, 20], [9, 0], [5, 0], [9, 0],], dtype=np.float32,),
)
)
def _test_eager_boxing_with_in_placement_contain_out_placement_s1_to_s0(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 2, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.broadcast)
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [1, 3]})
z = y.to_consistent(new_placement, flow.sbp.split(0))
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array([[4, 6, 5, 20], [6, 8, 9, 0],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array([[3, 7, 5, 0], [6, 8, 9, 0],], dtype=np.float32,),
)
)
def _test_eager_boxing_with_in_placement_contain_out_placement_s1_to_p(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 2, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.broadcast)
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [1, 3]})
z = y.to_consistent(new_placement, flow.sbp.partial_sum)
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[4, 6, 5, 0], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0],],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[0, 0, 0, 20], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_in_placement_contain_out_placement_s1_to_b(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 2, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.broadcast)
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [1, 3]})
z = y.to_consistent(new_placement, flow.sbp.broadcast)
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0],],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0],],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_out_placement_contain_in_placement_p_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.partial_sum)
new_placement = flow.placement(out_device, {0: [0, 1, 2, 3]})
y = x.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, new_placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[15], [16], [13], [15],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[20], [19], [16], [23],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[20], [28], [20], [20],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[35], [10], [11], [12],], dtype=np.float32,),
)
)
def _test_eager_boxing_with_out_placement_contain_in_placement_b_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.broadcast)
new_placement = flow.placement(out_device, {0: [0, 1, 2, 3]})
y = x.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, new_placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[4], [6], [3], [6],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[6], [8], [7], [8],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[5], [9], [5], [9],], dtype=np.float32,),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array([[20], [0], [0], [0],], dtype=np.float32,),
)
)
def _test_eager_boxing_with_out_placement_contain_in_placement_s0_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
new_placement = flow.placement(out_device, {0: [0, 1, 2, 3]})
y = x.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, new_placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[[4], [6], [3], [6], [2], [3], [4], [6], [9], [7], [6], [3],],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[[6], [8], [7], [8], [10], [9], [6], [8], [4], [2], [3], [7],],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[[5], [9], [5], [9], [10], [10], [6], [6], [5], [9], [9], [5],],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[[20], [0], [0], [0], [7], [5], [9], [4], [8], [5], [2], [8],],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_out_placement_contain_in_placement_s1_to_b(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [0, 1, 2, 3]})
z = y.to_consistent(new_placement, flow.sbp.broadcast)
test_case.assertEqual(z.placement, new_placement)
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_out_placement_contain_in_placement_s1_to_p(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [0, 1, 2, 3]})
z = y.to_consistent(new_placement, flow.sbp.partial_sum)
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 0, 0, 0, 0],
[6, 8, 0, 0, 0, 0],
[3, 7, 0, 0, 0, 0],
[6, 8, 0, 0, 0, 0],
[2, 10, 0, 0, 0, 0],
[3, 9, 0, 0, 0, 0],
[4, 6, 0, 0, 0, 0],
[6, 8, 0, 0, 0, 0],
[9, 4, 0, 0, 0, 0],
[7, 2, 0, 0, 0, 0],
[6, 3, 0, 0, 0, 0],
[3, 7, 0, 0, 0, 0],
],
dtype=np.float32,
),
)
)
elif flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[0, 0, 5, 20, 0, 0],
[0, 0, 9, 0, 0, 0],
[0, 0, 5, 0, 0, 0],
[0, 0, 9, 0, 0, 0],
[0, 0, 10, 7, 0, 0],
[0, 0, 10, 5, 0, 0],
[0, 0, 6, 9, 0, 0],
[0, 0, 6, 4, 0, 0],
[0, 0, 5, 8, 0, 0],
[0, 0, 9, 5, 0, 0],
[0, 0, 9, 2, 0, 0],
[0, 0, 5, 8, 0, 0],
],
dtype=np.float32,
),
)
)
elif flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
],
dtype=np.float32,
),
)
)
else:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[0, 0, 0, 0, 8, 9],
[0, 0, 0, 0, 4, 6],
[0, 0, 0, 0, 3, 5],
[0, 0, 0, 0, 8, 7],
[0, 0, 0, 0, 10, 3],
[0, 0, 0, 0, 5, 6],
[0, 0, 0, 0, 8, 6],
[0, 0, 0, 0, 5, 3],
[0, 0, 0, 0, 9, 6],
[0, 0, 0, 0, 4, 1],
[0, 0, 0, 0, 5, 2],
[0, 0, 0, 0, 9, 3],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_out_placement_contain_in_placement_s1_to_s0(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [0, 1, 2, 3]})
z = y.to_consistent(new_placement, flow.sbp.split(0))
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5],],
dtype=np.float32,
),
)
)
elif flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[6, 8, 9, 0, 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6],],
dtype=np.float32,
),
)
)
elif flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[4, 6, 6, 9, 8, 6], [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6],],
dtype=np.float32,
),
)
)
elif flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3],],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_out_placement_contain_in_placement_s1_to_s1(
test_case, in_device, out_device
):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9, 5, 20],
[6, 8, 9, 0, 4, 6, 9, 0],
[3, 7, 5, 0, 3, 5, 0, 3],
[6, 8, 9, 0, 8, 7, 8, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3, 10, 7],
[3, 9, 10, 5, 5, 6, 9, 10],
[4, 6, 6, 9, 8, 6, 6, 9],
[6, 8, 6, 4, 5, 3, 8, 6],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6, 8, 3],
[4, 9, 7, 0, 2, 1, 9, 7],
[2, 5, 7, 9, 4, 8, 5, 7],
[6, 8, 10, 0, 4, 9, 8, 10],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6, 5, 8],
[7, 2, 9, 5, 4, 1, 7, 2],
[6, 3, 9, 2, 5, 2, 9, 2],
[3, 7, 5, 8, 9, 3, 7, 5],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
new_placement = flow.placement(out_device, {0: [0, 1, 2, 3]})
z = y.to_consistent(new_placement, flow.sbp.split(1))
test_case.assertEqual(z.placement, new_placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8],],
dtype=np.float32,
),
)
)
elif flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[5, 20],
[9, 0],
[5, 0],
[9, 0],
[10, 7],
[10, 5],
[6, 9],
[6, 4],
],
dtype=np.float32,
),
)
)
elif flow.env.get_rank() == 2:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[[8, 9], [4, 6], [3, 5], [8, 7], [10, 3], [5, 6], [8, 6], [5, 3],],
dtype=np.float32,
),
)
)
elif flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[5, 20],
[9, 0],
[0, 3],
[8, 9],
[10, 7],
[9, 10],
[6, 9],
[8, 6],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_same_placement_p_to_s1(test_case, in_device, out_device):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
[6, 8, 9, 0, 4, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
[4, 9, 7, 0, 2, 1],
[6, 3, 9, 2, 5, 2],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
[6, 3, 9, 2, 5, 2],
[2, 5, 7, 9, 4, 8],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
[7, 2, 9, 5, 4, 1],
[4, 9, 7, 0, 2, 1],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.partial_sum)
y = x.to_consistent(placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[[15, 20], [16, 19], [13, 16], [15, 23], [17, 19], [16, 20],],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[[20, 35], [28, 10], [20, 11], [20, 12], [25, 5], [22, 6],],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[[27, 18], [13, 13], [16, 13], [22, 13], [10, 8], [12, 6],],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_same_placement_b_to_s1(test_case, in_device, out_device):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
[6, 8, 9, 0, 4, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
[4, 9, 7, 0, 2, 1],
[6, 3, 9, 2, 5, 2],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
[6, 3, 9, 2, 5, 2],
[2, 5, 7, 9, 4, 8],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
[7, 2, 9, 5, 4, 1],
[4, 9, 7, 0, 2, 1],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.broadcast)
y = x.to_consistent(placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[[4, 6], [6, 8], [3, 7], [6, 8], [6, 8], [6, 8],], dtype=np.float32,
),
)
)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[[5, 20], [9, 0], [5, 0], [9, 0], [9, 0], [6, 4],],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[[8, 9], [4, 6], [3, 5], [8, 7], [4, 6], [5, 3],], dtype=np.float32,
),
)
)
def _test_eager_boxing_with_same_placement_s0_to_s1(test_case, in_device, out_device):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
test_case.assertEqual(y.placement, placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[
[4, 6],
[6, 8],
[3, 7],
[6, 8],
[2, 10],
[3, 9],
[4, 6],
[6, 8],
[9, 4],
[7, 2],
[6, 3],
[3, 7],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[
[5, 20],
[9, 0],
[5, 0],
[9, 0],
[10, 7],
[10, 5],
[6, 9],
[6, 4],
[5, 8],
[9, 5],
[9, 2],
[5, 8],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
np.array(
[
[8, 9],
[4, 6],
[3, 5],
[8, 7],
[10, 3],
[5, 6],
[8, 6],
[5, 3],
[9, 6],
[4, 1],
[5, 2],
[9, 3],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_same_placement_s1_to_s1(test_case, in_device, out_device):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
z = y.to_consistent(placement, flow.sbp.split(1))
test_case.assertEqual(z.placement, placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6],
[6, 8],
[3, 7],
[6, 8],
[2, 10],
[3, 9],
[4, 6],
[6, 8],
[9, 4],
[7, 2],
[6, 3],
[3, 7],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[5, 20],
[9, 0],
[5, 0],
[9, 0],
[10, 7],
[10, 5],
[6, 9],
[6, 4],
[5, 8],
[9, 5],
[9, 2],
[5, 8],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[8, 9],
[4, 6],
[3, 5],
[8, 7],
[10, 3],
[5, 6],
[8, 6],
[5, 3],
[9, 6],
[4, 1],
[5, 2],
[9, 3],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_same_placement_s1_to_s0(test_case, in_device, out_device):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
z = y.to_consistent(placement, flow.sbp.split(0))
test_case.assertEqual(z.placement, placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_same_placement_s1_to_p(test_case, in_device, out_device):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
z = y.to_consistent(placement, flow.sbp.partial_sum)
test_case.assertEqual(z.placement, placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 0, 0, 0, 0],
[6, 8, 0, 0, 0, 0],
[3, 7, 0, 0, 0, 0],
[6, 8, 0, 0, 0, 0],
[2, 10, 0, 0, 0, 0],
[3, 9, 0, 0, 0, 0],
[4, 6, 0, 0, 0, 0],
[6, 8, 0, 0, 0, 0],
[9, 4, 0, 0, 0, 0],
[7, 2, 0, 0, 0, 0],
[6, 3, 0, 0, 0, 0],
[3, 7, 0, 0, 0, 0],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[0, 0, 5, 20, 0, 0],
[0, 0, 9, 0, 0, 0],
[0, 0, 5, 0, 0, 0],
[0, 0, 9, 0, 0, 0],
[0, 0, 10, 7, 0, 0],
[0, 0, 10, 5, 0, 0],
[0, 0, 6, 9, 0, 0],
[0, 0, 6, 4, 0, 0],
[0, 0, 5, 8, 0, 0],
[0, 0, 9, 5, 0, 0],
[0, 0, 9, 2, 0, 0],
[0, 0, 5, 8, 0, 0],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[0, 0, 0, 0, 8, 9],
[0, 0, 0, 0, 4, 6],
[0, 0, 0, 0, 3, 5],
[0, 0, 0, 0, 8, 7],
[0, 0, 0, 0, 10, 3],
[0, 0, 0, 0, 5, 6],
[0, 0, 0, 0, 8, 6],
[0, 0, 0, 0, 5, 3],
[0, 0, 0, 0, 9, 6],
[0, 0, 0, 0, 4, 1],
[0, 0, 0, 0, 5, 2],
[0, 0, 0, 0, 9, 3],
],
dtype=np.float32,
),
)
)
def _test_eager_boxing_with_same_placement_s1_to_b(test_case, in_device, out_device):
if flow.env.get_rank() == 0:
np_arr = np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 1:
np_arr = np.array(
[
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 2:
np_arr = np.array(
[
[9, 6, 5, 8, 3, 6],
[4, 9, 7, 0, 2, 1],
[2, 5, 7, 9, 4, 8],
[6, 8, 10, 0, 4, 9],
],
dtype=np.float32,
)
elif flow.env.get_rank() == 3:
np_arr = np.array(
[
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
)
device = flow.device(in_device)
tensor = flow.tensor(np_arr, device=device, dtype=flow.float32)
placement = flow.placement(in_device, {0: [0, 1, 3]})
x = tensor.to_consistent(placement, flow.sbp.split(0))
y = x.to_consistent(placement, flow.sbp.split(1))
z = y.to_consistent(placement, flow.sbp.broadcast)
test_case.assertEqual(z.placement, placement)
if flow.env.get_rank() == 0:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 1:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
),
)
)
if flow.env.get_rank() == 3:
test_case.assertTrue(
np.array_equal(
z.to_local().numpy(),
np.array(
[
[4, 6, 5, 20, 8, 9],
[6, 8, 9, 0, 4, 6],
[3, 7, 5, 0, 3, 5],
[6, 8, 9, 0, 8, 7],
[2, 10, 10, 7, 10, 3],
[3, 9, 10, 5, 5, 6],
[4, 6, 6, 9, 8, 6],
[6, 8, 6, 4, 5, 3],
[9, 4, 5, 8, 9, 6],
[7, 2, 9, 5, 4, 1],
[6, 3, 9, 2, 5, 2],
[3, 7, 5, 8, 9, 3],
],
dtype=np.float32,
),
)
)
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def _test_eager_boxing_b_to_s(
test_case, shape, device_type, in_device_list, out_device_list, out_split_axis
):
np_arr = np.random.uniform(-1e-05, 1e-05, shape)
# use cuda to avoid slice boxing here
placement_with_all_cuda_device = flow.env.all_device_placement("cuda")
x = flow.tensor(np_arr, device="cuda", dtype=flow.float32)
x = x.to_consistent(placement_with_all_cuda_device, flow.sbp.broadcast)
placement = flow.placement(device_type, {0: in_device_list})
y = x.to_consistent(placement, flow.sbp.broadcast)
new_placement = flow.placement(device_type, {0: out_device_list})
z = y.to_consistent(new_placement, flow.sbp.split(out_split_axis))
if flow.env.get_rank() in out_device_list:
idx = out_device_list.index(flow.env.get_rank())
step = int(shape[out_split_axis] / len(out_device_list))
if out_split_axis == 0:
test_case.assertTrue(
np.allclose(
z.to_local().numpy(),
x.to_local().numpy()[idx * step : (idx + 1) * step],
1e-5,
1e-5,
)
)
elif out_split_axis == 1:
test_case.assertTrue(
np.allclose(
z.to_local().numpy(),
x.to_local().numpy()[..., idx * step : (idx + 1) * step],
1e-5,
1e-5,
)
)
else:
raise "only test case with out_split_axis == 0 or out_split_axis == 1"
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def _test_eager_boxing_s_to_b(
test_case, shape, device_type, in_device_list, out_device_list, in_split_axis
):
np_arr = np.random.uniform(-1e-05, 1e-05, shape)
# use cuda to avoid slice boxing here
placement_with_all_cuda_device = flow.env.all_device_placement("cuda")
x = flow.tensor(np_arr, device="cuda", dtype=flow.float32)
x = x.to_consistent(placement_with_all_cuda_device, flow.sbp.broadcast)
placement = flow.placement(device_type, {0: in_device_list})
y = x.to_consistent(placement, flow.sbp.broadcast)
y = y.to_consistent(placement, flow.sbp.split(in_split_axis))
new_placement = flow.placement(device_type, {0: out_device_list})
z = y.to_consistent(new_placement, flow.sbp.broadcast)
if flow.env.get_rank() in out_device_list:
test_case.assertTrue(
np.allclose(z.to_local().numpy(), x.to_local().numpy(), 1e-5, 1e-5,)
)
test_case.assertEqual(z.placement, new_placement)
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def _test_eager_boxing_p_to_s(
test_case, shape, device_type, in_device_list, out_device_list, out_split_axis
):
np_arr = np.random.uniform(-1e-05, 1e-05, shape)
# use cuda to avoid slice boxing here
placement_with_all_cuda_device = flow.env.all_device_placement("cuda")
x = flow.tensor(np_arr, device="cuda", dtype=flow.float32)
x = x.to_consistent(placement_with_all_cuda_device, flow.sbp.broadcast)
placement = flow.placement(device_type, {0: in_device_list})
y = x.to_consistent(placement, flow.sbp.broadcast)
y = y.to_consistent(placement, flow.sbp.partial_sum)
new_placement = flow.placement(device_type, {0: out_device_list})
z = y.to_consistent(new_placement, flow.sbp.split(out_split_axis))
if flow.env.get_rank() in out_device_list:
idx = out_device_list.index(flow.env.get_rank())
step = int(shape[out_split_axis] / len(out_device_list))
if out_split_axis == 0:
test_case.assertTrue(
np.allclose(
z.to_local().numpy(),
x.to_local().numpy()[idx * step : (idx + 1) * step],
1e-5,
1e-5,
)
)
elif out_split_axis == 1:
test_case.assertTrue(
np.allclose(
z.to_local().numpy(),
x.to_local().numpy()[..., idx * step : (idx + 1) * step],
1e-5,
1e-5,
)
)
else:
raise "only test case with out_split_axis == 0 or out_split_axis == 1"
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def _test_eager_boxing_p_to_b(
test_case, shape, device_type, in_device_list, out_device_list
):
np_arr = np.random.uniform(-1e-05, 1e-05, shape)
# use cuda to avoid slice boxing here
placement_with_all_cuda_device = flow.env.all_device_placement("cuda")
x = flow.tensor(np_arr, device="cuda", dtype=flow.float32)
x = x.to_consistent(placement_with_all_cuda_device, flow.sbp.broadcast)
placement = flow.placement(device_type, {0: in_device_list})
y = x.to_consistent(placement, flow.sbp.broadcast)
y = y.to_consistent(placement, flow.sbp.partial_sum)
new_placement = flow.placement(device_type, {0: out_device_list})
z = y.to_consistent(new_placement, flow.sbp.broadcast)
if flow.env.get_rank() in out_device_list:
test_case.assertTrue(
np.allclose(z.to_local().numpy(), x.to_local().numpy(), 1e-5, 1e-5,)
)
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def _test_eager_naive_boxing_s_to_s(
test_case,
device_type,
shape,
in_device_list,
out_device_list,
in_split_axis,
out_split_axis,
):
np_arr = np.random.uniform(-1e-05, 1e-05, shape)
placement_with_all_cuda_device = flow.env.all_device_placement(device_type)
x = flow.tensor(np_arr, device=device_type, dtype=flow.float32)
x = x.to_consistent(placement_with_all_cuda_device, flow.sbp.broadcast)
placement = flow.placement(device_type, {0: in_device_list})
y = x.to_consistent(placement, flow.sbp.broadcast)
y = y.to_consistent(placement, flow.sbp.split(in_split_axis))
new_placement = flow.placement(device_type, {0: out_device_list})
z = y.to_consistent(new_placement, flow.sbp.split(out_split_axis))
if flow.env.get_rank() in out_device_list:
idx = out_device_list.index(flow.env.get_rank())
step = int(shape[out_split_axis] / len(out_device_list))
if out_split_axis == 0:
test_case.assertTrue(
np.allclose(
z.to_local().numpy(),
x.to_local().numpy()[idx * step : (idx + 1) * step],
1e-5,
1e-5,
)
)
elif out_split_axis == 1:
test_case.assertTrue(
np.allclose(
z.to_local().numpy(),
x.to_local().numpy()[..., idx * step : (idx + 1) * step],
1e-5,
1e-5,
)
)
else:
raise "only test case with out_split_axis == 0 or out_split_axis == 1"
test_case.assertEqual(z.placement, new_placement)
@flow.unittest.skip_unless_1n4d()
class TestEagerBoxingWithNonOverlappingPlacement(flow.unittest.TestCase):
def test_eager_boxing_with_non_overlapping_placement_p_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_non_overlapping_placement_p_to_s1(test_case, *arg)
def test_eager_boxing_with_non_overlapping_placement_b_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_non_overlapping_placement_b_to_s1(test_case, *arg)
def test_eager_boxing_with_non_overlapping_placement_s0_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_non_overlapping_placement_s0_to_s1(test_case, *arg)
def test_eager_boxing_with_non_overlapping_placement_s1_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_non_overlapping_placement_s1_to_s1(test_case, *arg)
def test_eager_boxing_with_non_overlapping_placement_s1_to_s0(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_non_overlapping_placement_s1_to_s0(test_case, *arg)
def test_eager_boxing_with_non_overlapping_placement_s1_to_b(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_non_overlapping_placement_s1_to_b(test_case, *arg)
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def test_eager_boxing_with_non_overlapping_placement_s1_to_p(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_non_overlapping_placement_s1_to_p(test_case, *arg)
@flow.unittest.skip_unless_1n4d()
class TestEagerBoxingWithOverlappingPlacement(flow.unittest.TestCase):
def test_eager_boxing_with_overlapping_placement_p_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_overlapping_placement_p_to_s1(test_case, *arg)
def test_eager_boxing_with_overlapping_placement_b_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_overlapping_placement_b_to_s1(test_case, *arg)
def test_eager_boxing_with_overlapping_placement_s0_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_overlapping_placement_s0_to_s1(test_case, *arg)
def test_eager_boxing_with_overlapping_placement_s1_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_overlapping_placement_s1_to_s1(test_case, *arg)
def test_eager_boxing_with_overlapping_placement_s1_to_s0(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_overlapping_placement_s1_to_s0(test_case, *arg)
def test_eager_boxing_with_overlapping_placement_s1_to_b(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_overlapping_placement_s1_to_b(test_case, *arg)
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def test_eager_boxing_with_overlapping_placement_s1_to_p(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_overlapping_placement_s1_to_p(test_case, *arg)
@flow.unittest.skip_unless_1n4d()
class TestEagerBoxingWithInPlacementContainOutPlacement(flow.unittest.TestCase):
def test_eager_boxing_with_in_placement_contain_out_placement_p_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_in_placement_contain_out_placement_p_to_s1(
test_case, *arg
)
def test_eager_boxing_with_in_placement_contain_out_placement_b_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_in_placement_contain_out_placement_b_to_s1(
test_case, *arg
)
def test_eager_boxing_with_in_placement_contain_out_placement_s0_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_in_placement_contain_out_placement_s0_to_s1(
test_case, *arg
)
def test_eager_boxing_with_in_placement_contain_out_placement_s1_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_in_placement_contain_out_placement_s1_to_s1(
test_case, *arg
)
def test_eager_boxing_with_in_placement_contain_out_placement_s1_to_s0(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_in_placement_contain_out_placement_s1_to_s0(
test_case, *arg
)
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def test_eager_boxing_with_in_placement_contain_out_placement_s1_to_p(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_in_placement_contain_out_placement_s1_to_p(
test_case, *arg
)
def test_eager_boxing_with_in_placement_contain_out_placement_s1_to_b(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_in_placement_contain_out_placement_s1_to_b(
test_case, *arg
)
@flow.unittest.skip_unless_1n4d()
class TestEagerBoxingWithOutPlacementContainInPlacement(flow.unittest.TestCase):
def test_eager_boxing_with_out_placement_contain_in_placement_p_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_out_placement_contain_in_placement_p_to_s1(
test_case, *arg
)
def test_eager_boxing_with_out_placement_contain_in_placement_b_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_out_placement_contain_in_placement_b_to_s1(
test_case, *arg
)
def test_eager_boxing_with_out_placement_contain_in_placement_s0_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_out_placement_contain_in_placement_s0_to_s1(
test_case, *arg
)
def test_eager_boxing_with_out_placement_contain_in_placement_s1_to_b(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_out_placement_contain_in_placement_s1_to_b(
test_case, *arg
)
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def test_eager_boxing_with_out_placement_contain_in_placement_s1_to_p(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_out_placement_contain_in_placement_s1_to_p(
test_case, *arg
)
def test_eager_boxing_with_out_placement_contain_in_placement_s1_to_s0(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_out_placement_contain_in_placement_s1_to_s0(
test_case, *arg
)
def test_eager_boxing_with_out_placement_contain_in_placement_s1_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_out_placement_contain_in_placement_s1_to_s1(
test_case, *arg
)
@flow.unittest.skip_unless_1n4d()
class TestEagerBoxingWithSameInOutPlacement(flow.unittest.TestCase):
def test_eager_boxing_with_same_placement_s0_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_same_placement_s0_to_s1(test_case, *arg)
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def test_eager_boxing_with_same_placement_p_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_same_placement_p_to_s1(test_case, *arg)
def test_eager_boxing_with_same_placement_b_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_same_placement_b_to_s1(test_case, *arg)
def test_eager_boxing_with_same_placement_s1_to_s1(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_same_placement_s1_to_s1(test_case, *arg)
def test_eager_boxing_with_same_placement_s1_to_s0(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_same_placement_s1_to_s0(test_case, *arg)
def test_eager_boxing_with_same_placement_s1_to_p(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_same_placement_s1_to_p(test_case, *arg)
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def test_eager_boxing_with_same_placement_s1_to_b(test_case):
arg_dict = OrderedDict()
arg_dict["in_device"] = ["cpu", "cuda"]
arg_dict["out_device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_eager_boxing_with_same_placement_s1_to_b(test_case, *arg)
@flow.unittest.skip_unless_1n4d()
class TestEagerBoxingBToS(flow.unittest.TestCase):
def test_eager_boxing_b_to_s(test_case):
arg_dict = OrderedDict()
arg_dict["shape"] = [(12, 12), (18, 24)]
arg_dict["device_type"] = ["cpu", "cuda"]
arg_dict["in_device_list"] = [[0, 1], [1, 2, 3]]
arg_dict["out_device_list"] = [[2, 3], [0, 1, 3]]
arg_dict["out_split_axis"] = [0, 1]
for arg in GenArgList(arg_dict):
_test_eager_boxing_b_to_s(test_case, *arg)
@flow.unittest.skip_unless_1n4d()
class TestEagerBoxingPToS(flow.unittest.TestCase):
def test_eager_boxing_p_to_s(test_case):
arg_dict = OrderedDict()
arg_dict["shape"] = [(12, 12), (18, 24)]
arg_dict["device_type"] = ["cpu", "cuda"]
arg_dict["in_device_list"] = [[0, 1], [1, 2, 3]]
arg_dict["out_device_list"] = [[2, 3], [0, 1, 3]]
arg_dict["out_split_axis"] = [0, 1]
for arg in GenArgList(arg_dict):
_test_eager_boxing_p_to_s(test_case, *arg)
@flow.unittest.skip_unless_1n4d()
class TestEagerBoxingSToB(flow.unittest.TestCase):
def test_eager_boxing_s_to_b(test_case):
arg_dict = OrderedDict()
arg_dict["shape"] = [(12, 12), (12, 18, 24)]
arg_dict["device_type"] = ["cpu", "cuda"]
arg_dict["in_device_list"] = [[0, 1], [1, 2, 3]]
arg_dict["out_device_list"] = [[2, 3], [0, 1, 3]]
arg_dict["in_split_axis"] = [0, 1]
for arg in GenArgList(arg_dict):
_test_eager_boxing_s_to_b(test_case, *arg)
@flow.unittest.skip_unless_1n4d()
class TestEagerBoxingPToB(flow.unittest.TestCase):
def test_eager_boxing_p_to_b(test_case):
arg_dict = OrderedDict()
arg_dict["shape"] = [(12, 12), (12, 18, 24)]
arg_dict["device_type"] = ["cpu", "cuda"]
arg_dict["in_device_list"] = [[0, 1], [1, 2, 3]]
arg_dict["out_device_list"] = [[2, 3], [0, 1, 3]]
for arg in GenArgList(arg_dict):
_test_eager_boxing_p_to_b(test_case, *arg)
@flow.unittest.skip_unless_1n4d()
class TestEagerNaiveBoxingSToS(flow.unittest.TestCase):
def test_eager_naive_boxing_s_to_s(test_case):
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "cuda"]
arg_dict["shape"] = [(12, 12), (18, 24)]
arg_dict["in_device_list"] = [[0, 1], [1, 2, 3]]
arg_dict["out_device_list"] = [[1], [3], [2, 3], [0, 1, 3]]
arg_dict["in_split_axis"] = [0, 1]
arg_dict["out_split_axis"] = [0, 1]
for arg in GenArgList(arg_dict):
_test_eager_naive_boxing_s_to_s(test_case, *arg)
@flow.unittest.skip_unless_1n2d()
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
class TestEagerConsistentCastWithSamePlacementAndSBP(flow.unittest.TestCase):
def test_eager_consistent_cast_with_same_placement_and_sbp(test_case):
x = np.ones((4, 8), dtype=np.int32)
placement = flow.placement("cuda", {0: range(2)})
y = flow.tensor(
x,
dtype=flow.float32,
placement=placement,
sbp=[flow.sbp.split(0)],
requires_grad=False,
)
z = y.to_consistent(placement=placement, sbp=[flow.sbp.split(0)])
test_case.assertEqual(y.consistent_id(), z.consistent_id())
@flow.unittest.skip_unless_1n4d()
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
class TestEagerConsistentCast1DTo2DSBP(flow.unittest.TestCase):
def test_eager_consistent_cast_1d_to_2d_sbp(test_case):
x = np.ones((4, 8), dtype=np.int32)
placement1 = flow.placement("cuda", {0: range(4)})
placement2 = flow.placement("cuda", {0: range(4)}, (2, 2))
y = flow.tensor(
x,
dtype=flow.float32,
placement=placement1,
sbp=[flow.sbp.split(0)],
requires_grad=False,
)
z = y.to_consistent(
placement=placement2, sbp=[flow.sbp.broadcast, flow.sbp.split(0)]
)
test_case.assertEqual(z.placement, placement2)
test_case.assertTrue(
np.array_equal(z.to_local().numpy(), np.ones((2, 8), dtype=np.int32),)
)
@flow.unittest.skip_unless_1n4d()
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
class TestEagerConsistentCast2DTo1DSBP(flow.unittest.TestCase):
def test_eager_consistent_cast_2d_to_1d_sbp(test_case):
x = np.ones((4, 8), dtype=np.int32)
placement1 = flow.placement("cuda", {0: range(4)})
placement2 = flow.placement("cuda", {0: range(4)}, (2, 2))
y = flow.tensor(
x,
dtype=flow.float32,
placement=placement2,
sbp=[flow.sbp.broadcast, flow.sbp.split(0)],
requires_grad=False,
)
z = y.to_consistent(placement=placement1, sbp=[flow.sbp.split(0)])
test_case.assertEqual(z.placement, placement1)
test_case.assertTrue(
np.array_equal(z.to_local().numpy(), np.ones((1, 8), dtype=np.int32),)
)
def _test_eager_consistent_cast_1d_uneven_split(test_case, device_type, shape):
np_arr = np.random.uniform(-1e-05, 1e-05, shape)
placement = flow.placement(device_type, {0: range(flow.env.get_world_size())})
x = flow.tensor(
np_arr, dtype=flow.float32, device=device_type, requires_grad=False,
)
x = x.to_consistent(placement=placement, sbp=[flow.sbp.broadcast])
# B To S(0)
y = x.to_consistent(placement=placement, sbp=[flow.sbp.split(0)])
from oneflow.framework import balanced_splitter as balanced_splitter
s0_balanced_ranges = balanced_splitter.BalancedRanges(
shape[0], flow.env.get_world_size()
)
s0_range_of_this_rank = s0_balanced_ranges[flow.env.get_rank()]
test_case.assertEqual(y.placement, placement)
test_case.assertTrue(
np.array_equal(
y.to_local().numpy(),
x.to_local().numpy()[s0_range_of_this_rank[0] : s0_range_of_this_rank[1]],
)
)
# S(0) To S(1)
z = y.to_consistent(placement=placement, sbp=[flow.sbp.split(1)])
s1_balanced_ranges = flow.framework.balanced_splitter.BalancedRanges(
shape[1], flow.env.get_world_size()
)
s1_range_of_this_rank = s1_balanced_ranges[flow.env.get_rank()]
test_case.assertEqual(z.placement, placement)
test_case.assertTrue(
np.allclose(
z.to_local().numpy(),
x.to_local().numpy()[
..., s1_range_of_this_rank[0] : s1_range_of_this_rank[1]
],
)
)
# S(1) To B
w = z.to_consistent(placement=placement, sbp=[flow.sbp.broadcast])
test_case.assertEqual(w.placement, placement)
test_case.assertTrue(np.allclose(w.to_local().numpy(), x.to_local().numpy()))
@flow.unittest.skip_unless_1n4d()
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
class TestEagerConsistentCastOneDUnevenSplit(flow.unittest.TestCase):
def test_eager_consistent_cast_1d_uneven_split(test_case):
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "cuda"]
arg_dict["shape"] = [(25, 33), (13, 17)]
for arg in GenArgList(arg_dict):
_test_eager_consistent_cast_1d_uneven_split(test_case, *arg)
def _test_eager_consistent_n_dim_reduce(test_case, device_type, src_sbp, dst_sbp):
np.random.seed(10)
np_arr = np.random.uniform(-1e-05, 1e-05, (16, 32))
placement0 = flow.placement(device_type, {0: [0]}, (1, 1))
placement1 = flow.placement(device_type, {0: range(4)}, (2, 2))
# oneflow.placement(device_type="cuda", device_ids={0 : [0]}, hierarchy=(1, 1))
# (src_sbp, src_sbp)
x = flow.tensor(
np_arr, placement=placement0, sbp=[src_sbp, src_sbp], requires_grad=False,
)
# oneflow.placement(device_type="cuda", device_ids={0 : [0, 1, 2, 3]}, hierarchy=(2, 2))
# (dst_sbp, dst_sbp)
y = x.to_consistent(placement=placement1, sbp=[dst_sbp, dst_sbp])
z = y.to_consistent(
placement=placement1, sbp=[flow.sbp.broadcast, flow.sbp.broadcast]
)
test_case.assertEqual(z.placement, placement1)
test_case.assertTrue(np.allclose(z.to_local().numpy(), np_arr))
@flow.unittest.skip_unless_1n4d()
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
class TestEagerConsistentCastNDimReduceBoxing(flow.unittest.TestCase):
def test_eager_consistent_n_dim_reduce(test_case):
arg_dict = OrderedDict()
arg_dict["device_type"] = ["cpu", "cuda"]
arg_dict["src_sbp"] = [flow.sbp.broadcast, flow.sbp.split(0), flow.sbp.split(1)]
arg_dict["dst_sbp"] = [flow.sbp.broadcast, flow.sbp.split(0), flow.sbp.split(1)]
for arg in GenArgList(arg_dict):
_test_eager_consistent_n_dim_reduce(test_case, *arg)
def _test_eager_consistent_with_0_size_data(
test_case,
shape,
in_device_type,
out_device_type,
in_device_list,
out_device_list,
in_sbp,
out_sbp,
):
in_placement = flow.placement(in_device_type, {0: in_device_list})
out_placement = flow.placement(out_device_type, {0: out_device_list})
x = flow.Tensor(*shape, placement=in_placement, sbp=in_sbp)
y = x.to_consistent(out_placement, out_sbp)
test_case.assertEqual(y.placement, out_placement)
test_case.assertEqual(y.sbp, out_sbp)
test_case.assertEqual(y.size(), shape)
@flow.unittest.skip_unless_1n4d()
class TestEagerNaiveBoxingSToS(flow.unittest.TestCase):
def test_eager_consistent_with_0_size_data(test_case):
arg_dict = OrderedDict()
arg_dict["shape"] = [(8, 0, 4), (5, 0, 7)]
arg_dict["in_device_type"] = ["cpu", "cuda"]
arg_dict["out_device_type"] = ["cpu", "cuda"]
arg_dict["in_device_list"] = [[0, 1], [1, 2, 3], [0, 1, 2, 3]]
arg_dict["out_device_list"] = [[1], [3], [2, 3], [0, 1, 3], [0, 1, 2, 3]]
arg_dict["in_sbp"] = [
(flow.sbp.split(0),),
(flow.sbp.split(2),),
(flow.sbp.broadcast,),
(flow.sbp.partial_sum,),
]
arg_dict["out_sbp"] = [
(flow.sbp.split(0),),
(flow.sbp.split(2),),
(flow.sbp.broadcast,),
(flow.sbp.partial_sum,),
]
for arg in GenArgList(arg_dict):
_test_eager_consistent_with_0_size_data(test_case, *arg)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.sbp.split",
"oneflow.env.get_rank",
"oneflow.device",
"oneflow.unittest.skip_unless_1n4d",
"oneflow.Tensor",
"oneflow.unittest.skip_unless_1n2d",
"oneflow.env.get_world_size",
"oneflow.tensor",
"oneflow.env.all_device_placement",
"oneflow.placement"
] | [((96537, 96569), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (96567, 96569), True, 'import oneflow as flow\n'), ((99084, 99116), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (99114, 99116), True, 'import oneflow as flow\n'), ((101572, 101604), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (101602, 101604), True, 'import oneflow as flow\n'), ((104462, 104494), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (104492, 104494), True, 'import oneflow as flow\n'), ((107352, 107384), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (107382, 107384), True, 'import oneflow as flow\n'), ((109820, 109852), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (109850, 109852), True, 'import oneflow as flow\n'), ((110339, 110371), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (110369, 110371), True, 'import oneflow as flow\n'), ((110858, 110890), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (110888, 110890), True, 'import oneflow as flow\n'), ((111380, 111412), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (111410, 111412), True, 'import oneflow as flow\n'), ((111859, 111891), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (111889, 111891), True, 'import oneflow as flow\n'), ((112448, 112480), 'oneflow.unittest.skip_unless_1n2d', 'flow.unittest.skip_unless_1n2d', ([], {}), '()\n', (112478, 112480), True, 'import oneflow as flow\n'), ((113142, 113174), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (113172, 113174), True, 'import oneflow as flow\n'), ((114029, 114061), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (114059, 114061), True, 'import oneflow as flow\n'), ((116634, 116666), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (116664, 116666), True, 'import oneflow as flow\n'), ((118056, 118088), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (118086, 118088), True, 'import oneflow as flow\n'), ((119241, 119273), 'oneflow.unittest.skip_unless_1n4d', 'flow.unittest.skip_unless_1n4d', ([], {}), '()\n', (119271, 119273), True, 'import oneflow as flow\n'), ((1527, 1549), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (1538, 1549), True, 'import oneflow as flow\n'), ((1563, 1617), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (1574, 1617), True, 'import oneflow as flow\n'), ((1634, 1674), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1]}'], {}), '(in_device, {(0): [0, 1]})\n', (1648, 1674), True, 'import oneflow as flow\n'), ((1755, 1796), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (1769, 1796), True, 'import oneflow as flow\n'), ((3156, 3178), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (3167, 3178), True, 'import oneflow as flow\n'), ((3192, 3246), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (3203, 3246), True, 'import oneflow as flow\n'), ((3263, 3303), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1]}'], {}), '(in_device, {(0): [0, 1]})\n', (3277, 3303), True, 'import oneflow as flow\n'), ((3382, 3423), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (3396, 3423), True, 'import oneflow as flow\n'), ((4775, 4797), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (4786, 4797), True, 'import oneflow as flow\n'), ((4811, 4865), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (4822, 4865), True, 'import oneflow as flow\n'), ((4882, 4922), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1]}'], {}), '(in_device, {(0): [0, 1]})\n', (4896, 4922), True, 'import oneflow as flow\n'), ((5000, 5041), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (5014, 5041), True, 'import oneflow as flow\n'), ((6790, 6812), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (6801, 6812), True, 'import oneflow as flow\n'), ((6826, 6880), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (6837, 6880), True, 'import oneflow as flow\n'), ((6897, 6937), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1]}'], {}), '(in_device, {(0): [0, 1]})\n', (6911, 6937), True, 'import oneflow as flow\n'), ((7069, 7110), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (7083, 7110), True, 'import oneflow as flow\n'), ((8859, 8881), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (8870, 8881), True, 'import oneflow as flow\n'), ((8895, 8949), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (8906, 8949), True, 'import oneflow as flow\n'), ((8966, 9006), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1]}'], {}), '(in_device, {(0): [0, 1]})\n', (8980, 9006), True, 'import oneflow as flow\n'), ((9138, 9179), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (9152, 9179), True, 'import oneflow as flow\n'), ((10697, 10719), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (10708, 10719), True, 'import oneflow as flow\n'), ((10733, 10787), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (10744, 10787), True, 'import oneflow as flow\n'), ((10804, 10844), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1]}'], {}), '(in_device, {(0): [0, 1]})\n', (10818, 10844), True, 'import oneflow as flow\n'), ((10976, 11017), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (10990, 11017), True, 'import oneflow as flow\n'), ((13080, 13102), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (13091, 13102), True, 'import oneflow as flow\n'), ((13116, 13170), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (13127, 13170), True, 'import oneflow as flow\n'), ((13187, 13227), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1]}'], {}), '(in_device, {(0): [0, 1]})\n', (13201, 13227), True, 'import oneflow as flow\n'), ((13359, 13400), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (13373, 13400), True, 'import oneflow as flow\n'), ((15457, 15479), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (15468, 15479), True, 'import oneflow as flow\n'), ((15493, 15547), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (15504, 15547), True, 'import oneflow as flow\n'), ((15564, 15607), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (15578, 15607), True, 'import oneflow as flow\n'), ((15688, 15729), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (15702, 15729), True, 'import oneflow as flow\n'), ((17091, 17113), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (17102, 17113), True, 'import oneflow as flow\n'), ((17127, 17181), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (17138, 17181), True, 'import oneflow as flow\n'), ((17198, 17241), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (17212, 17241), True, 'import oneflow as flow\n'), ((17320, 17361), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (17334, 17361), True, 'import oneflow as flow\n'), ((18709, 18731), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (18720, 18731), True, 'import oneflow as flow\n'), ((18745, 18799), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (18756, 18799), True, 'import oneflow as flow\n'), ((18816, 18859), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (18830, 18859), True, 'import oneflow as flow\n'), ((18937, 18978), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (18951, 18978), True, 'import oneflow as flow\n'), ((21642, 21664), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (21653, 21664), True, 'import oneflow as flow\n'), ((21678, 21732), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (21689, 21732), True, 'import oneflow as flow\n'), ((21749, 21792), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (21763, 21792), True, 'import oneflow as flow\n'), ((21924, 21965), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (21938, 21965), True, 'import oneflow as flow\n'), ((24702, 24724), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (24713, 24724), True, 'import oneflow as flow\n'), ((24738, 24792), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (24749, 24792), True, 'import oneflow as flow\n'), ((24809, 24852), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (24823, 24852), True, 'import oneflow as flow\n'), ((24984, 25025), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (24998, 25025), True, 'import oneflow as flow\n'), ((27449, 27471), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (27460, 27471), True, 'import oneflow as flow\n'), ((27485, 27539), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (27496, 27539), True, 'import oneflow as flow\n'), ((27556, 27599), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (27570, 27599), True, 'import oneflow as flow\n'), ((27731, 27772), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (27745, 27772), True, 'import oneflow as flow\n'), ((30730, 30752), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (30741, 30752), True, 'import oneflow as flow\n'), ((30766, 30820), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (30777, 30820), True, 'import oneflow as flow\n'), ((30837, 30880), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (30851, 30880), True, 'import oneflow as flow\n'), ((31012, 31053), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [2, 3]}'], {}), '(out_device, {(0): [2, 3]})\n', (31026, 31053), True, 'import oneflow as flow\n'), ((33572, 33594), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (33583, 33594), True, 'import oneflow as flow\n'), ((33608, 33662), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (33619, 33662), True, 'import oneflow as flow\n'), ((33679, 33722), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (33693, 33722), True, 'import oneflow as flow\n'), ((33803, 33844), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [1, 3]}'], {}), '(out_device, {(0): [1, 3]})\n', (33817, 33844), True, 'import oneflow as flow\n'), ((35219, 35241), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (35230, 35241), True, 'import oneflow as flow\n'), ((35255, 35309), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (35266, 35309), True, 'import oneflow as flow\n'), ((35326, 35369), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (35340, 35369), True, 'import oneflow as flow\n'), ((35448, 35489), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [1, 3]}'], {}), '(out_device, {(0): [1, 3]})\n', (35462, 35489), True, 'import oneflow as flow\n'), ((36850, 36872), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (36861, 36872), True, 'import oneflow as flow\n'), ((36886, 36940), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (36897, 36940), True, 'import oneflow as flow\n'), ((36957, 37000), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (36971, 37000), True, 'import oneflow as flow\n'), ((37078, 37119), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [1, 3]}'], {}), '(out_device, {(0): [1, 3]})\n', (37092, 37119), True, 'import oneflow as flow\n'), ((39347, 39369), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (39358, 39369), True, 'import oneflow as flow\n'), ((39383, 39437), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (39394, 39437), True, 'import oneflow as flow\n'), ((39454, 39500), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 2, 1, 3]}'], {}), '(in_device, {(0): [0, 2, 1, 3]})\n', (39468, 39500), True, 'import oneflow as flow\n'), ((39633, 39674), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [1, 3]}'], {}), '(out_device, {(0): [1, 3]})\n', (39647, 39674), True, 'import oneflow as flow\n'), ((41035, 41057), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (41046, 41057), True, 'import oneflow as flow\n'), ((41071, 41125), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (41082, 41125), True, 'import oneflow as flow\n'), ((41142, 41188), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 2, 1, 3]}'], {}), '(in_device, {(0): [0, 2, 1, 3]})\n', (41156, 41188), True, 'import oneflow as flow\n'), ((41321, 41362), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [1, 3]}'], {}), '(out_device, {(0): [1, 3]})\n', (41335, 41362), True, 'import oneflow as flow\n'), ((42714, 42736), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (42725, 42736), True, 'import oneflow as flow\n'), ((42750, 42804), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (42761, 42804), True, 'import oneflow as flow\n'), ((42821, 42867), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 2, 1, 3]}'], {}), '(in_device, {(0): [0, 2, 1, 3]})\n', (42835, 42867), True, 'import oneflow as flow\n'), ((43000, 43041), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [1, 3]}'], {}), '(out_device, {(0): [1, 3]})\n', (43014, 43041), True, 'import oneflow as flow\n'), ((44568, 44590), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (44579, 44590), True, 'import oneflow as flow\n'), ((44604, 44658), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (44615, 44658), True, 'import oneflow as flow\n'), ((44675, 44721), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 2, 1, 3]}'], {}), '(in_device, {(0): [0, 2, 1, 3]})\n', (44689, 44721), True, 'import oneflow as flow\n'), ((44854, 44895), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [1, 3]}'], {}), '(out_device, {(0): [1, 3]})\n', (44868, 44895), True, 'import oneflow as flow\n'), ((46421, 46443), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (46432, 46443), True, 'import oneflow as flow\n'), ((46457, 46511), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (46468, 46511), True, 'import oneflow as flow\n'), ((46528, 46571), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (46542, 46571), True, 'import oneflow as flow\n'), ((46652, 46699), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [0, 1, 2, 3]}'], {}), '(out_device, {(0): [0, 1, 2, 3]})\n', (46666, 46699), True, 'import oneflow as flow\n'), ((48492, 48514), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (48503, 48514), True, 'import oneflow as flow\n'), ((48528, 48582), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (48539, 48582), True, 'import oneflow as flow\n'), ((48599, 48642), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (48613, 48642), True, 'import oneflow as flow\n'), ((48721, 48768), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [0, 1, 2, 3]}'], {}), '(out_device, {(0): [0, 1, 2, 3]})\n', (48735, 48768), True, 'import oneflow as flow\n'), ((50547, 50569), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (50558, 50569), True, 'import oneflow as flow\n'), ((50583, 50637), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (50594, 50637), True, 'import oneflow as flow\n'), ((50654, 50697), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (50668, 50697), True, 'import oneflow as flow\n'), ((50775, 50822), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [0, 1, 2, 3]}'], {}), '(out_device, {(0): [0, 1, 2, 3]})\n', (50789, 50822), True, 'import oneflow as flow\n'), ((53444, 53466), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (53455, 53466), True, 'import oneflow as flow\n'), ((53480, 53534), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (53491, 53534), True, 'import oneflow as flow\n'), ((53551, 53594), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (53565, 53594), True, 'import oneflow as flow\n'), ((53726, 53773), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [0, 1, 2, 3]}'], {}), '(out_device, {(0): [0, 1, 2, 3]})\n', (53740, 53773), True, 'import oneflow as flow\n'), ((55809, 55831), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (55820, 55831), True, 'import oneflow as flow\n'), ((55845, 55899), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (55856, 55899), True, 'import oneflow as flow\n'), ((55916, 55959), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (55930, 55959), True, 'import oneflow as flow\n'), ((56091, 56138), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [0, 1, 2, 3]}'], {}), '(out_device, {(0): [0, 1, 2, 3]})\n', (56105, 56138), True, 'import oneflow as flow\n'), ((60706, 60728), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (60717, 60728), True, 'import oneflow as flow\n'), ((60742, 60796), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (60753, 60796), True, 'import oneflow as flow\n'), ((60813, 60856), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (60827, 60856), True, 'import oneflow as flow\n'), ((60988, 61035), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [0, 1, 2, 3]}'], {}), '(out_device, {(0): [0, 1, 2, 3]})\n', (61002, 61035), True, 'import oneflow as flow\n'), ((63765, 63787), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (63776, 63787), True, 'import oneflow as flow\n'), ((63801, 63855), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (63812, 63855), True, 'import oneflow as flow\n'), ((63872, 63912), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1]}'], {}), '(in_device, {(0): [0, 1]})\n', (63886, 63912), True, 'import oneflow as flow\n'), ((64044, 64091), 'oneflow.placement', 'flow.placement', (['out_device', '{(0): [0, 1, 2, 3]}'], {}), '(out_device, {(0): [0, 1, 2, 3]})\n', (64058, 64091), True, 'import oneflow as flow\n'), ((67429, 67451), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (67440, 67451), True, 'import oneflow as flow\n'), ((67465, 67519), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (67476, 67519), True, 'import oneflow as flow\n'), ((67536, 67579), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (67550, 67579), True, 'import oneflow as flow\n'), ((70190, 70212), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (70201, 70212), True, 'import oneflow as flow\n'), ((70226, 70280), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (70237, 70280), True, 'import oneflow as flow\n'), ((70297, 70340), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (70311, 70340), True, 'import oneflow as flow\n'), ((72591, 72613), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (72602, 72613), True, 'import oneflow as flow\n'), ((72627, 72681), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (72638, 72681), True, 'import oneflow as flow\n'), ((72698, 72741), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (72712, 72741), True, 'import oneflow as flow\n'), ((76109, 76131), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (76120, 76131), True, 'import oneflow as flow\n'), ((76145, 76199), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (76156, 76199), True, 'import oneflow as flow\n'), ((76216, 76259), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (76230, 76259), True, 'import oneflow as flow\n'), ((79681, 79703), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (79692, 79703), True, 'import oneflow as flow\n'), ((79717, 79771), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (79728, 79771), True, 'import oneflow as flow\n'), ((79788, 79831), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (79802, 79831), True, 'import oneflow as flow\n'), ((82628, 82650), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (82639, 82650), True, 'import oneflow as flow\n'), ((82664, 82718), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (82675, 82718), True, 'import oneflow as flow\n'), ((82735, 82778), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (82749, 82778), True, 'import oneflow as flow\n'), ((86634, 86656), 'oneflow.device', 'flow.device', (['in_device'], {}), '(in_device)\n', (86645, 86656), True, 'import oneflow as flow\n'), ((86670, 86724), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device', 'dtype': 'flow.float32'}), '(np_arr, device=device, dtype=flow.float32)\n', (86681, 86724), True, 'import oneflow as flow\n'), ((86741, 86784), 'oneflow.placement', 'flow.placement', (['in_device', '{(0): [0, 1, 3]}'], {}), '(in_device, {(0): [0, 1, 3]})\n', (86755, 86784), True, 'import oneflow as flow\n'), ((89651, 89690), 'numpy.random.uniform', 'np.random.uniform', (['(-1e-05)', '(1e-05)', 'shape'], {}), '(-1e-05, 1e-05, shape)\n', (89668, 89690), True, 'import numpy as np\n'), ((89770, 89807), 'oneflow.env.all_device_placement', 'flow.env.all_device_placement', (['"""cuda"""'], {}), "('cuda')\n", (89799, 89807), True, 'import oneflow as flow\n'), ((89817, 89871), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': '"""cuda"""', 'dtype': 'flow.float32'}), "(np_arr, device='cuda', dtype=flow.float32)\n", (89828, 89871), True, 'import oneflow as flow\n'), ((89965, 90015), 'oneflow.placement', 'flow.placement', (['device_type', '{(0): in_device_list}'], {}), '(device_type, {(0): in_device_list})\n', (89979, 90015), True, 'import oneflow as flow\n'), ((90089, 90140), 'oneflow.placement', 'flow.placement', (['device_type', '{(0): out_device_list}'], {}), '(device_type, {(0): out_device_list})\n', (90103, 90140), True, 'import oneflow as flow\n'), ((89462, 89496), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (89471, 89496), False, 'import os\n'), ((91279, 91318), 'numpy.random.uniform', 'np.random.uniform', (['(-1e-05)', '(1e-05)', 'shape'], {}), '(-1e-05, 1e-05, shape)\n', (91296, 91318), True, 'import numpy as np\n'), ((91398, 91435), 'oneflow.env.all_device_placement', 'flow.env.all_device_placement', (['"""cuda"""'], {}), "('cuda')\n", (91427, 91435), True, 'import oneflow as flow\n'), ((91445, 91499), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': '"""cuda"""', 'dtype': 'flow.float32'}), "(np_arr, device='cuda', dtype=flow.float32)\n", (91456, 91499), True, 'import oneflow as flow\n'), ((91593, 91643), 'oneflow.placement', 'flow.placement', (['device_type', '{(0): in_device_list}'], {}), '(device_type, {(0): in_device_list})\n', (91607, 91643), True, 'import oneflow as flow\n'), ((91785, 91836), 'oneflow.placement', 'flow.placement', (['device_type', '{(0): out_device_list}'], {}), '(device_type, {(0): out_device_list})\n', (91799, 91836), True, 'import oneflow as flow\n'), ((91091, 91125), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (91100, 91125), False, 'import os\n'), ((92325, 92364), 'numpy.random.uniform', 'np.random.uniform', (['(-1e-05)', '(1e-05)', 'shape'], {}), '(-1e-05, 1e-05, shape)\n', (92342, 92364), True, 'import numpy as np\n'), ((92444, 92481), 'oneflow.env.all_device_placement', 'flow.env.all_device_placement', (['"""cuda"""'], {}), "('cuda')\n", (92473, 92481), True, 'import oneflow as flow\n'), ((92491, 92545), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': '"""cuda"""', 'dtype': 'flow.float32'}), "(np_arr, device='cuda', dtype=flow.float32)\n", (92502, 92545), True, 'import oneflow as flow\n'), ((92639, 92689), 'oneflow.placement', 'flow.placement', (['device_type', '{(0): in_device_list}'], {}), '(device_type, {(0): in_device_list})\n', (92653, 92689), True, 'import oneflow as flow\n'), ((92820, 92871), 'oneflow.placement', 'flow.placement', (['device_type', '{(0): out_device_list}'], {}), '(device_type, {(0): out_device_list})\n', (92834, 92871), True, 'import oneflow as flow\n'), ((92136, 92170), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (92145, 92170), False, 'import os\n'), ((93995, 94034), 'numpy.random.uniform', 'np.random.uniform', (['(-1e-05)', '(1e-05)', 'shape'], {}), '(-1e-05, 1e-05, shape)\n', (94012, 94034), True, 'import numpy as np\n'), ((94114, 94151), 'oneflow.env.all_device_placement', 'flow.env.all_device_placement', (['"""cuda"""'], {}), "('cuda')\n", (94143, 94151), True, 'import oneflow as flow\n'), ((94161, 94215), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': '"""cuda"""', 'dtype': 'flow.float32'}), "(np_arr, device='cuda', dtype=flow.float32)\n", (94172, 94215), True, 'import oneflow as flow\n'), ((94309, 94359), 'oneflow.placement', 'flow.placement', (['device_type', '{(0): in_device_list}'], {}), '(device_type, {(0): in_device_list})\n', (94323, 94359), True, 'import oneflow as flow\n'), ((94491, 94542), 'oneflow.placement', 'flow.placement', (['device_type', '{(0): out_device_list}'], {}), '(device_type, {(0): out_device_list})\n', (94505, 94542), True, 'import oneflow as flow\n'), ((93822, 93856), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (93831, 93856), False, 'import os\n'), ((95023, 95062), 'numpy.random.uniform', 'np.random.uniform', (['(-1e-05)', '(1e-05)', 'shape'], {}), '(-1e-05, 1e-05, shape)\n', (95040, 95062), True, 'import numpy as np\n'), ((95100, 95142), 'oneflow.env.all_device_placement', 'flow.env.all_device_placement', (['device_type'], {}), '(device_type)\n', (95129, 95142), True, 'import oneflow as flow\n'), ((95152, 95211), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'device': 'device_type', 'dtype': 'flow.float32'}), '(np_arr, device=device_type, dtype=flow.float32)\n', (95163, 95211), True, 'import oneflow as flow\n'), ((95306, 95356), 'oneflow.placement', 'flow.placement', (['device_type', '{(0): in_device_list}'], {}), '(device_type, {(0): in_device_list})\n', (95320, 95356), True, 'import oneflow as flow\n'), ((95497, 95548), 'oneflow.placement', 'flow.placement', (['device_type', '{(0): out_device_list}'], {}), '(device_type, {(0): out_device_list})\n', (95511, 95548), True, 'import oneflow as flow\n'), ((94788, 94822), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (94797, 94822), False, 'import os\n'), ((112498, 112532), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (112507, 112532), False, 'import os\n'), ((113192, 113226), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (113201, 113226), False, 'import os\n'), ((114079, 114113), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (114088, 114113), False, 'import os\n'), ((114986, 115025), 'numpy.random.uniform', 'np.random.uniform', (['(-1e-05)', '(1e-05)', 'shape'], {}), '(-1e-05, 1e-05, shape)\n', (115003, 115025), True, 'import numpy as np\n'), ((115117, 115202), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'dtype': 'flow.float32', 'device': 'device_type', 'requires_grad': '(False)'}), '(np_arr, dtype=flow.float32, device=device_type, requires_grad=False\n )\n', (115128, 115202), True, 'import oneflow as flow\n'), ((116684, 116718), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (116693, 116718), False, 'import os\n'), ((117211, 117229), 'numpy.random.seed', 'np.random.seed', (['(10)'], {}), '(10)\n', (117225, 117229), True, 'import numpy as np\n'), ((117243, 117285), 'numpy.random.uniform', 'np.random.uniform', (['(-1e-05)', '(1e-05)', '(16, 32)'], {}), '(-1e-05, 1e-05, (16, 32))\n', (117260, 117285), True, 'import numpy as np\n'), ((117303, 117350), 'oneflow.placement', 'flow.placement', (['device_type', '{(0): [0]}', '(1, 1)'], {}), '(device_type, {(0): [0]}, (1, 1))\n', (117317, 117350), True, 'import oneflow as flow\n'), ((117535, 117625), 'oneflow.tensor', 'flow.tensor', (['np_arr'], {'placement': 'placement0', 'sbp': '[src_sbp, src_sbp]', 'requires_grad': '(False)'}), '(np_arr, placement=placement0, sbp=[src_sbp, src_sbp],\n requires_grad=False)\n', (117546, 117625), True, 'import oneflow as flow\n'), ((118106, 118140), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (118115, 118140), False, 'import os\n'), ((118860, 118913), 'oneflow.placement', 'flow.placement', (['in_device_type', '{(0): in_device_list}'], {}), '(in_device_type, {(0): in_device_list})\n', (118874, 118913), True, 'import oneflow as flow\n'), ((118932, 118987), 'oneflow.placement', 'flow.placement', (['out_device_type', '{(0): out_device_list}'], {}), '(out_device_type, {(0): out_device_list})\n', (118946, 118987), True, 'import oneflow as flow\n'), ((118994, 119049), 'oneflow.Tensor', 'flow.Tensor', (['*shape'], {'placement': 'in_placement', 'sbp': 'in_sbp'}), '(*shape, placement=in_placement, sbp=in_sbp)\n', (119005, 119049), True, 'import oneflow as flow\n'), ((120239, 120254), 'unittest.main', 'unittest.main', ([], {}), '()\n', (120252, 120254), False, 'import unittest\n'), ((866, 885), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (883, 885), True, 'import oneflow as flow\n'), ((909, 999), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (917, 999), True, 'import numpy as np\n'), ((1834, 1851), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (1848, 1851), True, 'import oneflow as flow\n'), ((1914, 1933), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (1931, 1933), True, 'import oneflow as flow\n'), ((2152, 2171), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (2169, 2171), True, 'import oneflow as flow\n'), ((2495, 2514), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (2512, 2514), True, 'import oneflow as flow\n'), ((2538, 2628), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (2546, 2628), True, 'import numpy as np\n'), ((3461, 3478), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (3475, 3478), True, 'import oneflow as flow\n'), ((3541, 3560), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (3558, 3560), True, 'import oneflow as flow\n'), ((3774, 3793), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (3791, 3793), True, 'import oneflow as flow\n'), ((4114, 4133), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (4131, 4133), True, 'import oneflow as flow\n'), ((4157, 4247), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (4165, 4247), True, 'import numpy as np\n'), ((4961, 4978), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (4975, 4978), True, 'import oneflow as flow\n'), ((5079, 5096), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (5093, 5096), True, 'import oneflow as flow\n'), ((5159, 5178), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (5176, 5178), True, 'import oneflow as flow\n'), ((5483, 5502), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (5500, 5502), True, 'import oneflow as flow\n'), ((6129, 6148), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (6146, 6148), True, 'import oneflow as flow\n'), ((6172, 6262), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (6180, 6262), True, 'import numpy as np\n'), ((6976, 6993), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (6990, 6993), True, 'import oneflow as flow\n'), ((7030, 7047), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (7044, 7047), True, 'import oneflow as flow\n'), ((7148, 7165), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (7162, 7165), True, 'import oneflow as flow\n'), ((7228, 7247), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (7245, 7247), True, 'import oneflow as flow\n'), ((7552, 7571), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (7569, 7571), True, 'import oneflow as flow\n'), ((8198, 8217), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (8215, 8217), True, 'import oneflow as flow\n'), ((8241, 8331), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (8249, 8331), True, 'import numpy as np\n'), ((9045, 9062), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (9059, 9062), True, 'import oneflow as flow\n'), ((9099, 9116), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (9113, 9116), True, 'import oneflow as flow\n'), ((9217, 9234), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (9231, 9234), True, 'import oneflow as flow\n'), ((9297, 9316), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (9314, 9316), True, 'import oneflow as flow\n'), ((9613, 9632), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (9630, 9632), True, 'import oneflow as flow\n'), ((10036, 10055), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (10053, 10055), True, 'import oneflow as flow\n'), ((10079, 10169), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (10087, 10169), True, 'import numpy as np\n'), ((10883, 10900), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (10897, 10900), True, 'import oneflow as flow\n'), ((10937, 10954), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (10951, 10954), True, 'import oneflow as flow\n'), ((11136, 11155), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (11153, 11155), True, 'import oneflow as flow\n'), ((11725, 11744), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (11742, 11744), True, 'import oneflow as flow\n'), ((12419, 12438), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (12436, 12438), True, 'import oneflow as flow\n'), ((12462, 12552), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (12470, 12552), True, 'import numpy as np\n'), ((13266, 13283), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (13280, 13283), True, 'import oneflow as flow\n'), ((13320, 13337), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (13334, 13337), True, 'import oneflow as flow\n'), ((13521, 13540), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (13538, 13540), True, 'import oneflow as flow\n'), ((14107, 14126), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (14124, 14126), True, 'import oneflow as flow\n'), ((14796, 14815), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (14813, 14815), True, 'import oneflow as flow\n'), ((14839, 14929), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (14847, 14929), True, 'import numpy as np\n'), ((15767, 15784), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (15781, 15784), True, 'import oneflow as flow\n'), ((15847, 15866), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (15864, 15866), True, 'import oneflow as flow\n'), ((16088, 16107), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (16105, 16107), True, 'import oneflow as flow\n'), ((16430, 16449), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (16447, 16449), True, 'import oneflow as flow\n'), ((16473, 16563), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (16481, 16563), True, 'import numpy as np\n'), ((17399, 17416), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (17413, 17416), True, 'import oneflow as flow\n'), ((17479, 17498), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (17496, 17498), True, 'import oneflow as flow\n'), ((17712, 17731), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (17729, 17731), True, 'import oneflow as flow\n'), ((18048, 18067), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (18065, 18067), True, 'import oneflow as flow\n'), ((18091, 18181), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (18099, 18181), True, 'import numpy as np\n'), ((18898, 18915), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (18912, 18915), True, 'import oneflow as flow\n'), ((19016, 19033), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (19030, 19033), True, 'import oneflow as flow\n'), ((19096, 19115), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (19113, 19115), True, 'import oneflow as flow\n'), ((19762, 19781), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (19779, 19781), True, 'import oneflow as flow\n'), ((20532, 20551), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (20549, 20551), True, 'import oneflow as flow\n'), ((20575, 20689), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (20583, 20689), True, 'import numpy as np\n'), ((21831, 21848), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (21845, 21848), True, 'import oneflow as flow\n'), ((21885, 21902), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (21899, 21902), True, 'import oneflow as flow\n'), ((22003, 22020), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (22017, 22020), True, 'import oneflow as flow\n'), ((22083, 22102), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (22100, 22102), True, 'import oneflow as flow\n'), ((22787, 22806), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (22804, 22806), True, 'import oneflow as flow\n'), ((23592, 23611), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (23609, 23611), True, 'import oneflow as flow\n'), ((23635, 23749), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (23643, 23749), True, 'import numpy as np\n'), ((24891, 24908), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (24905, 24908), True, 'import oneflow as flow\n'), ((24945, 24962), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (24959, 24962), True, 'import oneflow as flow\n'), ((25063, 25080), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (25077, 25080), True, 'import oneflow as flow\n'), ((25143, 25162), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (25160, 25162), True, 'import oneflow as flow\n'), ((25693, 25712), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (25710, 25712), True, 'import oneflow as flow\n'), ((26339, 26358), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (26356, 26358), True, 'import oneflow as flow\n'), ((26382, 26496), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (26390, 26496), True, 'import numpy as np\n'), ((27638, 27655), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (27652, 27655), True, 'import oneflow as flow\n'), ((27692, 27709), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (27706, 27709), True, 'import oneflow as flow\n'), ((27891, 27910), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (27908, 27910), True, 'import oneflow as flow\n'), ((28705, 28724), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (28722, 28724), True, 'import oneflow as flow\n'), ((29620, 29639), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (29637, 29639), True, 'import oneflow as flow\n'), ((29663, 29777), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (29671, 29777), True, 'import numpy as np\n'), ((30919, 30936), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (30933, 30936), True, 'import oneflow as flow\n'), ((30973, 30990), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (30987, 30990), True, 'import oneflow as flow\n'), ((31174, 31193), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (31191, 31193), True, 'import oneflow as flow\n'), ((31984, 32003), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (32001, 32003), True, 'import oneflow as flow\n'), ((32911, 32930), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (32928, 32930), True, 'import oneflow as flow\n'), ((32954, 33044), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (32962, 33044), True, 'import numpy as np\n'), ((33882, 33899), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (33896, 33899), True, 'import oneflow as flow\n'), ((33962, 33981), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (33979, 33981), True, 'import oneflow as flow\n'), ((34203, 34222), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (34220, 34222), True, 'import oneflow as flow\n'), ((34558, 34577), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (34575, 34577), True, 'import oneflow as flow\n'), ((34601, 34691), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (34609, 34691), True, 'import numpy as np\n'), ((35527, 35544), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (35541, 35544), True, 'import oneflow as flow\n'), ((35607, 35626), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (35624, 35626), True, 'import oneflow as flow\n'), ((35840, 35859), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (35857, 35859), True, 'import oneflow as flow\n'), ((36189, 36208), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (36206, 36208), True, 'import oneflow as flow\n'), ((36232, 36322), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (36240, 36322), True, 'import numpy as np\n'), ((37039, 37056), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (37053, 37056), True, 'import oneflow as flow\n'), ((37157, 37174), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (37171, 37174), True, 'import oneflow as flow\n'), ((37237, 37256), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (37254, 37256), True, 'import oneflow as flow\n'), ((37903, 37922), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (37920, 37922), True, 'import oneflow as flow\n'), ((38686, 38705), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (38703, 38705), True, 'import oneflow as flow\n'), ((38729, 38819), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (38737, 38819), True, 'import numpy as np\n'), ((39594, 39611), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (39608, 39611), True, 'import oneflow as flow\n'), ((39712, 39729), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (39726, 39729), True, 'import oneflow as flow\n'), ((39792, 39811), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (39809, 39811), True, 'import oneflow as flow\n'), ((40025, 40044), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (40042, 40044), True, 'import oneflow as flow\n'), ((40374, 40393), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (40391, 40393), True, 'import oneflow as flow\n'), ((40417, 40507), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (40425, 40507), True, 'import numpy as np\n'), ((41282, 41299), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (41296, 41299), True, 'import oneflow as flow\n'), ((41400, 41417), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (41414, 41417), True, 'import oneflow as flow\n'), ((41480, 41499), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (41497, 41499), True, 'import oneflow as flow\n'), ((41710, 41729), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (41727, 41729), True, 'import oneflow as flow\n'), ((42053, 42072), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (42070, 42072), True, 'import oneflow as flow\n'), ((42096, 42186), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (42104, 42186), True, 'import numpy as np\n'), ((42961, 42978), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (42975, 42978), True, 'import oneflow as flow\n'), ((43162, 43181), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (43179, 43181), True, 'import oneflow as flow\n'), ((43477, 43496), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (43494, 43496), True, 'import oneflow as flow\n'), ((43907, 43926), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (43924, 43926), True, 'import oneflow as flow\n'), ((43950, 44040), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (43958, 44040), True, 'import numpy as np\n'), ((44815, 44832), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (44829, 44832), True, 'import oneflow as flow\n'), ((45014, 45033), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (45031, 45033), True, 'import oneflow as flow\n'), ((45330, 45349), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (45347, 45349), True, 'import oneflow as flow\n'), ((45760, 45779), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (45777, 45779), True, 'import oneflow as flow\n'), ((45803, 45893), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (45811, 45893), True, 'import numpy as np\n'), ((46737, 46754), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (46751, 46754), True, 'import oneflow as flow\n'), ((46817, 46836), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (46834, 46836), True, 'import oneflow as flow\n'), ((47042, 47061), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (47059, 47061), True, 'import oneflow as flow\n'), ((47267, 47286), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (47284, 47286), True, 'import oneflow as flow\n'), ((47492, 47511), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (47509, 47511), True, 'import oneflow as flow\n'), ((47831, 47850), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (47848, 47850), True, 'import oneflow as flow\n'), ((47874, 47964), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (47882, 47964), True, 'import numpy as np\n'), ((48806, 48823), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (48820, 48823), True, 'import oneflow as flow\n'), ((48886, 48905), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (48903, 48905), True, 'import oneflow as flow\n'), ((49107, 49126), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (49124, 49126), True, 'import oneflow as flow\n'), ((49328, 49347), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (49345, 49347), True, 'import oneflow as flow\n'), ((49549, 49568), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (49566, 49568), True, 'import oneflow as flow\n'), ((49886, 49905), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (49903, 49905), True, 'import oneflow as flow\n'), ((49929, 50019), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (49937, 50019), True, 'import numpy as np\n'), ((50736, 50753), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (50750, 50753), True, 'import oneflow as flow\n'), ((50860, 50877), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (50874, 50877), True, 'import oneflow as flow\n'), ((50940, 50959), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (50957, 50959), True, 'import oneflow as flow\n'), ((51259, 51278), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (51276, 51278), True, 'import oneflow as flow\n'), ((51579, 51598), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (51596, 51598), True, 'import oneflow as flow\n'), ((51900, 51919), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (51917, 51919), True, 'import oneflow as flow\n'), ((52334, 52353), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (52351, 52353), True, 'import oneflow as flow\n'), ((52377, 52491), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (52385, 52491), True, 'import numpy as np\n'), ((53633, 53650), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (53647, 53650), True, 'import oneflow as flow\n'), ((53687, 53704), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (53701, 53704), True, 'import oneflow as flow\n'), ((54699, 54718), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (54716, 54718), True, 'import oneflow as flow\n'), ((54742, 54856), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (54750, 54856), True, 'import numpy as np\n'), ((55998, 56015), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (56012, 56015), True, 'import oneflow as flow\n'), ((56052, 56069), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (56066, 56069), True, 'import oneflow as flow\n'), ((56259, 56278), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (56276, 56278), True, 'import oneflow as flow\n'), ((59596, 59615), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (59613, 59615), True, 'import oneflow as flow\n'), ((59639, 59753), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (59647, 59753), True, 'import numpy as np\n'), ((60895, 60912), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (60909, 60912), True, 'import oneflow as flow\n'), ((60949, 60966), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (60963, 60966), True, 'import oneflow as flow\n'), ((61073, 61090), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (61087, 61090), True, 'import oneflow as flow\n'), ((61153, 61172), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (61170, 61172), True, 'import oneflow as flow\n'), ((62555, 62574), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (62572, 62574), True, 'import oneflow as flow\n'), ((62598, 62736), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9, 5, 20], [6, 8, 9, 0, 4, 6, 9, 0], [3, 7, 5, 0, 3, 5, 0,\n 3], [6, 8, 9, 0, 8, 7, 8, 9]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9, 5, 20], [6, 8, 9, 0, 4, 6, 9, 0], [3, 7, 5, 0,\n 3, 5, 0, 3], [6, 8, 9, 0, 8, 7, 8, 9]], dtype=np.float32)\n', (62606, 62736), True, 'import numpy as np\n'), ((63951, 63968), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (63965, 63968), True, 'import oneflow as flow\n'), ((64005, 64022), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (64019, 64022), True, 'import oneflow as flow\n'), ((64129, 64146), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (64143, 64146), True, 'import oneflow as flow\n'), ((64209, 64228), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (64226, 64228), True, 'import oneflow as flow\n'), ((66031, 66050), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (66048, 66050), True, 'import oneflow as flow\n'), ((66074, 66228), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7], [6, 8, 9, 0, 4, 6], [6, 8, 6, 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7], [6, 8, 9, 0, 4, 6], [6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (66082, 66228), True, 'import numpy as np\n'), ((67675, 67692), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (67689, 67692), True, 'import oneflow as flow\n'), ((67751, 67770), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (67768, 67770), True, 'import oneflow as flow\n'), ((68070, 68089), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (68087, 68089), True, 'import oneflow as flow\n'), ((68387, 68406), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (68404, 68406), True, 'import oneflow as flow\n'), ((68792, 68811), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (68809, 68811), True, 'import oneflow as flow\n'), ((68835, 68989), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7], [6, 8, 9, 0, 4, 6], [6, 8, 6, 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7], [6, 8, 9, 0, 4, 6], [6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (68843, 68989), True, 'import numpy as np\n'), ((70434, 70451), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (70448, 70451), True, 'import oneflow as flow\n'), ((70510, 70529), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (70527, 70529), True, 'import oneflow as flow\n'), ((70797, 70816), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (70814, 70816), True, 'import oneflow as flow\n'), ((71105, 71124), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (71122, 71124), True, 'import oneflow as flow\n'), ((71481, 71500), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (71498, 71500), True, 'import oneflow as flow\n'), ((71524, 71638), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (71532, 71638), True, 'import numpy as np\n'), ((72780, 72797), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (72794, 72797), True, 'import oneflow as flow\n'), ((72834, 72851), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (72848, 72851), True, 'import oneflow as flow\n'), ((72910, 72929), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (72927, 72929), True, 'import oneflow as flow\n'), ((73576, 73595), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (73593, 73595), True, 'import oneflow as flow\n'), ((74244, 74263), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (74261, 74263), True, 'import oneflow as flow\n'), ((74999, 75018), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (75016, 75018), True, 'import oneflow as flow\n'), ((75042, 75156), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (75050, 75156), True, 'import numpy as np\n'), ((76298, 76315), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (76312, 76315), True, 'import oneflow as flow\n'), ((76352, 76369), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (76366, 76369), True, 'import oneflow as flow\n'), ((76406, 76423), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (76420, 76423), True, 'import oneflow as flow\n'), ((76482, 76501), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (76499, 76501), True, 'import oneflow as flow\n'), ((77148, 77167), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (77165, 77167), True, 'import oneflow as flow\n'), ((77816, 77835), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (77833, 77835), True, 'import oneflow as flow\n'), ((78571, 78590), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (78588, 78590), True, 'import oneflow as flow\n'), ((78614, 78728), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (78622, 78728), True, 'import numpy as np\n'), ((79870, 79887), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (79884, 79887), True, 'import oneflow as flow\n'), ((79924, 79941), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (79938, 79941), True, 'import oneflow as flow\n'), ((79978, 79995), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (79992, 79995), True, 'import oneflow as flow\n'), ((80054, 80073), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (80071, 80073), True, 'import oneflow as flow\n'), ((80512, 80531), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (80529, 80531), True, 'import oneflow as flow\n'), ((80973, 80992), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (80990, 80992), True, 'import oneflow as flow\n'), ((81518, 81537), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (81535, 81537), True, 'import oneflow as flow\n'), ((81561, 81675), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (81569, 81675), True, 'import numpy as np\n'), ((82817, 82834), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (82831, 82834), True, 'import oneflow as flow\n'), ((82871, 82888), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (82885, 82888), True, 'import oneflow as flow\n'), ((83004, 83023), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (83021, 83023), True, 'import oneflow as flow\n'), ((83814, 83833), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (83831, 83833), True, 'import oneflow as flow\n'), ((84626, 84645), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (84643, 84645), True, 'import oneflow as flow\n'), ((85524, 85543), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (85541, 85543), True, 'import oneflow as flow\n'), ((85567, 85681), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (85575, 85681), True, 'import numpy as np\n'), ((86823, 86840), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (86837, 86840), True, 'import oneflow as flow\n'), ((86877, 86894), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (86891, 86894), True, 'import oneflow as flow\n'), ((87008, 87027), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (87025, 87027), True, 'import oneflow as flow\n'), ((87822, 87841), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (87839, 87841), True, 'import oneflow as flow\n'), ((88636, 88655), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (88653, 88655), True, 'import oneflow as flow\n'), ((90178, 90208), 'oneflow.sbp.split', 'flow.sbp.split', (['out_split_axis'], {}), '(out_split_axis)\n', (90192, 90208), True, 'import oneflow as flow\n'), ((90218, 90237), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (90235, 90237), True, 'import oneflow as flow\n'), ((91733, 91762), 'oneflow.sbp.split', 'flow.sbp.split', (['in_split_axis'], {}), '(in_split_axis)\n', (91747, 91762), True, 'import oneflow as flow\n'), ((91902, 91921), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (91919, 91921), True, 'import oneflow as flow\n'), ((92909, 92939), 'oneflow.sbp.split', 'flow.sbp.split', (['out_split_axis'], {}), '(out_split_axis)\n', (92923, 92939), True, 'import oneflow as flow\n'), ((92949, 92968), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (92966, 92968), True, 'import oneflow as flow\n'), ((94608, 94627), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (94625, 94627), True, 'import oneflow as flow\n'), ((95445, 95474), 'oneflow.sbp.split', 'flow.sbp.split', (['in_split_axis'], {}), '(in_split_axis)\n', (95459, 95474), True, 'import oneflow as flow\n'), ((95586, 95616), 'oneflow.sbp.split', 'flow.sbp.split', (['out_split_axis'], {}), '(out_split_axis)\n', (95600, 95616), True, 'import oneflow as flow\n'), ((95626, 95645), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (95643, 95645), True, 'import oneflow as flow\n'), ((96740, 96753), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (96751, 96753), False, 'from collections import OrderedDict\n'), ((96870, 96890), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (96880, 96890), False, 'from test_util import GenArgList\n'), ((97076, 97089), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (97087, 97089), False, 'from collections import OrderedDict\n'), ((97206, 97226), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (97216, 97226), False, 'from test_util import GenArgList\n'), ((97413, 97426), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (97424, 97426), False, 'from collections import OrderedDict\n'), ((97543, 97563), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (97553, 97563), False, 'from test_util import GenArgList\n'), ((97751, 97764), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (97762, 97764), False, 'from collections import OrderedDict\n'), ((97881, 97901), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (97891, 97901), False, 'from test_util import GenArgList\n'), ((98089, 98102), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (98100, 98102), False, 'from collections import OrderedDict\n'), ((98219, 98239), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (98229, 98239), False, 'from test_util import GenArgList\n'), ((98426, 98439), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (98437, 98439), False, 'from collections import OrderedDict\n'), ((98556, 98576), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (98566, 98576), False, 'from test_util import GenArgList\n'), ((98842, 98855), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (98853, 98855), False, 'from collections import OrderedDict\n'), ((98972, 98992), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (98982, 98992), False, 'from test_util import GenArgList\n'), ((98687, 98721), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (98696, 98721), False, 'import os\n'), ((99280, 99293), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (99291, 99293), False, 'from collections import OrderedDict\n'), ((99410, 99430), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (99420, 99430), False, 'from test_util import GenArgList\n'), ((99608, 99621), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (99619, 99621), False, 'from collections import OrderedDict\n'), ((99738, 99758), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (99748, 99758), False, 'from test_util import GenArgList\n'), ((99937, 99950), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (99948, 99950), False, 'from collections import OrderedDict\n'), ((100067, 100087), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (100077, 100087), False, 'from test_util import GenArgList\n'), ((100267, 100280), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (100278, 100280), False, 'from collections import OrderedDict\n'), ((100397, 100417), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (100407, 100417), False, 'from test_util import GenArgList\n'), ((100597, 100610), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (100608, 100610), False, 'from collections import OrderedDict\n'), ((100727, 100747), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (100737, 100747), False, 'from test_util import GenArgList\n'), ((100926, 100939), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (100937, 100939), False, 'from collections import OrderedDict\n'), ((101056, 101076), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (101066, 101076), False, 'from test_util import GenArgList\n'), ((101334, 101347), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (101345, 101347), False, 'from collections import OrderedDict\n'), ((101464, 101484), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (101474, 101484), False, 'from test_util import GenArgList\n'), ((101183, 101217), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (101192, 101217), False, 'import os\n'), ((101791, 101804), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (101802, 101804), False, 'from collections import OrderedDict\n'), ((101921, 101941), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (101931, 101941), False, 'from test_util import GenArgList\n'), ((102175, 102188), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (102186, 102188), False, 'from collections import OrderedDict\n'), ((102305, 102325), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (102315, 102325), False, 'from test_util import GenArgList\n'), ((102560, 102573), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (102571, 102573), False, 'from collections import OrderedDict\n'), ((102690, 102710), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (102700, 102710), False, 'from test_util import GenArgList\n'), ((102946, 102959), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (102957, 102959), False, 'from collections import OrderedDict\n'), ((103076, 103096), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (103086, 103096), False, 'from test_util import GenArgList\n'), ((103332, 103345), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (103343, 103345), False, 'from collections import OrderedDict\n'), ((103462, 103482), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (103472, 103482), False, 'from test_util import GenArgList\n'), ((103797, 103810), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (103808, 103810), False, 'from collections import OrderedDict\n'), ((103927, 103947), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (103937, 103947), False, 'from test_util import GenArgList\n'), ((103633, 103667), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (103642, 103667), False, 'import os\n'), ((104181, 104194), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (104192, 104194), False, 'from collections import OrderedDict\n'), ((104311, 104331), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (104321, 104331), False, 'from test_util import GenArgList\n'), ((104681, 104694), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (104692, 104694), False, 'from collections import OrderedDict\n'), ((104811, 104831), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (104821, 104831), False, 'from test_util import GenArgList\n'), ((105065, 105078), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (105076, 105078), False, 'from collections import OrderedDict\n'), ((105195, 105215), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (105205, 105215), False, 'from test_util import GenArgList\n'), ((105450, 105463), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (105461, 105463), False, 'from collections import OrderedDict\n'), ((105580, 105600), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (105590, 105600), False, 'from test_util import GenArgList\n'), ((105835, 105848), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (105846, 105848), False, 'from collections import OrderedDict\n'), ((105965, 105985), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (105975, 105985), False, 'from test_util import GenArgList\n'), ((106299, 106312), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (106310, 106312), False, 'from collections import OrderedDict\n'), ((106429, 106449), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (106439, 106449), False, 'from test_util import GenArgList\n'), ((106135, 106169), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (106144, 106169), False, 'import os\n'), ((106684, 106697), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (106695, 106697), False, 'from collections import OrderedDict\n'), ((106814, 106834), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (106824, 106834), False, 'from test_util import GenArgList\n'), ((107070, 107083), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (107081, 107083), False, 'from collections import OrderedDict\n'), ((107200, 107220), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (107210, 107220), False, 'from test_util import GenArgList\n'), ((107540, 107553), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (107551, 107553), False, 'from collections import OrderedDict\n'), ((107670, 107690), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (107680, 107690), False, 'from test_util import GenArgList\n'), ((107935, 107948), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (107946, 107948), False, 'from collections import OrderedDict\n'), ((108065, 108085), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (108075, 108085), False, 'from test_util import GenArgList\n'), ((107791, 107825), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (107800, 107825), False, 'import os\n'), ((108249, 108262), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (108260, 108262), False, 'from collections import OrderedDict\n'), ((108379, 108399), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (108389, 108399), False, 'from test_util import GenArgList\n'), ((108564, 108577), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (108575, 108577), False, 'from collections import OrderedDict\n'), ((108694, 108714), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (108704, 108714), False, 'from test_util import GenArgList\n'), ((108880, 108893), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (108891, 108893), False, 'from collections import OrderedDict\n'), ((109010, 109030), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (109020, 109030), False, 'from test_util import GenArgList\n'), ((109195, 109208), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (109206, 109208), False, 'from collections import OrderedDict\n'), ((109325, 109345), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (109335, 109345), False, 'from test_util import GenArgList\n'), ((109589, 109602), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (109600, 109602), False, 'from collections import OrderedDict\n'), ((109719, 109739), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (109729, 109739), False, 'from test_util import GenArgList\n'), ((109445, 109479), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (109454, 109479), False, 'import os\n'), ((109968, 109981), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (109979, 109981), False, 'from collections import OrderedDict\n'), ((110259, 110279), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (110269, 110279), False, 'from test_util import GenArgList\n'), ((110487, 110500), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (110498, 110500), False, 'from collections import OrderedDict\n'), ((110778, 110798), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (110788, 110798), False, 'from test_util import GenArgList\n'), ((111006, 111019), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (111017, 111019), False, 'from collections import OrderedDict\n'), ((111300, 111320), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (111310, 111320), False, 'from test_util import GenArgList\n'), ((111528, 111541), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (111539, 111541), False, 'from collections import OrderedDict\n'), ((111779, 111799), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (111789, 111799), False, 'from test_util import GenArgList\n'), ((112018, 112031), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (112029, 112031), False, 'from collections import OrderedDict\n'), ((112362, 112382), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (112372, 112382), False, 'from test_util import GenArgList\n'), ((112722, 112753), 'numpy.ones', 'np.ones', (['(4, 8)'], {'dtype': 'np.int32'}), '((4, 8), dtype=np.int32)\n', (112729, 112753), True, 'import numpy as np\n'), ((113387, 113418), 'numpy.ones', 'np.ones', (['(4, 8)'], {'dtype': 'np.int32'}), '((4, 8), dtype=np.int32)\n', (113394, 113418), True, 'import numpy as np\n'), ((114274, 114305), 'numpy.ones', 'np.ones', (['(4, 8)'], {'dtype': 'np.int32'}), '((4, 8), dtype=np.int32)\n', (114281, 114305), True, 'import numpy as np\n'), ((115521, 115546), 'oneflow.env.get_world_size', 'flow.env.get_world_size', ([], {}), '()\n', (115544, 115546), True, 'import oneflow as flow\n'), ((115600, 115619), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (115617, 115619), True, 'import oneflow as flow\n'), ((116040, 116065), 'oneflow.env.get_world_size', 'flow.env.get_world_size', ([], {}), '()\n', (116063, 116065), True, 'import oneflow as flow\n'), ((116119, 116138), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (116136, 116138), True, 'import oneflow as flow\n'), ((116895, 116908), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (116906, 116908), False, 'from collections import OrderedDict\n'), ((117027, 117047), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (117037, 117047), False, 'from test_util import GenArgList\n'), ((118310, 118323), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (118321, 118323), False, 'from collections import OrderedDict\n'), ((118571, 118591), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (118581, 118591), False, 'from test_util import GenArgList\n'), ((119408, 119421), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (119419, 119421), False, 'from collections import OrderedDict\n'), ((120115, 120135), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (120125, 120135), False, 'from test_util import GenArgList\n'), ((1027, 1046), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (1044, 1046), True, 'import oneflow as flow\n'), ((1070, 1162), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (1078, 1162), True, 'import numpy as np\n'), ((2656, 2675), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (2673, 2675), True, 'import oneflow as flow\n'), ((2699, 2791), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (2707, 2791), True, 'import numpy as np\n'), ((4275, 4294), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (4292, 4294), True, 'import oneflow as flow\n'), ((4318, 4410), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (4326, 4410), True, 'import numpy as np\n'), ((6290, 6309), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (6307, 6309), True, 'import oneflow as flow\n'), ((6333, 6425), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (6341, 6425), True, 'import numpy as np\n'), ((8359, 8378), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (8376, 8378), True, 'import oneflow as flow\n'), ((8402, 8494), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (8410, 8494), True, 'import numpy as np\n'), ((10197, 10216), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (10214, 10216), True, 'import oneflow as flow\n'), ((10240, 10332), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (10248, 10332), True, 'import numpy as np\n'), ((12580, 12599), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (12597, 12599), True, 'import oneflow as flow\n'), ((12623, 12715), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (12631, 12715), True, 'import numpy as np\n'), ((14957, 14976), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (14974, 14976), True, 'import oneflow as flow\n'), ((15000, 15092), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (15008, 15092), True, 'import numpy as np\n'), ((16591, 16610), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (16608, 16610), True, 'import oneflow as flow\n'), ((16634, 16726), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (16642, 16726), True, 'import numpy as np\n'), ((18209, 18228), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (18226, 18228), True, 'import oneflow as flow\n'), ((18252, 18344), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (18260, 18344), True, 'import numpy as np\n'), ((20808, 20827), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (20825, 20827), True, 'import oneflow as flow\n'), ((20851, 20968), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (20859, 20968), True, 'import numpy as np\n'), ((23868, 23887), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (23885, 23887), True, 'import oneflow as flow\n'), ((23911, 24028), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (23919, 24028), True, 'import numpy as np\n'), ((26615, 26634), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (26632, 26634), True, 'import oneflow as flow\n'), ((26658, 26775), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (26666, 26775), True, 'import numpy as np\n'), ((29896, 29915), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (29913, 29915), True, 'import oneflow as flow\n'), ((29939, 30056), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (29947, 30056), True, 'import numpy as np\n'), ((33072, 33091), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (33089, 33091), True, 'import oneflow as flow\n'), ((33115, 33207), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (33123, 33207), True, 'import numpy as np\n'), ((34719, 34738), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (34736, 34738), True, 'import oneflow as flow\n'), ((34762, 34854), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (34770, 34854), True, 'import numpy as np\n'), ((36350, 36369), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (36367, 36369), True, 'import oneflow as flow\n'), ((36393, 36485), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (36401, 36485), True, 'import numpy as np\n'), ((38847, 38866), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (38864, 38866), True, 'import oneflow as flow\n'), ((38890, 38982), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (38898, 38982), True, 'import numpy as np\n'), ((40535, 40554), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (40552, 40554), True, 'import oneflow as flow\n'), ((40578, 40670), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (40586, 40670), True, 'import numpy as np\n'), ((42214, 42233), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (42231, 42233), True, 'import oneflow as flow\n'), ((42257, 42349), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (42265, 42349), True, 'import numpy as np\n'), ((44068, 44087), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (44085, 44087), True, 'import oneflow as flow\n'), ((44111, 44203), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (44119, 44203), True, 'import numpy as np\n'), ((45921, 45940), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (45938, 45940), True, 'import oneflow as flow\n'), ((45964, 46056), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (45972, 46056), True, 'import numpy as np\n'), ((47992, 48011), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (48009, 48011), True, 'import oneflow as flow\n'), ((48035, 48127), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (48043, 48127), True, 'import numpy as np\n'), ((50047, 50066), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (50064, 50066), True, 'import oneflow as flow\n'), ((50090, 50182), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (50098, 50182), True, 'import numpy as np\n'), ((52610, 52629), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (52627, 52629), True, 'import oneflow as flow\n'), ((52653, 52770), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (52661, 52770), True, 'import numpy as np\n'), ((53981, 54268), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6],\n [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2,\n 5, 2], [3, 7, 5, 8, 9, 3]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9,\n 8, 6], [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, \n 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]], dtype=np.float32)\n', (53989, 54268), True, 'import numpy as np\n'), ((54975, 54994), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (54992, 54994), True, 'import oneflow as flow\n'), ((55018, 55135), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (55026, 55135), True, 'import numpy as np\n'), ((57071, 57090), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (57088, 57090), True, 'import oneflow as flow\n'), ((59872, 59891), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (59889, 59891), True, 'import oneflow as flow\n'), ((59915, 60032), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (59923, 60032), True, 'import numpy as np\n'), ((61475, 61494), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (61492, 61494), True, 'import oneflow as flow\n'), ((62856, 62875), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (62873, 62875), True, 'import oneflow as flow\n'), ((62899, 63042), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3, 10, 7], [3, 9, 10, 5, 5, 6, 9, 10], [4, 6, 6, 9, 8, \n 6, 6, 9], [6, 8, 6, 4, 5, 3, 8, 6]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3, 10, 7], [3, 9, 10, 5, 5, 6, 9, 10], [4, 6, \n 6, 9, 8, 6, 6, 9], [6, 8, 6, 4, 5, 3, 8, 6]], dtype=np.float32)\n', (62907, 63042), True, 'import numpy as np\n'), ((64535, 64554), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (64552, 64554), True, 'import oneflow as flow\n'), ((66379, 66398), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (66396, 66398), True, 'import oneflow as flow\n'), ((66422, 66584), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3], [4, 9, 7, 0, 2, 1], [6, 3, 9, 2, 5, 2]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3], [4, 9, 7, 0, 2, 1], [6, 3, 9, 2, 5, 2]], dtype=np.\n float32)\n', (66430, 66584), True, 'import numpy as np\n'), ((69140, 69159), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (69157, 69159), True, 'import oneflow as flow\n'), ((69183, 69345), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3], [4, 9, 7, 0, 2, 1], [6, 3, 9, 2, 5, 2]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3], [4, 9, 7, 0, 2, 1], [6, 3, 9, 2, 5, 2]], dtype=np.\n float32)\n', (69191, 69345), True, 'import numpy as np\n'), ((71757, 71776), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (71774, 71776), True, 'import oneflow as flow\n'), ((71800, 71917), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (71808, 71917), True, 'import numpy as np\n'), ((75275, 75294), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (75292, 75294), True, 'import oneflow as flow\n'), ((75318, 75435), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (75326, 75435), True, 'import numpy as np\n'), ((78847, 78866), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (78864, 78866), True, 'import oneflow as flow\n'), ((78890, 79007), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (78898, 79007), True, 'import numpy as np\n'), ((81794, 81813), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (81811, 81813), True, 'import oneflow as flow\n'), ((81837, 81954), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (81845, 81954), True, 'import numpy as np\n'), ((85800, 85819), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (85817, 85819), True, 'import oneflow as flow\n'), ((85843, 85960), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (85851, 85960), True, 'import numpy as np\n'), ((90294, 90313), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (90311, 90313), True, 'import oneflow as flow\n'), ((93025, 93044), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (93042, 93044), True, 'import oneflow as flow\n'), ((95702, 95721), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (95719, 95721), True, 'import oneflow as flow\n'), ((118425, 118442), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (118439, 118442), True, 'import oneflow as flow\n'), ((118444, 118461), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (118458, 118461), True, 'import oneflow as flow\n'), ((118514, 118531), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (118528, 118531), True, 'import oneflow as flow\n'), ((118533, 118550), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (118547, 118550), True, 'import oneflow as flow\n'), ((1202, 1221), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (1219, 1221), True, 'import oneflow as flow\n'), ((1245, 1335), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (1253, 1335), True, 'import numpy as np\n'), ((2052, 2117), 'numpy.array', 'np.array', (['[[6, 16], [9, 17], [7, 13], [12, 16]]'], {'dtype': 'np.float32'}), '([[6, 16], [9, 17], [7, 13], [12, 16]], dtype=np.float32)\n', (2060, 2117), True, 'import numpy as np\n'), ((2290, 2355), 'numpy.array', 'np.array', (['[[15, 27], [19, 5], [11, 9], [15, 4]]'], {'dtype': 'np.float32'}), '([[15, 27], [19, 5], [11, 9], [15, 4]], dtype=np.float32)\n', (2298, 2355), True, 'import numpy as np\n'), ((2831, 2850), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (2848, 2850), True, 'import oneflow as flow\n'), ((2874, 2964), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (2882, 2964), True, 'import numpy as np\n'), ((3679, 3739), 'numpy.array', 'np.array', (['[[4, 6], [6, 8], [3, 7], [6, 8]]'], {'dtype': 'np.float32'}), '([[4, 6], [6, 8], [3, 7], [6, 8]], dtype=np.float32)\n', (3687, 3739), True, 'import numpy as np\n'), ((3912, 3973), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [5, 0], [9, 0]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [5, 0], [9, 0]], dtype=np.float32)\n', (3920, 3973), True, 'import numpy as np\n'), ((4450, 4469), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (4467, 4469), True, 'import oneflow as flow\n'), ((4493, 4583), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (4501, 4583), True, 'import numpy as np\n'), ((5297, 5394), 'numpy.array', 'np.array', (['[[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8]]'], {'dtype': 'np.float32'}), '([[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8]],\n dtype=np.float32)\n', (5305, 5394), True, 'import numpy as np\n'), ((5621, 5721), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4]\n ], dtype=np.float32)\n', (5629, 5721), True, 'import numpy as np\n'), ((6465, 6484), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (6482, 6484), True, 'import oneflow as flow\n'), ((6508, 6598), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (6516, 6598), True, 'import numpy as np\n'), ((7366, 7463), 'numpy.array', 'np.array', (['[[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8]]'], {'dtype': 'np.float32'}), '([[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8]],\n dtype=np.float32)\n', (7374, 7463), True, 'import numpy as np\n'), ((7690, 7790), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4]\n ], dtype=np.float32)\n', (7698, 7790), True, 'import numpy as np\n'), ((8534, 8553), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (8551, 8553), True, 'import oneflow as flow\n'), ((8577, 8667), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (8585, 8667), True, 'import numpy as np\n'), ((9435, 9525), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (9443, 9525), True, 'import numpy as np\n'), ((9751, 9843), 'numpy.array', 'np.array', (['[[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype\n =np.float32)\n', (9759, 9843), True, 'import numpy as np\n'), ((10372, 10391), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (10389, 10391), True, 'import oneflow as flow\n'), ((10415, 10505), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (10423, 10505), True, 'import numpy as np\n'), ((11274, 11423), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0], [2, 10, 10, 7], [\n 3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0], [2, 10, \n 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype=np.float32)\n', (11282, 11423), True, 'import numpy as np\n'), ((11863, 12012), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0], [2, 10, 10, 7], [\n 3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0], [2, 10, \n 10, 7], [3, 9, 10, 5], [4, 6, 6, 9], [6, 8, 6, 4]], dtype=np.float32)\n', (11871, 12012), True, 'import numpy as np\n'), ((12755, 12774), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (12772, 12774), True, 'import oneflow as flow\n'), ((12798, 12888), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (12806, 12888), True, 'import numpy as np\n'), ((13659, 13804), 'numpy.array', 'np.array', (['[[4, 6, 0, 0], [6, 8, 0, 0], [3, 7, 0, 0], [6, 8, 0, 0], [2, 10, 0, 0], [3,\n 9, 0, 0], [4, 6, 0, 0], [6, 8, 0, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 0, 0], [6, 8, 0, 0], [3, 7, 0, 0], [6, 8, 0, 0], [2, 10, 0,\n 0], [3, 9, 0, 0], [4, 6, 0, 0], [6, 8, 0, 0]], dtype=np.float32)\n', (13667, 13804), True, 'import numpy as np\n'), ((14245, 14393), 'numpy.array', 'np.array', (['[[0, 0, 5, 20], [0, 0, 9, 0], [0, 0, 5, 0], [0, 0, 9, 0], [0, 0, 10, 7], [0,\n 0, 10, 5], [0, 0, 6, 9], [0, 0, 6, 4]]'], {'dtype': 'np.float32'}), '([[0, 0, 5, 20], [0, 0, 9, 0], [0, 0, 5, 0], [0, 0, 9, 0], [0, 0, \n 10, 7], [0, 0, 10, 5], [0, 0, 6, 9], [0, 0, 6, 4]], dtype=np.float32)\n', (14253, 14393), True, 'import numpy as np\n'), ((15132, 15151), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (15149, 15151), True, 'import oneflow as flow\n'), ((15175, 15265), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (15183, 15265), True, 'import numpy as np\n'), ((15985, 16053), 'numpy.array', 'np.array', (['[[15, 20], [16, 19], [13, 16], [15, 23]]'], {'dtype': 'np.float32'}), '([[15, 20], [16, 19], [13, 16], [15, 23]], dtype=np.float32)\n', (15993, 16053), True, 'import numpy as np\n'), ((16226, 16294), 'numpy.array', 'np.array', (['[[20, 35], [28, 10], [20, 11], [20, 12]]'], {'dtype': 'np.float32'}), '([[20, 35], [28, 10], [20, 11], [20, 12]], dtype=np.float32)\n', (16234, 16294), True, 'import numpy as np\n'), ((16766, 16785), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (16783, 16785), True, 'import oneflow as flow\n'), ((16809, 16899), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (16817, 16899), True, 'import numpy as np\n'), ((17617, 17677), 'numpy.array', 'np.array', (['[[4, 6], [6, 8], [3, 7], [6, 8]]'], {'dtype': 'np.float32'}), '([[4, 6], [6, 8], [3, 7], [6, 8]], dtype=np.float32)\n', (17625, 17677), True, 'import numpy as np\n'), ((17850, 17911), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [5, 0], [9, 0]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [5, 0], [9, 0]], dtype=np.float32)\n', (17858, 17911), True, 'import numpy as np\n'), ((18384, 18403), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (18401, 18403), True, 'import oneflow as flow\n'), ((18427, 18517), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (18435, 18517), True, 'import numpy as np\n'), ((19234, 19363), 'numpy.array', 'np.array', (['[[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8], [9, 4], [\n 7, 2], [6, 3], [3, 7]]'], {'dtype': 'np.float32'}), '([[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8],\n [9, 4], [7, 2], [6, 3], [3, 7]], dtype=np.float32)\n', (19242, 19363), True, 'import numpy as np\n'), ((19900, 20031), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4], [5, 8],\n [9, 5], [9, 2], [5, 8]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4],\n [5, 8], [9, 5], [9, 2], [5, 8]], dtype=np.float32)\n', (19908, 20031), True, 'import numpy as np\n'), ((21087, 21106), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (21104, 21106), True, 'import oneflow as flow\n'), ((21130, 21243), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9]], dtype=np.float32)\n', (21138, 21243), True, 'import numpy as np\n'), ((22221, 22393), 'numpy.array', 'np.array', (['[[4, 6, 5], [6, 8, 9], [3, 7, 5], [6, 8, 9], [2, 10, 10], [3, 9, 10], [4, 6,\n 6], [6, 8, 6], [9, 4, 5], [7, 2, 9], [6, 3, 9], [3, 7, 5]]'], {'dtype': 'np.float32'}), '([[4, 6, 5], [6, 8, 9], [3, 7, 5], [6, 8, 9], [2, 10, 10], [3, 9, \n 10], [4, 6, 6], [6, 8, 6], [9, 4, 5], [7, 2, 9], [6, 3, 9], [3, 7, 5]],\n dtype=np.float32)\n', (22229, 22393), True, 'import numpy as np\n'), ((22925, 23096), 'numpy.array', 'np.array', (['[[20, 8, 9], [0, 4, 6], [0, 3, 5], [0, 8, 7], [7, 10, 3], [5, 5, 6], [9, 8,\n 6], [4, 5, 3], [8, 9, 6], [5, 4, 1], [2, 5, 2], [8, 9, 3]]'], {'dtype': 'np.float32'}), '([[20, 8, 9], [0, 4, 6], [0, 3, 5], [0, 8, 7], [7, 10, 3], [5, 5, 6\n ], [9, 8, 6], [4, 5, 3], [8, 9, 6], [5, 4, 1], [2, 5, 2], [8, 9, 3]],\n dtype=np.float32)\n', (22933, 23096), True, 'import numpy as np\n'), ((24147, 24166), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (24164, 24166), True, 'import oneflow as flow\n'), ((24190, 24303), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9]], dtype=np.float32)\n', (24198, 24303), True, 'import numpy as np\n'), ((25281, 25444), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6]], dtype=np.\n float32)\n', (25289, 25444), True, 'import numpy as np\n'), ((25831, 25983), 'numpy.array', 'np.array', (['[[4, 6, 6, 9, 8, 6], [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4,\n 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]]'], {'dtype': 'np.float32'}), '([[4, 6, 6, 9, 8, 6], [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2,\n 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]], dtype=np.float32)\n', (25839, 25983), True, 'import numpy as np\n'), ((26894, 26913), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (26911, 26913), True, 'import oneflow as flow\n'), ((26937, 27050), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9]], dtype=np.float32)\n', (26945, 27050), True, 'import numpy as np\n'), ((28029, 28316), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6],\n [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2,\n 5, 2], [3, 7, 5, 8, 9, 3]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9,\n 8, 6], [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, \n 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]], dtype=np.float32)\n', (28037, 28316), True, 'import numpy as np\n'), ((28843, 29130), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6],\n [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2,\n 5, 2], [3, 7, 5, 8, 9, 3]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9,\n 8, 6], [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, \n 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]], dtype=np.float32)\n', (28851, 29130), True, 'import numpy as np\n'), ((30175, 30194), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (30192, 30194), True, 'import oneflow as flow\n'), ((30218, 30331), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9]], dtype=np.float32)\n', (30226, 30331), True, 'import numpy as np\n'), ((31312, 31594), 'numpy.array', 'np.array', (['[[4, 6, 0, 0, 0, 0], [6, 8, 0, 0, 0, 0], [3, 7, 0, 0, 0, 0], [6, 8, 0, 0, 0,\n 0], [2, 10, 0, 0, 0, 0], [3, 9, 0, 0, 0, 0], [4, 6, 0, 0, 0, 0], [6, 8,\n 0, 0, 0, 0], [9, 4, 0, 0, 0, 0], [7, 2, 0, 0, 0, 0], [6, 3, 0, 0, 0, 0],\n [3, 7, 0, 0, 0, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 0, 0, 0, 0], [6, 8, 0, 0, 0, 0], [3, 7, 0, 0, 0, 0], [6, 8,\n 0, 0, 0, 0], [2, 10, 0, 0, 0, 0], [3, 9, 0, 0, 0, 0], [4, 6, 0, 0, 0, 0\n ], [6, 8, 0, 0, 0, 0], [9, 4, 0, 0, 0, 0], [7, 2, 0, 0, 0, 0], [6, 3, 0,\n 0, 0, 0], [3, 7, 0, 0, 0, 0]], dtype=np.float32)\n', (31320, 31594), True, 'import numpy as np\n'), ((32122, 32408), 'numpy.array', 'np.array', (['[[0, 0, 5, 20, 8, 9], [0, 0, 9, 0, 4, 6], [0, 0, 5, 0, 3, 5], [0, 0, 9, 0, \n 8, 7], [0, 0, 10, 7, 10, 3], [0, 0, 10, 5, 5, 6], [0, 0, 6, 9, 8, 6], [\n 0, 0, 6, 4, 5, 3], [0, 0, 5, 8, 9, 6], [0, 0, 9, 5, 4, 1], [0, 0, 9, 2,\n 5, 2], [0, 0, 5, 8, 9, 3]]'], {'dtype': 'np.float32'}), '([[0, 0, 5, 20, 8, 9], [0, 0, 9, 0, 4, 6], [0, 0, 5, 0, 3, 5], [0, \n 0, 9, 0, 8, 7], [0, 0, 10, 7, 10, 3], [0, 0, 10, 5, 5, 6], [0, 0, 6, 9,\n 8, 6], [0, 0, 6, 4, 5, 3], [0, 0, 5, 8, 9, 6], [0, 0, 9, 5, 4, 1], [0, \n 0, 9, 2, 5, 2], [0, 0, 5, 8, 9, 3]], dtype=np.float32)\n', (32130, 32408), True, 'import numpy as np\n'), ((33247, 33266), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (33264, 33266), True, 'import oneflow as flow\n'), ((33290, 33380), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (33298, 33380), True, 'import numpy as np\n'), ((34100, 34168), 'numpy.array', 'np.array', (['[[15, 20], [16, 19], [13, 16], [15, 23]]'], {'dtype': 'np.float32'}), '([[15, 20], [16, 19], [13, 16], [15, 23]], dtype=np.float32)\n', (34108, 34168), True, 'import numpy as np\n'), ((34341, 34409), 'numpy.array', 'np.array', (['[[20, 35], [28, 10], [20, 11], [20, 12]]'], {'dtype': 'np.float32'}), '([[20, 35], [28, 10], [20, 11], [20, 12]], dtype=np.float32)\n', (34349, 34409), True, 'import numpy as np\n'), ((34894, 34913), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (34911, 34913), True, 'import oneflow as flow\n'), ((34937, 35027), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (34945, 35027), True, 'import numpy as np\n'), ((35745, 35805), 'numpy.array', 'np.array', (['[[4, 6], [6, 8], [3, 7], [6, 8]]'], {'dtype': 'np.float32'}), '([[4, 6], [6, 8], [3, 7], [6, 8]], dtype=np.float32)\n', (35753, 35805), True, 'import numpy as np\n'), ((35978, 36039), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [5, 0], [9, 0]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [5, 0], [9, 0]], dtype=np.float32)\n', (35986, 36039), True, 'import numpy as np\n'), ((36525, 36544), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (36542, 36544), True, 'import oneflow as flow\n'), ((36568, 36658), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (36576, 36658), True, 'import numpy as np\n'), ((37375, 37504), 'numpy.array', 'np.array', (['[[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8], [9, 4], [\n 7, 2], [6, 3], [3, 7]]'], {'dtype': 'np.float32'}), '([[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8],\n [9, 4], [7, 2], [6, 3], [3, 7]], dtype=np.float32)\n', (37383, 37504), True, 'import numpy as np\n'), ((38041, 38172), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4], [5, 8],\n [9, 5], [9, 2], [5, 8]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4],\n [5, 8], [9, 5], [9, 2], [5, 8]], dtype=np.float32)\n', (38049, 38172), True, 'import numpy as np\n'), ((39022, 39041), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (39039, 39041), True, 'import oneflow as flow\n'), ((39065, 39155), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (39073, 39155), True, 'import numpy as np\n'), ((39930, 39990), 'numpy.array', 'np.array', (['[[4, 6], [6, 8], [3, 7], [6, 8]]'], {'dtype': 'np.float32'}), '([[4, 6], [6, 8], [3, 7], [6, 8]], dtype=np.float32)\n', (39938, 39990), True, 'import numpy as np\n'), ((40163, 40224), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [5, 0], [9, 0]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [5, 0], [9, 0]], dtype=np.float32)\n', (40171, 40224), True, 'import numpy as np\n'), ((40710, 40729), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (40727, 40729), True, 'import oneflow as flow\n'), ((40753, 40843), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (40761, 40843), True, 'import numpy as np\n'), ((41618, 41675), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0]], dtype=np.float32)\n', (41626, 41675), True, 'import numpy as np\n'), ((41848, 41904), 'numpy.array', 'np.array', (['[[3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[3, 7, 5, 0], [6, 8, 9, 0]], dtype=np.float32)\n', (41856, 41904), True, 'import numpy as np\n'), ((42389, 42408), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (42406, 42408), True, 'import oneflow as flow\n'), ((42432, 42522), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (42440, 42522), True, 'import numpy as np\n'), ((43300, 43389), 'numpy.array', 'np.array', (['[[4, 6, 5, 0], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 0], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=np\n .float32)\n', (43308, 43389), True, 'import numpy as np\n'), ((43615, 43705), 'numpy.array', 'np.array', (['[[0, 0, 0, 20], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]'], {'dtype': 'np.float32'}), '([[0, 0, 0, 20], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], dtype=\n np.float32)\n', (43623, 43705), True, 'import numpy as np\n'), ((44243, 44262), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (44260, 44262), True, 'import oneflow as flow\n'), ((44286, 44376), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (44294, 44376), True, 'import numpy as np\n'), ((45152, 45242), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (45160, 45242), True, 'import numpy as np\n'), ((45468, 45558), 'numpy.array', 'np.array', (['[[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20], [6, 8, 9, 0], [3, 7, 5, 0], [6, 8, 9, 0]], dtype=\n np.float32)\n', (45476, 45558), True, 'import numpy as np\n'), ((46096, 46115), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (46113, 46115), True, 'import oneflow as flow\n'), ((46139, 46229), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (46147, 46229), True, 'import numpy as np\n'), ((46955, 47007), 'numpy.array', 'np.array', (['[[15], [16], [13], [15]]'], {'dtype': 'np.float32'}), '([[15], [16], [13], [15]], dtype=np.float32)\n', (46963, 47007), True, 'import numpy as np\n'), ((47180, 47232), 'numpy.array', 'np.array', (['[[20], [19], [16], [23]]'], {'dtype': 'np.float32'}), '([[20], [19], [16], [23]], dtype=np.float32)\n', (47188, 47232), True, 'import numpy as np\n'), ((47405, 47457), 'numpy.array', 'np.array', (['[[20], [28], [20], [20]]'], {'dtype': 'np.float32'}), '([[20], [28], [20], [20]], dtype=np.float32)\n', (47413, 47457), True, 'import numpy as np\n'), ((47630, 47682), 'numpy.array', 'np.array', (['[[35], [10], [11], [12]]'], {'dtype': 'np.float32'}), '([[35], [10], [11], [12]], dtype=np.float32)\n', (47638, 47682), True, 'import numpy as np\n'), ((48167, 48186), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (48184, 48186), True, 'import oneflow as flow\n'), ((48210, 48300), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (48218, 48300), True, 'import numpy as np\n'), ((49024, 49072), 'numpy.array', 'np.array', (['[[4], [6], [3], [6]]'], {'dtype': 'np.float32'}), '([[4], [6], [3], [6]], dtype=np.float32)\n', (49032, 49072), True, 'import numpy as np\n'), ((49245, 49293), 'numpy.array', 'np.array', (['[[6], [8], [7], [8]]'], {'dtype': 'np.float32'}), '([[6], [8], [7], [8]], dtype=np.float32)\n', (49253, 49293), True, 'import numpy as np\n'), ((49466, 49514), 'numpy.array', 'np.array', (['[[5], [9], [5], [9]]'], {'dtype': 'np.float32'}), '([[5], [9], [5], [9]], dtype=np.float32)\n', (49474, 49514), True, 'import numpy as np\n'), ((49687, 49736), 'numpy.array', 'np.array', (['[[20], [0], [0], [0]]'], {'dtype': 'np.float32'}), '([[20], [0], [0], [0]], dtype=np.float32)\n', (49695, 49736), True, 'import numpy as np\n'), ((50222, 50241), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (50239, 50241), True, 'import oneflow as flow\n'), ((50265, 50355), 'numpy.array', 'np.array', (['[[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8], [4, 9, 7, 0], [2, 5, 7, 9], [6, 8, 10, 0]], dtype=\n np.float32)\n', (50273, 50355), True, 'import numpy as np\n'), ((51078, 51170), 'numpy.array', 'np.array', (['[[4], [6], [3], [6], [2], [3], [4], [6], [9], [7], [6], [3]]'], {'dtype': 'np.float32'}), '([[4], [6], [3], [6], [2], [3], [4], [6], [9], [7], [6], [3]],\n dtype=np.float32)\n', (51086, 51170), True, 'import numpy as np\n'), ((51397, 51490), 'numpy.array', 'np.array', (['[[6], [8], [7], [8], [10], [9], [6], [8], [4], [2], [3], [7]]'], {'dtype': 'np.float32'}), '([[6], [8], [7], [8], [10], [9], [6], [8], [4], [2], [3], [7]],\n dtype=np.float32)\n', (51405, 51490), True, 'import numpy as np\n'), ((51717, 51811), 'numpy.array', 'np.array', (['[[5], [9], [5], [9], [10], [10], [6], [6], [5], [9], [9], [5]]'], {'dtype': 'np.float32'}), '([[5], [9], [5], [9], [10], [10], [6], [6], [5], [9], [9], [5]],\n dtype=np.float32)\n', (51725, 51811), True, 'import numpy as np\n'), ((52038, 52131), 'numpy.array', 'np.array', (['[[20], [0], [0], [0], [7], [5], [9], [4], [8], [5], [2], [8]]'], {'dtype': 'np.float32'}), '([[20], [0], [0], [0], [7], [5], [9], [4], [8], [5], [2], [8]],\n dtype=np.float32)\n', (52046, 52131), True, 'import numpy as np\n'), ((52889, 52908), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (52906, 52908), True, 'import oneflow as flow\n'), ((52932, 53045), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9]], dtype=np.float32)\n', (52940, 53045), True, 'import numpy as np\n'), ((55254, 55273), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (55271, 55273), True, 'import oneflow as flow\n'), ((55297, 55410), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9]], dtype=np.float32)\n', (55305, 55410), True, 'import numpy as np\n'), ((56397, 56679), 'numpy.array', 'np.array', (['[[4, 6, 0, 0, 0, 0], [6, 8, 0, 0, 0, 0], [3, 7, 0, 0, 0, 0], [6, 8, 0, 0, 0,\n 0], [2, 10, 0, 0, 0, 0], [3, 9, 0, 0, 0, 0], [4, 6, 0, 0, 0, 0], [6, 8,\n 0, 0, 0, 0], [9, 4, 0, 0, 0, 0], [7, 2, 0, 0, 0, 0], [6, 3, 0, 0, 0, 0],\n [3, 7, 0, 0, 0, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 0, 0, 0, 0], [6, 8, 0, 0, 0, 0], [3, 7, 0, 0, 0, 0], [6, 8,\n 0, 0, 0, 0], [2, 10, 0, 0, 0, 0], [3, 9, 0, 0, 0, 0], [4, 6, 0, 0, 0, 0\n ], [6, 8, 0, 0, 0, 0], [9, 4, 0, 0, 0, 0], [7, 2, 0, 0, 0, 0], [6, 3, 0,\n 0, 0, 0], [3, 7, 0, 0, 0, 0]], dtype=np.float32)\n', (56405, 56679), True, 'import numpy as np\n'), ((57885, 57904), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (57902, 57904), True, 'import oneflow as flow\n'), ((60151, 60170), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (60168, 60170), True, 'import oneflow as flow\n'), ((60194, 60307), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9]], dtype=np.float32)\n', (60202, 60307), True, 'import numpy as np\n'), ((61291, 61384), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5]],\n dtype=np.float32)\n', (61299, 61384), True, 'import numpy as np\n'), ((61800, 61819), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (61817, 61819), True, 'import oneflow as flow\n'), ((63161, 63180), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (63178, 63180), True, 'import oneflow as flow\n'), ((63204, 63343), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6, 8, 3], [4, 9, 7, 0, 2, 1, 9, 7], [2, 5, 7, 9, 4, 8, 5, \n 7], [6, 8, 10, 0, 4, 9, 8, 10]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6, 8, 3], [4, 9, 7, 0, 2, 1, 9, 7], [2, 5, 7, 9, \n 4, 8, 5, 7], [6, 8, 10, 0, 4, 9, 8, 10]], dtype=np.float32)\n', (63212, 63343), True, 'import numpy as np\n'), ((64347, 64444), 'numpy.array', 'np.array', (['[[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8]]'], {'dtype': 'np.float32'}), '([[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8]],\n dtype=np.float32)\n', (64355, 64444), True, 'import numpy as np\n'), ((65077, 65096), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (65094, 65096), True, 'import oneflow as flow\n'), ((66730, 66749), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (66747, 66749), True, 'import oneflow as flow\n'), ((66773, 66926), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9], [6, 3, 9, 2, 5, 2], [2, 5, 7, 9, 4, 8]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9], [6, 3, 9, 2, 5, 2], [2, 5, 7, 9, 4, 8]], dtype=np.float32)\n', (66781, 66926), True, 'import numpy as np\n'), ((67889, 67981), 'numpy.array', 'np.array', (['[[15, 20], [16, 19], [13, 16], [15, 23], [17, 19], [16, 20]]'], {'dtype': 'np.float32'}), '([[15, 20], [16, 19], [13, 16], [15, 23], [17, 19], [16, 20]],\n dtype=np.float32)\n', (67897, 67981), True, 'import numpy as np\n'), ((68208, 68299), 'numpy.array', 'np.array', (['[[20, 35], [28, 10], [20, 11], [20, 12], [25, 5], [22, 6]]'], {'dtype': 'np.float32'}), '([[20, 35], [28, 10], [20, 11], [20, 12], [25, 5], [22, 6]], dtype=\n np.float32)\n', (68216, 68299), True, 'import numpy as np\n'), ((68525, 68616), 'numpy.array', 'np.array', (['[[27, 18], [13, 13], [16, 13], [22, 13], [10, 8], [12, 6]]'], {'dtype': 'np.float32'}), '([[27, 18], [13, 13], [16, 13], [22, 13], [10, 8], [12, 6]], dtype=\n np.float32)\n', (68533, 68616), True, 'import numpy as np\n'), ((69491, 69510), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (69508, 69510), True, 'import oneflow as flow\n'), ((69534, 69687), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9], [6, 3, 9, 2, 5, 2], [2, 5, 7, 9, 4, 8]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9], [6, 3, 9, 2, 5, 2], [2, 5, 7, 9, 4, 8]], dtype=np.float32)\n', (69542, 69687), True, 'import numpy as np\n'), ((70648, 70724), 'numpy.array', 'np.array', (['[[4, 6], [6, 8], [3, 7], [6, 8], [6, 8], [6, 8]]'], {'dtype': 'np.float32'}), '([[4, 6], [6, 8], [3, 7], [6, 8], [6, 8], [6, 8]], dtype=np.float32)\n', (70656, 70724), True, 'import numpy as np\n'), ((70935, 71012), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [5, 0], [9, 0], [9, 0], [6, 4]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [5, 0], [9, 0], [9, 0], [6, 4]], dtype=np.float32)\n', (70943, 71012), True, 'import numpy as np\n'), ((71243, 71319), 'numpy.array', 'np.array', (['[[8, 9], [4, 6], [3, 5], [8, 7], [4, 6], [5, 3]]'], {'dtype': 'np.float32'}), '([[8, 9], [4, 6], [3, 5], [8, 7], [4, 6], [5, 3]], dtype=np.float32)\n', (71251, 71319), True, 'import numpy as np\n'), ((72036, 72055), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (72053, 72055), True, 'import oneflow as flow\n'), ((72079, 72192), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9]], dtype=np.float32)\n', (72087, 72192), True, 'import numpy as np\n'), ((73048, 73177), 'numpy.array', 'np.array', (['[[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8], [9, 4], [\n 7, 2], [6, 3], [3, 7]]'], {'dtype': 'np.float32'}), '([[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8],\n [9, 4], [7, 2], [6, 3], [3, 7]], dtype=np.float32)\n', (73056, 73177), True, 'import numpy as np\n'), ((73714, 73845), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4], [5, 8],\n [9, 5], [9, 2], [5, 8]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4],\n [5, 8], [9, 5], [9, 2], [5, 8]], dtype=np.float32)\n', (73722, 73845), True, 'import numpy as np\n'), ((74382, 74511), 'numpy.array', 'np.array', (['[[8, 9], [4, 6], [3, 5], [8, 7], [10, 3], [5, 6], [8, 6], [5, 3], [9, 6], [\n 4, 1], [5, 2], [9, 3]]'], {'dtype': 'np.float32'}), '([[8, 9], [4, 6], [3, 5], [8, 7], [10, 3], [5, 6], [8, 6], [5, 3],\n [9, 6], [4, 1], [5, 2], [9, 3]], dtype=np.float32)\n', (74390, 74511), True, 'import numpy as np\n'), ((75554, 75573), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (75571, 75573), True, 'import oneflow as flow\n'), ((75597, 75710), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9]], dtype=np.float32)\n', (75605, 75710), True, 'import numpy as np\n'), ((76620, 76749), 'numpy.array', 'np.array', (['[[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8], [9, 4], [\n 7, 2], [6, 3], [3, 7]]'], {'dtype': 'np.float32'}), '([[4, 6], [6, 8], [3, 7], [6, 8], [2, 10], [3, 9], [4, 6], [6, 8],\n [9, 4], [7, 2], [6, 3], [3, 7]], dtype=np.float32)\n', (76628, 76749), True, 'import numpy as np\n'), ((77286, 77417), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4], [5, 8],\n [9, 5], [9, 2], [5, 8]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4],\n [5, 8], [9, 5], [9, 2], [5, 8]], dtype=np.float32)\n', (77294, 77417), True, 'import numpy as np\n'), ((77954, 78083), 'numpy.array', 'np.array', (['[[8, 9], [4, 6], [3, 5], [8, 7], [10, 3], [5, 6], [8, 6], [5, 3], [9, 6], [\n 4, 1], [5, 2], [9, 3]]'], {'dtype': 'np.float32'}), '([[8, 9], [4, 6], [3, 5], [8, 7], [10, 3], [5, 6], [8, 6], [5, 3],\n [9, 6], [4, 1], [5, 2], [9, 3]], dtype=np.float32)\n', (77962, 78083), True, 'import numpy as np\n'), ((79126, 79145), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (79143, 79145), True, 'import oneflow as flow\n'), ((79169, 79282), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9]], dtype=np.float32)\n', (79177, 79282), True, 'import numpy as np\n'), ((80192, 80306), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7]], dtype=np.float32)\n', (80200, 80306), True, 'import numpy as np\n'), ((80650, 80767), 'numpy.array', 'np.array', (['[[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [6, 8, 6, \n 4, 5, 3]]'], {'dtype': 'np.float32'}), '([[2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6], [\n 6, 8, 6, 4, 5, 3]], dtype=np.float32)\n', (80658, 80767), True, 'import numpy as np\n'), ((81111, 81223), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (81119, 81223), True, 'import numpy as np\n'), ((82073, 82092), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (82090, 82092), True, 'import oneflow as flow\n'), ((82116, 82229), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9]], dtype=np.float32)\n', (82124, 82229), True, 'import numpy as np\n'), ((83142, 83424), 'numpy.array', 'np.array', (['[[4, 6, 0, 0, 0, 0], [6, 8, 0, 0, 0, 0], [3, 7, 0, 0, 0, 0], [6, 8, 0, 0, 0,\n 0], [2, 10, 0, 0, 0, 0], [3, 9, 0, 0, 0, 0], [4, 6, 0, 0, 0, 0], [6, 8,\n 0, 0, 0, 0], [9, 4, 0, 0, 0, 0], [7, 2, 0, 0, 0, 0], [6, 3, 0, 0, 0, 0],\n [3, 7, 0, 0, 0, 0]]'], {'dtype': 'np.float32'}), '([[4, 6, 0, 0, 0, 0], [6, 8, 0, 0, 0, 0], [3, 7, 0, 0, 0, 0], [6, 8,\n 0, 0, 0, 0], [2, 10, 0, 0, 0, 0], [3, 9, 0, 0, 0, 0], [4, 6, 0, 0, 0, 0\n ], [6, 8, 0, 0, 0, 0], [9, 4, 0, 0, 0, 0], [7, 2, 0, 0, 0, 0], [6, 3, 0,\n 0, 0, 0], [3, 7, 0, 0, 0, 0]], dtype=np.float32)\n', (83150, 83424), True, 'import numpy as np\n'), ((83952, 84238), 'numpy.array', 'np.array', (['[[0, 0, 5, 20, 0, 0], [0, 0, 9, 0, 0, 0], [0, 0, 5, 0, 0, 0], [0, 0, 9, 0, \n 0, 0], [0, 0, 10, 7, 0, 0], [0, 0, 10, 5, 0, 0], [0, 0, 6, 9, 0, 0], [0,\n 0, 6, 4, 0, 0], [0, 0, 5, 8, 0, 0], [0, 0, 9, 5, 0, 0], [0, 0, 9, 2, 0,\n 0], [0, 0, 5, 8, 0, 0]]'], {'dtype': 'np.float32'}), '([[0, 0, 5, 20, 0, 0], [0, 0, 9, 0, 0, 0], [0, 0, 5, 0, 0, 0], [0, \n 0, 9, 0, 0, 0], [0, 0, 10, 7, 0, 0], [0, 0, 10, 5, 0, 0], [0, 0, 6, 9, \n 0, 0], [0, 0, 6, 4, 0, 0], [0, 0, 5, 8, 0, 0], [0, 0, 9, 5, 0, 0], [0, \n 0, 9, 2, 0, 0], [0, 0, 5, 8, 0, 0]], dtype=np.float32)\n', (83960, 84238), True, 'import numpy as np\n'), ((84764, 85046), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 8, 9], [0, 0, 0, 0, 4, 6], [0, 0, 0, 0, 3, 5], [0, 0, 0, 0, 8,\n 7], [0, 0, 0, 0, 10, 3], [0, 0, 0, 0, 5, 6], [0, 0, 0, 0, 8, 6], [0, 0,\n 0, 0, 5, 3], [0, 0, 0, 0, 9, 6], [0, 0, 0, 0, 4, 1], [0, 0, 0, 0, 5, 2],\n [0, 0, 0, 0, 9, 3]]'], {'dtype': 'np.float32'}), '([[0, 0, 0, 0, 8, 9], [0, 0, 0, 0, 4, 6], [0, 0, 0, 0, 3, 5], [0, 0,\n 0, 0, 8, 7], [0, 0, 0, 0, 10, 3], [0, 0, 0, 0, 5, 6], [0, 0, 0, 0, 8, 6\n ], [0, 0, 0, 0, 5, 3], [0, 0, 0, 0, 9, 6], [0, 0, 0, 0, 4, 1], [0, 0, 0,\n 0, 5, 2], [0, 0, 0, 0, 9, 3]], dtype=np.float32)\n', (84772, 85046), True, 'import numpy as np\n'), ((86079, 86098), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (86096, 86098), True, 'import oneflow as flow\n'), ((86122, 86235), 'numpy.array', 'np.array', (['[[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8, 10, 0, \n 4, 9]]'], {'dtype': 'np.float32'}), '([[9, 6, 5, 8, 3, 6], [4, 9, 7, 0, 2, 1], [2, 5, 7, 9, 4, 8], [6, 8,\n 10, 0, 4, 9]], dtype=np.float32)\n', (86130, 86235), True, 'import numpy as np\n'), ((87146, 87433), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6],\n [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2,\n 5, 2], [3, 7, 5, 8, 9, 3]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9,\n 8, 6], [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, \n 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]], dtype=np.float32)\n', (87154, 87433), True, 'import numpy as np\n'), ((87960, 88247), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6],\n [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2,\n 5, 2], [3, 7, 5, 8, 9, 3]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9,\n 8, 6], [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, \n 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]], dtype=np.float32)\n', (87968, 88247), True, 'import numpy as np\n'), ((88774, 89061), 'numpy.array', 'np.array', (['[[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, 8, 9, 0, \n 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9, 8, 6],\n [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2,\n 5, 2], [3, 7, 5, 8, 9, 3]]'], {'dtype': 'np.float32'}), '([[4, 6, 5, 20, 8, 9], [6, 8, 9, 0, 4, 6], [3, 7, 5, 0, 3, 5], [6, \n 8, 9, 0, 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6], [4, 6, 6, 9,\n 8, 6], [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, \n 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]], dtype=np.float32)\n', (88782, 89061), True, 'import numpy as np\n'), ((113982, 114013), 'numpy.ones', 'np.ones', (['(2, 8)'], {'dtype': 'np.int32'}), '((2, 8), dtype=np.int32)\n', (113989, 114013), True, 'import numpy as np\n'), ((114847, 114878), 'numpy.ones', 'np.ones', (['(1, 8)'], {'dtype': 'np.int32'}), '((1, 8), dtype=np.int32)\n', (114854, 114878), True, 'import numpy as np\n'), ((115080, 115105), 'oneflow.env.get_world_size', 'flow.env.get_world_size', ([], {}), '()\n', (115103, 115105), True, 'import oneflow as flow\n'), ((115350, 115367), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (115364, 115367), True, 'import oneflow as flow\n'), ((115928, 115945), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (115942, 115945), True, 'import oneflow as flow\n'), ((119777, 119794), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (119791, 119794), True, 'import oneflow as flow\n'), ((119811, 119828), 'oneflow.sbp.split', 'flow.sbp.split', (['(2)'], {}), '(2)\n', (119825, 119828), True, 'import oneflow as flow\n'), ((119959, 119976), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (119973, 119976), True, 'import oneflow as flow\n'), ((119993, 120010), 'oneflow.sbp.split', 'flow.sbp.split', (['(2)'], {}), '(2)\n', (120007, 120010), True, 'import oneflow as flow\n'), ((1363, 1382), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (1380, 1382), True, 'import oneflow as flow\n'), ((1406, 1495), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (1414, 1495), True, 'import numpy as np\n'), ((2992, 3011), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (3009, 3011), True, 'import oneflow as flow\n'), ((3035, 3124), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (3043, 3124), True, 'import numpy as np\n'), ((4611, 4630), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (4628, 4630), True, 'import oneflow as flow\n'), ((4654, 4743), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (4662, 4743), True, 'import numpy as np\n'), ((6626, 6645), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (6643, 6645), True, 'import oneflow as flow\n'), ((6669, 6758), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (6677, 6758), True, 'import numpy as np\n'), ((8695, 8714), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (8712, 8714), True, 'import oneflow as flow\n'), ((8738, 8827), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (8746, 8827), True, 'import numpy as np\n'), ((10533, 10552), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (10550, 10552), True, 'import oneflow as flow\n'), ((10576, 10665), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (10584, 10665), True, 'import numpy as np\n'), ((12916, 12935), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (12933, 12935), True, 'import oneflow as flow\n'), ((12959, 13048), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (12967, 13048), True, 'import numpy as np\n'), ((15293, 15312), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (15310, 15312), True, 'import oneflow as flow\n'), ((15336, 15425), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (15344, 15425), True, 'import numpy as np\n'), ((16927, 16946), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (16944, 16946), True, 'import oneflow as flow\n'), ((16970, 17059), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (16978, 17059), True, 'import numpy as np\n'), ((18545, 18564), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (18562, 18564), True, 'import oneflow as flow\n'), ((18588, 18677), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (18596, 18677), True, 'import numpy as np\n'), ((21363, 21382), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (21380, 21382), True, 'import oneflow as flow\n'), ((21406, 21518), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (21414, 21518), True, 'import numpy as np\n'), ((24423, 24442), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (24440, 24442), True, 'import oneflow as flow\n'), ((24466, 24578), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (24474, 24578), True, 'import numpy as np\n'), ((27170, 27189), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (27187, 27189), True, 'import oneflow as flow\n'), ((27213, 27325), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (27221, 27325), True, 'import numpy as np\n'), ((30451, 30470), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (30468, 30470), True, 'import oneflow as flow\n'), ((30494, 30606), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (30502, 30606), True, 'import numpy as np\n'), ((33408, 33427), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (33425, 33427), True, 'import oneflow as flow\n'), ((33451, 33540), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (33459, 33540), True, 'import numpy as np\n'), ((35055, 35074), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (35072, 35074), True, 'import oneflow as flow\n'), ((35098, 35187), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (35106, 35187), True, 'import numpy as np\n'), ((36686, 36705), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (36703, 36705), True, 'import oneflow as flow\n'), ((36729, 36818), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (36737, 36818), True, 'import numpy as np\n'), ((39183, 39202), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (39200, 39202), True, 'import oneflow as flow\n'), ((39226, 39315), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (39234, 39315), True, 'import numpy as np\n'), ((40871, 40890), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (40888, 40890), True, 'import oneflow as flow\n'), ((40914, 41003), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (40922, 41003), True, 'import numpy as np\n'), ((42550, 42569), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (42567, 42569), True, 'import oneflow as flow\n'), ((42593, 42682), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (42601, 42682), True, 'import numpy as np\n'), ((44404, 44423), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (44421, 44423), True, 'import oneflow as flow\n'), ((44447, 44536), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (44455, 44536), True, 'import numpy as np\n'), ((46257, 46276), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (46274, 46276), True, 'import oneflow as flow\n'), ((46300, 46389), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (46308, 46389), True, 'import numpy as np\n'), ((48328, 48347), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (48345, 48347), True, 'import oneflow as flow\n'), ((48371, 48460), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (48379, 48460), True, 'import numpy as np\n'), ((50383, 50402), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (50400, 50402), True, 'import oneflow as flow\n'), ((50426, 50515), 'numpy.array', 'np.array', (['[[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8], [7, 2, 9, 5], [6, 3, 9, 2], [3, 7, 5, 8]], dtype=np\n .float32)\n', (50434, 50515), True, 'import numpy as np\n'), ((53165, 53184), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (53182, 53184), True, 'import oneflow as flow\n'), ((53208, 53320), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (53216, 53320), True, 'import numpy as np\n'), ((55530, 55549), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (55547, 55549), True, 'import oneflow as flow\n'), ((55573, 55685), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (55581, 55685), True, 'import numpy as np\n'), ((57209, 57495), 'numpy.array', 'np.array', (['[[0, 0, 5, 20, 0, 0], [0, 0, 9, 0, 0, 0], [0, 0, 5, 0, 0, 0], [0, 0, 9, 0, \n 0, 0], [0, 0, 10, 7, 0, 0], [0, 0, 10, 5, 0, 0], [0, 0, 6, 9, 0, 0], [0,\n 0, 6, 4, 0, 0], [0, 0, 5, 8, 0, 0], [0, 0, 9, 5, 0, 0], [0, 0, 9, 2, 0,\n 0], [0, 0, 5, 8, 0, 0]]'], {'dtype': 'np.float32'}), '([[0, 0, 5, 20, 0, 0], [0, 0, 9, 0, 0, 0], [0, 0, 5, 0, 0, 0], [0, \n 0, 9, 0, 0, 0], [0, 0, 10, 7, 0, 0], [0, 0, 10, 5, 0, 0], [0, 0, 6, 9, \n 0, 0], [0, 0, 6, 4, 0, 0], [0, 0, 5, 8, 0, 0], [0, 0, 9, 5, 0, 0], [0, \n 0, 9, 2, 0, 0], [0, 0, 5, 8, 0, 0]], dtype=np.float32)\n', (57217, 57495), True, 'import numpy as np\n'), ((60427, 60446), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (60444, 60446), True, 'import oneflow as flow\n'), ((60470, 60582), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (60478, 60582), True, 'import numpy as np\n'), ((61613, 61709), 'numpy.array', 'np.array', (['[[6, 8, 9, 0, 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6]]'], {'dtype': 'np.float32'}), '([[6, 8, 9, 0, 8, 7], [2, 10, 10, 7, 10, 3], [3, 9, 10, 5, 5, 6]],\n dtype=np.float32)\n', (61621, 61709), True, 'import numpy as np\n'), ((62121, 62140), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (62138, 62140), True, 'import oneflow as flow\n'), ((63462, 63481), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (63479, 63481), True, 'import oneflow as flow\n'), ((63505, 63642), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6, 5, 8], [7, 2, 9, 5, 4, 1, 7, 2], [6, 3, 9, 2, 5, 2, 9, \n 2], [3, 7, 5, 8, 9, 3, 7, 5]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6, 5, 8], [7, 2, 9, 5, 4, 1, 7, 2], [6, 3, 9, 2, \n 5, 2, 9, 2], [3, 7, 5, 8, 9, 3, 7, 5]], dtype=np.float32)\n', (63513, 63642), True, 'import numpy as np\n'), ((64673, 64773), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [5, 0], [9, 0], [10, 7], [10, 5], [6, 9], [6, 4]\n ], dtype=np.float32)\n', (64681, 64773), True, 'import numpy as np\n'), ((65403, 65422), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (65420, 65422), True, 'import oneflow as flow\n'), ((67078, 67097), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (67095, 67097), True, 'import oneflow as flow\n'), ((67121, 67273), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9,\n 3], [7, 2, 9, 5, 4, 1], [4, 9, 7, 0, 2, 1]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3], [7, 2, 9, 5, 4, 1], [4, 9, 7, 0, 2, 1]], dtype=np.float32)\n', (67129, 67273), True, 'import numpy as np\n'), ((69839, 69858), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (69856, 69858), True, 'import oneflow as flow\n'), ((69882, 70034), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9,\n 3], [7, 2, 9, 5, 4, 1], [4, 9, 7, 0, 2, 1]]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3], [7, 2, 9, 5, 4, 1], [4, 9, 7, 0, 2, 1]], dtype=np.float32)\n', (69890, 70034), True, 'import numpy as np\n'), ((72312, 72331), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (72329, 72331), True, 'import oneflow as flow\n'), ((72355, 72467), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (72363, 72467), True, 'import numpy as np\n'), ((75830, 75849), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (75847, 75849), True, 'import oneflow as flow\n'), ((75873, 75985), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (75881, 75985), True, 'import numpy as np\n'), ((79402, 79421), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (79419, 79421), True, 'import oneflow as flow\n'), ((79445, 79557), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (79453, 79557), True, 'import numpy as np\n'), ((82349, 82368), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (82366, 82368), True, 'import oneflow as flow\n'), ((82392, 82504), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (82400, 82504), True, 'import numpy as np\n'), ((86355, 86374), 'oneflow.env.get_rank', 'flow.env.get_rank', ([], {}), '()\n', (86372, 86374), True, 'import oneflow as flow\n'), ((86398, 86510), 'numpy.array', 'np.array', (['[[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]\n ]'], {'dtype': 'np.float32'}), '([[9, 4, 5, 8, 9, 6], [7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7,\n 5, 8, 9, 3]], dtype=np.float32)\n', (86406, 86510), True, 'import numpy as np\n'), ((112934, 112951), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (112948, 112951), True, 'import oneflow as flow\n'), ((113051, 113068), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (113065, 113068), True, 'import oneflow as flow\n'), ((113668, 113685), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (113682, 113685), True, 'import oneflow as flow\n'), ((113819, 113836), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (113833, 113836), True, 'import oneflow as flow\n'), ((114575, 114592), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (114589, 114592), True, 'import oneflow as flow\n'), ((114693, 114710), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (114707, 114710), True, 'import oneflow as flow\n'), ((58023, 58303), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0,\n 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, \n 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0]]'], {'dtype': 'np.float32'}), '([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0,\n 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0,\n 0, 0], [0, 0, 0, 0, 0, 0]], dtype=np.float32)\n', (58031, 58303), True, 'import numpy as np\n'), ((58809, 59091), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 8, 9], [0, 0, 0, 0, 4, 6], [0, 0, 0, 0, 3, 5], [0, 0, 0, 0, 8,\n 7], [0, 0, 0, 0, 10, 3], [0, 0, 0, 0, 5, 6], [0, 0, 0, 0, 8, 6], [0, 0,\n 0, 0, 5, 3], [0, 0, 0, 0, 9, 6], [0, 0, 0, 0, 4, 1], [0, 0, 0, 0, 5, 2],\n [0, 0, 0, 0, 9, 3]]'], {'dtype': 'np.float32'}), '([[0, 0, 0, 0, 8, 9], [0, 0, 0, 0, 4, 6], [0, 0, 0, 0, 3, 5], [0, 0,\n 0, 0, 8, 7], [0, 0, 0, 0, 10, 3], [0, 0, 0, 0, 5, 6], [0, 0, 0, 0, 8, 6\n ], [0, 0, 0, 0, 5, 3], [0, 0, 0, 0, 9, 6], [0, 0, 0, 0, 4, 1], [0, 0, 0,\n 0, 5, 2], [0, 0, 0, 0, 9, 3]], dtype=np.float32)\n', (58817, 59091), True, 'import numpy as np\n'), ((61938, 62030), 'numpy.array', 'np.array', (['[[4, 6, 6, 9, 8, 6], [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6]]'], {'dtype': 'np.float32'}), '([[4, 6, 6, 9, 8, 6], [6, 8, 6, 4, 5, 3], [9, 4, 5, 8, 9, 6]],\n dtype=np.float32)\n', (61946, 62030), True, 'import numpy as np\n'), ((65215, 65312), 'numpy.array', 'np.array', (['[[8, 9], [4, 6], [3, 5], [8, 7], [10, 3], [5, 6], [8, 6], [5, 3]]'], {'dtype': 'np.float32'}), '([[8, 9], [4, 6], [3, 5], [8, 7], [10, 3], [5, 6], [8, 6], [5, 3]],\n dtype=np.float32)\n', (65223, 65312), True, 'import numpy as np\n'), ((62259, 62351), 'numpy.array', 'np.array', (['[[7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]]'], {'dtype': 'np.float32'}), '([[7, 2, 9, 5, 4, 1], [6, 3, 9, 2, 5, 2], [3, 7, 5, 8, 9, 3]],\n dtype=np.float32)\n', (62267, 62351), True, 'import numpy as np\n'), ((65541, 65641), 'numpy.array', 'np.array', (['[[5, 20], [9, 0], [0, 3], [8, 9], [10, 7], [9, 10], [6, 9], [8, 6]]'], {'dtype': 'np.float32'}), '([[5, 20], [9, 0], [0, 3], [8, 9], [10, 7], [9, 10], [6, 9], [8, 6]\n ], dtype=np.float32)\n', (65549, 65641), True, 'import numpy as np\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 oneflow as flow
import oneflow.python.framework.dtype as dtype_util
import oneflow.python.framework.id_util as id_util
import oneflow.python.framework.module as module_util
from oneflow.python.oneflow_export import oneflow_export
from oneflow.python.framework.remote_blob import BlobDef
from typing import Optional, Sequence, Union
import random
import sys
@oneflow_export("data.OFRecordRawDecoder", "data.ofrecord_raw_decoder")
def OFRecordRawDecoder(
input_blob: BlobDef,
blob_name: str,
shape: Sequence[int],
dtype: dtype_util.dtype,
dim1_varying_length: bool = False,
auto_zero_padding: bool = False,
name: Optional[str] = None,
) -> BlobDef:
if name is None:
name = id_util.UniqueStr("OFRecordRawDecoder_")
return (
flow.user_op_builder(name)
.Op("ofrecord_raw_decoder")
.Input("in", [input_blob])
.Output("out")
.Attr("name", blob_name)
.Attr("shape", shape)
.Attr("data_type", dtype)
.Attr("dim1_varying_length", dim1_varying_length)
.Attr("auto_zero_padding", auto_zero_padding)
.Build()
.InferAndTryRun()
.RemoteBlobList()[0]
)
@oneflow_export(
"data.OFRecordImageDecoderRandomCrop", "data.ofrecord_image_decoder_random_crop"
)
def OFRecordImageDecoderRandomCrop(
input_blob: BlobDef,
blob_name: str,
color_space: str = "BGR",
num_attempts: int = 10,
seed: Optional[int] = None,
random_area: Sequence[float] = [0.08, 1.0],
random_aspect_ratio: Sequence[float] = [0.75, 1.333333],
name: Optional[str] = None,
) -> BlobDef:
if name is None:
name = id_util.UniqueStr("OFRecordImageDecoderRandomCrop_")
return (
flow.user_op_builder(name)
.Op("ofrecord_image_decoder_random_crop")
.Input("in", [input_blob])
.Output("out")
.Attr("name", blob_name)
.Attr("color_space", color_space)
.Attr("num_attempts", num_attempts)
.SetRandomSeed(seed)
.Attr("random_area", random_area)
.Attr("random_aspect_ratio", random_aspect_ratio)
.Build()
.InferAndTryRun()
.RemoteBlobList()[0]
)
@oneflow_export("data.OFRecordImageDecoder", "data.ofrecord_image_decoder")
def OFRecordImageDecoder(
input_blob: BlobDef,
blob_name: str,
color_space: str = "BGR",
name: Optional[str] = None,
) -> BlobDef:
if name is None:
name = id_util.UniqueStr("OFRecordImageDecoder_")
return (
flow.user_op_builder(name)
.Op("ofrecord_image_decoder")
.Input("in", [input_blob])
.Output("out")
.Attr("name", blob_name)
.Attr("color_space", color_space)
.Build()
.InferAndTryRun()
.RemoteBlobList()[0]
)
@oneflow_export("image.Resize", "image.resize")
def Resize(
input_blob: BlobDef,
color_space: str = "BGR",
interp_type: str = "Linear",
resize_shorter: int = 0,
resize_x: int = 0,
resize_y: int = 0,
name: Optional[str] = None,
) -> BlobDef:
if name is None:
name = id_util.UniqueStr("ImageResize_")
return (
flow.user_op_builder(name)
.Op("image_resize")
.Input("in", [input_blob])
.Output("out")
.Attr("color_space", color_space)
.Attr("interp_type", interp_type)
.Attr("resize_shorter", resize_shorter)
.Attr("resize_x", resize_x)
.Attr("resize_y", resize_y)
.Build()
.InferAndTryRun()
.RemoteBlobList()[0]
)
@oneflow_export("image.CropMirrorNormalize", "image.crop_mirror_normalize")
def CropMirrorNormalize(
input_blob: BlobDef,
mirror_blob: Optional[BlobDef] = None,
color_space: str = "BGR",
output_layout: str = "NCHW",
crop_h: int = 0,
crop_w: int = 0,
crop_pos_y: float = 0.5,
crop_pos_x: float = 0.5,
mean: Sequence[float] = [0.0],
std: Sequence[float] = [1.0],
output_dtype: dtype_util.dtype = dtype_util.float,
name: Optional[str] = None,
):
if name is None:
name = id_util.UniqueStr("CropMirrorNormalize_")
op = (
flow.user_op_builder(name).Op("crop_mirror_normalize").Input("in", [input_blob])
)
if mirror_blob is not None:
op = op.Input("mirror", [mirror_blob])
return (
op.Output("out")
.Attr("color_space", color_space)
.Attr("output_layout", output_layout)
.Attr("mean", mean)
.Attr("std", std)
.Attr("crop_h", crop_h)
.Attr("crop_w", crop_w)
.Attr("crop_pos_y", crop_pos_y)
.Attr("crop_pos_x", crop_pos_x)
.Attr("output_dtype", output_dtype)
.Build()
.InferAndTryRun()
.RemoteBlobList()[0]
)
@oneflow_export("random.CoinFlip", "random.coin_flip")
def CoinFlip(
batch_size: int = 1,
seed: Optional[int] = None,
probability: float = 0.5,
name: Optional[str] = None,
) -> BlobDef:
if name is None:
name = id_util.UniqueStr("CoinFlip_")
return (
flow.user_op_builder(name)
.Op("coin_flip")
.Output("out")
.Attr("batch_size", batch_size)
.Attr("probability", probability)
.SetRandomSeed(seed)
.Build()
.InferAndTryRun()
.RemoteBlobList()[0]
)
@oneflow_export("image.decode", "image_decode")
def image_decode(
images_bytes_buffer: BlobDef,
dtype: dtype_util.dtype = dtype_util.uint8,
color_space: str = "BGR",
name: Optional[str] = None,
) -> BlobDef:
# TODO: check color_space valiad
if name is None:
name = id_util.UniqueStr("ImageDecode_")
op = (
flow.user_op_builder(name)
.Op("image_decode")
.Input("in", [images_bytes_buffer])
.Output("out")
.Attr("color_space", color_space)
.Attr("data_type", dtype)
.Build()
)
return op.InferAndTryRun().SoleOutputBlob()
@oneflow_export("image.target_resize", "image_target_resize")
def image_target_resize(
images: BlobDef, target_size: int, max_size: int, name: Optional[str] = None
) -> Sequence[BlobDef]:
# TODO: check target_size and max_size valid
if name is None:
name = id_util.UniqueStr("ImageTargetResize_")
op = (
flow.user_op_builder(name)
.Op("image_target_resize")
.Input("in", [images])
.Output("out")
.Output("size")
.Output("scale")
.Attr("target_size", target_size)
.Attr("max_size", max_size)
.Build()
)
return op.InferAndTryRun().RemoteBlobList()
@oneflow_export("image.batch_align", "image_batch_align")
def image_batch_align(
images: BlobDef,
shape: Sequence[int],
dtype: dtype_util.dtype,
alignment: int,
name: Optional[str] = None,
) -> BlobDef:
if name is None:
name = id_util.UniqueStr("ImageBatchAlign_")
op = (
flow.user_op_builder(name)
.Op("image_batch_align")
.Input("in", [images])
.Output("out")
.Attr("shape", shape)
.Attr("data_type", dtype)
.Attr("alignment", alignment)
.Build()
)
return op.InferAndTryRun().SoleOutputBlob()
@oneflow_export("image.normalize", "image_normalize")
def image_normalize(
image: BlobDef,
std: Sequence[float],
mean: Sequence[float],
name: Optional[str] = None,
) -> BlobDef:
if name is None:
name = id_util.UniqueStr("ImageNormalize_")
assert isinstance(std, (list, tuple))
assert isinstance(mean, (list, tuple))
op = (
flow.user_op_builder(name)
.Op("image_normalize")
.Input("in", [image])
.Output("out")
.Attr("std", std)
.Attr("mean", mean)
.Build()
)
return op.InferAndTryRun().SoleOutputBlob()
@oneflow_export("image.flip", "image_flip")
def image_flip(
image: BlobDef, flip_code: Union[int, BlobDef], name: Optional[str] = None
) -> BlobDef:
assert isinstance(image, BlobDef)
if name is None:
name = id_util.UniqueStr("ImageFlip_")
if not isinstance(flip_code, BlobDef):
assert isinstance(flip_code, int)
flip_code = flow.constant(
flip_code,
shape=(image.shape[0],),
dtype=flow.int8,
name="{}_FlipCode_".format(name),
)
else:
assert image.shape[0] == flip_code.shape[0]
op = (
flow.user_op_builder(name)
.Op("image_flip")
.Input("in", [image])
.Input("flip_code", [flip_code])
.Output("out")
.Build()
)
return op.InferAndTryRun().SoleOutputBlob()
@oneflow_export("detection.object_bbox_flip", "object_bbox_flip")
def object_bbox_flip(
bbox: BlobDef,
image_size: BlobDef,
flip_code: Union[int, BlobDef],
name: Optional[str] = None,
) -> BlobDef:
assert isinstance(bbox, BlobDef)
assert isinstance(image_size, BlobDef)
assert bbox.shape[0] == image_size.shape[0]
if name is None:
name = id_util.UniqueStr("ObjectBboxFlip_")
if not isinstance(flip_code, BlobDef):
assert isinstance(flip_code, int)
flip_code = flow.constant(
flip_code,
shape=(bbox.shape[0],),
dtype=flow.int8,
name="{}_FlipCode".format(name),
)
else:
assert bbox.shape[0] == flip_code.shape[0]
op = (
flow.user_op_builder(name)
.Op("object_bbox_flip")
.Input("bbox", [bbox])
.Input("image_size", [image_size])
.Input("flip_code", [flip_code])
.Output("out")
.Build()
)
return op.InferAndTryRun().SoleOutputBlob()
@oneflow_export("detection.object_bbox_scale", "object_bbox_scale")
def object_bbox_scale(
bbox: BlobDef, scale: BlobDef, name: Optional[str] = None
) -> BlobDef:
assert isinstance(bbox, BlobDef)
assert isinstance(scale, BlobDef)
assert bbox.shape[0] == scale.shape[0]
if name is None:
name = id_util.UniqueStr("ObjectBboxScale_")
op = (
flow.user_op_builder(name)
.Op("object_bbox_scale")
.Input("bbox", [bbox])
.Input("scale", [scale])
.Output("out")
.Build()
)
return op.InferAndTryRun().SoleOutputBlob()
@oneflow_export(
"detection.object_segmentation_polygon_flip", "object_segmentation_polygon_flip"
)
def object_segm_poly_flip(
poly: BlobDef,
image_size: BlobDef,
flip_code: Union[int, BlobDef],
name: Optional[str] = None,
) -> BlobDef:
assert isinstance(poly, BlobDef)
assert isinstance(image_size, BlobDef)
assert poly.shape[0] == image_size.shape[0]
if name is None:
name = id_util.UniqueStr("ObjectSegmPolyFilp_")
if not isinstance(flip_code, BlobDef):
assert isinstance(flip_code, int)
flip_code = flow.constant(
flip_code,
shape=(poly.shape[0],),
dtype=flow.int8,
name="{}_FlipCode".format(name),
)
else:
assert poly.shape[0] == flip_code.shape[0]
op = (
flow.user_op_builder(name)
.Op("object_segmentation_polygon_flip")
.Input("poly", [poly])
.Input("image_size", [image_size])
.Input("flip_code", [flip_code])
.Output("out")
.Build()
)
return op.InferAndTryRun().SoleOutputBlob()
@oneflow_export(
"detection.object_segmentation_polygon_scale", "object_segmentation_polygon_scale"
)
def object_segm_poly_scale(
poly: BlobDef, scale: BlobDef, name: Optional[str] = None
) -> BlobDef:
assert isinstance(poly, BlobDef)
assert isinstance(scale, BlobDef)
assert poly.shape[0] == scale.shape[0]
if name is None:
name = id_util.UniqueStr("ObjectSegmPolyFilp_")
op = (
flow.user_op_builder(name)
.Op("object_segmentation_polygon_scale")
.Input("poly", [poly])
.Input("scale", [scale])
.Output("out")
.Build()
)
return op.InferAndTryRun().SoleOutputBlob()
@oneflow_export(
"detection.object_segmentation_polygon_to_mask",
"object_segmentation_polygon_to_mask",
)
def object_segm_poly_to_mask(
poly: BlobDef, poly_index: BlobDef, image_size: BlobDef, name: Optional[str] = None
) -> BlobDef:
assert isinstance(poly, BlobDef)
assert isinstance(poly_index, BlobDef)
assert isinstance(image_size, BlobDef)
assert poly.shape[0] == poly_index.shape[0]
assert poly.shape[0] == image_size.shape[0]
if name is None:
name = id_util.UniqueStr("ObjectSegmPolyToMask_")
op = (
flow.user_op_builder(name)
.Op("object_segmentation_polygon_to_mask")
.Input("poly", [poly])
.Input("poly_index", [poly_index])
.Input("image_size", [image_size])
.Output("out")
.Build()
)
return op.InferAndTryRun().SoleOutputBlob()
@oneflow_export("data.coco_reader")
def api_coco_reader(
annotation_file: str,
image_dir: str,
batch_size: int,
shuffle: bool = True,
random_seed: Optional[int] = None,
group_by_aspect_ratio: bool = True,
stride_partition: bool = True,
name: str = None,
) -> BlobDef:
assert name is not None
module = flow.find_or_create_module(
name,
lambda: COCOReader(
annotation_file=annotation_file,
image_dir=image_dir,
batch_size=batch_size,
shuffle=shuffle,
random_seed=random_seed,
group_by_aspect_ratio=group_by_aspect_ratio,
stride_partition=stride_partition,
name=name,
),
)
return module()
class COCOReader(module_util.Module):
def __init__(
self,
annotation_file: str,
image_dir: str,
batch_size: int,
shuffle: bool = True,
random_seed: Optional[int] = None,
group_by_aspect_ratio: bool = True,
stride_partition: bool = True,
name: str = None,
):
assert name is not None
if random_seed is None:
random_seed = random.randrange(sys.maxsize)
module_util.Module.__init__(self, name)
self.op_module_builder = (
flow.consistent_user_op_module_builder("COCOReader")
.Output("image")
.Output("image_id")
.Output("image_size")
.Output("gt_bbox")
.Output("gt_label")
.Output("gt_segm")
.Output("gt_segm_index")
.Attr("annotation_file", annotation_file)
.Attr("image_dir", image_dir)
.Attr("batch_size", batch_size)
.Attr("shuffle_after_epoch", shuffle)
.Attr("random_seed", random_seed)
.Attr("group_by_ratio", group_by_aspect_ratio)
.Attr("stride_partition", stride_partition)
.CheckAndComplete()
)
self.op_module_builder.user_op_module.InitOpKernel()
def forward(self):
if self.call_seq_no == 0:
name = self.module_name
else:
name = id_util.UniqueStr("COCOReader")
return (
self.op_module_builder.OpName(name)
.Build()
.InferAndTryRun()
.RemoteBlobList()
)
| [
"oneflow.consistent_user_op_module_builder",
"oneflow.user_op_builder",
"oneflow.python.framework.id_util.UniqueStr",
"oneflow.python.framework.module.Module.__init__",
"oneflow.python.oneflow_export.oneflow_export"
] | [((998, 1068), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""data.OFRecordRawDecoder"""', '"""data.ofrecord_raw_decoder"""'], {}), "('data.OFRecordRawDecoder', 'data.ofrecord_raw_decoder')\n", (1012, 1068), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((1824, 1924), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""data.OFRecordImageDecoderRandomCrop"""', '"""data.ofrecord_image_decoder_random_crop"""'], {}), "('data.OFRecordImageDecoderRandomCrop',\n 'data.ofrecord_image_decoder_random_crop')\n", (1838, 1924), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((2827, 2901), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""data.OFRecordImageDecoder"""', '"""data.ofrecord_image_decoder"""'], {}), "('data.OFRecordImageDecoder', 'data.ofrecord_image_decoder')\n", (2841, 2901), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((3428, 3474), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""image.Resize"""', '"""image.resize"""'], {}), "('image.Resize', 'image.resize')\n", (3442, 3474), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((4185, 4259), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""image.CropMirrorNormalize"""', '"""image.crop_mirror_normalize"""'], {}), "('image.CropMirrorNormalize', 'image.crop_mirror_normalize')\n", (4199, 4259), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((5387, 5440), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""random.CoinFlip"""', '"""random.coin_flip"""'], {}), "('random.CoinFlip', 'random.coin_flip')\n", (5401, 5440), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((5944, 5990), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""image.decode"""', '"""image_decode"""'], {}), "('image.decode', 'image_decode')\n", (5958, 5990), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((6566, 6626), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""image.target_resize"""', '"""image_target_resize"""'], {}), "('image.target_resize', 'image_target_resize')\n", (6580, 6626), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((7219, 7275), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""image.batch_align"""', '"""image_batch_align"""'], {}), "('image.batch_align', 'image_batch_align')\n", (7233, 7275), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((7825, 7877), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""image.normalize"""', '"""image_normalize"""'], {}), "('image.normalize', 'image_normalize')\n", (7839, 7877), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((8436, 8478), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""image.flip"""', '"""image_flip"""'], {}), "('image.flip', 'image_flip')\n", (8450, 8478), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((9264, 9328), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""detection.object_bbox_flip"""', '"""object_bbox_flip"""'], {}), "('detection.object_bbox_flip', 'object_bbox_flip')\n", (9278, 9328), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((10295, 10361), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""detection.object_bbox_scale"""', '"""object_bbox_scale"""'], {}), "('detection.object_bbox_scale', 'object_bbox_scale')\n", (10309, 10361), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((10895, 10995), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""detection.object_segmentation_polygon_flip"""', '"""object_segmentation_polygon_flip"""'], {}), "('detection.object_segmentation_polygon_flip',\n 'object_segmentation_polygon_flip')\n", (10909, 10995), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((11989, 12091), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""detection.object_segmentation_polygon_scale"""', '"""object_segmentation_polygon_scale"""'], {}), "('detection.object_segmentation_polygon_scale',\n 'object_segmentation_polygon_scale')\n", (12003, 12091), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((12651, 12757), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""detection.object_segmentation_polygon_to_mask"""', '"""object_segmentation_polygon_to_mask"""'], {}), "('detection.object_segmentation_polygon_to_mask',\n 'object_segmentation_polygon_to_mask')\n", (12665, 12757), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((13508, 13542), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""data.coco_reader"""'], {}), "('data.coco_reader')\n", (13522, 13542), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((1351, 1391), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""OFRecordRawDecoder_"""'], {}), "('OFRecordRawDecoder_')\n", (1368, 1391), True, 'import oneflow.python.framework.id_util as id_util\n'), ((2289, 2341), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""OFRecordImageDecoderRandomCrop_"""'], {}), "('OFRecordImageDecoderRandomCrop_')\n", (2306, 2341), True, 'import oneflow.python.framework.id_util as id_util\n'), ((3085, 3127), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""OFRecordImageDecoder_"""'], {}), "('OFRecordImageDecoder_')\n", (3102, 3127), True, 'import oneflow.python.framework.id_util as id_util\n'), ((3732, 3765), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""ImageResize_"""'], {}), "('ImageResize_')\n", (3749, 3765), True, 'import oneflow.python.framework.id_util as id_util\n'), ((4711, 4752), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""CropMirrorNormalize_"""'], {}), "('CropMirrorNormalize_')\n", (4728, 4752), True, 'import oneflow.python.framework.id_util as id_util\n'), ((5624, 5654), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""CoinFlip_"""'], {}), "('CoinFlip_')\n", (5641, 5654), True, 'import oneflow.python.framework.id_util as id_util\n'), ((6240, 6273), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""ImageDecode_"""'], {}), "('ImageDecode_')\n", (6257, 6273), True, 'import oneflow.python.framework.id_util as id_util\n'), ((6842, 6881), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""ImageTargetResize_"""'], {}), "('ImageTargetResize_')\n", (6859, 6881), True, 'import oneflow.python.framework.id_util as id_util\n'), ((7477, 7514), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""ImageBatchAlign_"""'], {}), "('ImageBatchAlign_')\n", (7494, 7514), True, 'import oneflow.python.framework.id_util as id_util\n'), ((8054, 8090), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""ImageNormalize_"""'], {}), "('ImageNormalize_')\n", (8071, 8090), True, 'import oneflow.python.framework.id_util as id_util\n'), ((8663, 8694), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""ImageFlip_"""'], {}), "('ImageFlip_')\n", (8680, 8694), True, 'import oneflow.python.framework.id_util as id_util\n'), ((9642, 9678), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""ObjectBboxFlip_"""'], {}), "('ObjectBboxFlip_')\n", (9659, 9678), True, 'import oneflow.python.framework.id_util as id_util\n'), ((10616, 10653), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""ObjectBboxScale_"""'], {}), "('ObjectBboxScale_')\n", (10633, 10653), True, 'import oneflow.python.framework.id_util as id_util\n'), ((11316, 11356), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""ObjectSegmPolyFilp_"""'], {}), "('ObjectSegmPolyFilp_')\n", (11333, 11356), True, 'import oneflow.python.framework.id_util as id_util\n'), ((12353, 12393), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""ObjectSegmPolyFilp_"""'], {}), "('ObjectSegmPolyFilp_')\n", (12370, 12393), True, 'import oneflow.python.framework.id_util as id_util\n'), ((13153, 13195), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""ObjectSegmPolyToMask_"""'], {}), "('ObjectSegmPolyToMask_')\n", (13170, 13195), True, 'import oneflow.python.framework.id_util as id_util\n'), ((14729, 14768), 'oneflow.python.framework.module.Module.__init__', 'module_util.Module.__init__', (['self', 'name'], {}), '(self, name)\n', (14756, 14768), True, 'import oneflow.python.framework.module as module_util\n'), ((14691, 14720), 'random.randrange', 'random.randrange', (['sys.maxsize'], {}), '(sys.maxsize)\n', (14707, 14720), False, 'import random\n'), ((15676, 15707), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""COCOReader"""'], {}), "('COCOReader')\n", (15693, 15707), True, 'import oneflow.python.framework.id_util as id_util\n'), ((4772, 4798), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (4792, 4798), True, 'import oneflow as flow\n'), ((9043, 9069), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (9063, 9069), True, 'import oneflow as flow\n'), ((10674, 10700), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (10694, 10700), True, 'import oneflow as flow\n'), ((12414, 12440), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (12434, 12440), True, 'import oneflow as flow\n'), ((6294, 6320), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (6314, 6320), True, 'import oneflow as flow\n'), ((8197, 8223), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (8217, 8223), True, 'import oneflow as flow\n'), ((10024, 10050), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (10044, 10050), True, 'import oneflow as flow\n'), ((11702, 11728), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (11722, 11728), True, 'import oneflow as flow\n'), ((13216, 13242), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (13236, 13242), True, 'import oneflow as flow\n'), ((7535, 7561), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (7555, 7561), True, 'import oneflow as flow\n'), ((6902, 6928), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (6922, 6928), True, 'import oneflow as flow\n'), ((3149, 3175), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (3169, 3175), True, 'import oneflow as flow\n'), ((5677, 5703), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (5697, 5703), True, 'import oneflow as flow\n'), ((1413, 1439), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (1433, 1439), True, 'import oneflow as flow\n'), ((3787, 3813), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (3807, 3813), True, 'import oneflow as flow\n'), ((2363, 2389), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (2383, 2389), True, 'import oneflow as flow\n'), ((14816, 14868), 'oneflow.consistent_user_op_module_builder', 'flow.consistent_user_op_module_builder', (['"""COCOReader"""'], {}), "('COCOReader')\n", (14854, 14868), 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 unittest
from collections import OrderedDict
import numpy as np
from oneflow.test_utils.automated_test_util import *
from oneflow.test_utils.test_util import GenArgList
import oneflow as flow
import oneflow.unittest
import torch
import random
def _test_rnn(test_case, device):
l = ["tanh", "relu"]
input_size = random.randint(10, 1000)
hidden_size = random.randint(10, 1000)
num_layers = random.randint(1, 6)
nonlinearity = l[0 if num_layers <= 3 else 1]
bias = random.randint(-10, 10) <= 0
batch_first = random.randint(-10, 10) <= 0
dropout = 0
bidirectional = random.randint(-10, 10) <= 0
rnn_torch = torch.nn.RNN(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
nonlinearity=nonlinearity,
bias=bias,
batch_first=batch_first,
dropout=0,
bidirectional=bidirectional,
).to(device)
weights_torch = []
for w in rnn_torch.parameters():
weights_torch.append(
w.permute(1, 0).cpu().data.numpy()
if len(w.size()) > 1
else w.cpu().data.numpy()
)
rnn_flow = flow.nn.RNN(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
nonlinearity=nonlinearity,
bias=bias,
batch_first=batch_first,
dropout=0,
bidirectional=bidirectional,
).to(device)
for i, w in enumerate(rnn_flow.parameters()):
w_torch = weights_torch[i]
w.copy_(flow.tensor(w_torch))
x = np.random.rand(32, 10, input_size)
x_torch = torch.tensor(x, dtype=torch.float32, requires_grad=True).to(device)
x_flow = flow.tensor(x, dtype=flow.float32, requires_grad=True).to(device)
out_torch, hid_torch = rnn_torch(x_torch)
out_flow, hid_flow = rnn_flow(x_flow)
test_case.assertTrue(
np.allclose(
out_torch.cpu().data.numpy(),
out_flow.cpu().data.numpy(),
rtol=1e-05,
atol=1e-05,
)
)
z_torch = out_torch.sum()
z_torch.backward()
z_flow = out_flow.sum()
z_flow.backward()
test_case.assertTrue(
np.allclose(x_torch.cpu().data.numpy(), x_flow.cpu().data.numpy())
)
def _test_lstm(test_case, device):
input_size = random.randint(10, 1000)
hidden_size = random.randint(12, 1000)
num_layers = random.randint(1, 6)
bias = random.randint(-10, 10) <= 0
batch_first = random.randint(-10, 10) <= 0
dropout = 0
bidirectional = random.randint(-10, 10) <= 0
proj_size = random.randint(10, hidden_size - 1)
lstm_torch = torch.nn.LSTM(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
bias=bias,
batch_first=batch_first,
dropout=0,
bidirectional=bidirectional,
proj_size=proj_size,
).to(device)
weights_torch = []
for w in lstm_torch.parameters():
weights_torch.append(
w.permute(1, 0).cpu().data.numpy()
if len(w.size()) > 1
else w.cpu().data.numpy()
)
lstm_flow = flow.nn.LSTM(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
bias=bias,
batch_first=batch_first,
dropout=0,
bidirectional=bidirectional,
proj_size=proj_size,
).to(device)
for i, w in enumerate(lstm_flow.parameters()):
w_torch = weights_torch[i]
w.copy_(flow.tensor(w_torch))
x = np.random.rand(32, 10, input_size)
x_torch = torch.tensor(x, dtype=torch.float32, requires_grad=True).to(device)
x_flow = flow.tensor(x, dtype=flow.float32, requires_grad=True).to(device)
out_torch, hid_torch = lstm_torch(x_torch)
out_flow, hid_flow = lstm_flow(x_flow)
test_case.assertTrue(
np.allclose(
out_torch.cpu().data.numpy(),
out_flow.cpu().data.numpy(),
rtol=1e-05,
atol=1e-05,
)
)
z_torch = out_torch.sum()
z_torch.backward()
z_flow = out_flow.sum()
z_flow.backward()
test_case.assertTrue(
np.allclose(x_torch.cpu().data.numpy(), x_flow.cpu().data.numpy())
)
def _test_gru(test_case, device):
input_size = random.randint(10, 1000)
hidden_size = random.randint(10, 1000)
num_layers = random.randint(1, 6)
bias = bool(random.randint(-5, 5))
batch_first = bool(random.randint(-5, 5))
dropout = 0
bidirectional = bool(random.randint(-5, 5))
gru_torch = torch.nn.GRU(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
bias=bias,
batch_first=batch_first,
dropout=0,
bidirectional=bidirectional,
).to(device)
weights_torch = []
for w in gru_torch.parameters():
weights_torch.append(
w.permute(1, 0).cpu().data.numpy()
if len(w.size()) > 1
else w.cpu().data.numpy()
)
gru_flow = flow.nn.GRU(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
bias=bias,
batch_first=batch_first,
dropout=0,
bidirectional=bidirectional,
).to(device)
for i, w in enumerate(gru_flow.parameters()):
w_torch = weights_torch[i]
w.copy_(flow.tensor(w_torch))
x = np.random.rand(32, 10, input_size)
x_torch = torch.tensor(x, dtype=torch.float32, requires_grad=True).to(device)
x_flow = flow.tensor(x, dtype=flow.float32, requires_grad=True).to(device)
out_torch, hid_torch = gru_torch(x_torch)
out_flow, hid_flow = gru_flow(x_flow)
test_case.assertTrue(
np.allclose(
out_torch.cpu().data.numpy(),
out_flow.cpu().data.numpy(),
rtol=1e-05,
atol=1e-05,
)
)
z_torch = out_torch.sum()
z_torch.backward()
z_flow = out_flow.sum()
z_flow.backward()
test_case.assertTrue(
np.allclose(x_torch.cpu().data.numpy(), x_flow.cpu().data.numpy())
)
@flow.unittest.skip_unless_1n1d()
class TestRNNModule(flow.unittest.TestCase):
def test_rnn(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [_test_rnn, _test_lstm, _test_gru]
arg_dict["device"] = ["cuda", "cpu"]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
if __name__ == "__main__":
unittest.main()
| [
"oneflow.nn.LSTM",
"oneflow.nn.GRU",
"oneflow.nn.RNN",
"oneflow.unittest.skip_unless_1n1d",
"oneflow.tensor",
"oneflow.test_utils.test_util.GenArgList"
] | [((6668, 6700), 'oneflow.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (6698, 6700), True, 'import oneflow as flow\n'), ((923, 947), 'random.randint', 'random.randint', (['(10)', '(1000)'], {}), '(10, 1000)\n', (937, 947), False, 'import random\n'), ((966, 990), 'random.randint', 'random.randint', (['(10)', '(1000)'], {}), '(10, 1000)\n', (980, 990), False, 'import random\n'), ((1008, 1028), 'random.randint', 'random.randint', (['(1)', '(6)'], {}), '(1, 6)\n', (1022, 1028), False, 'import random\n'), ((2153, 2187), 'numpy.random.rand', 'np.random.rand', (['(32)', '(10)', 'input_size'], {}), '(32, 10, input_size)\n', (2167, 2187), True, 'import numpy as np\n'), ((2897, 2921), 'random.randint', 'random.randint', (['(10)', '(1000)'], {}), '(10, 1000)\n', (2911, 2921), False, 'import random\n'), ((2940, 2964), 'random.randint', 'random.randint', (['(12)', '(1000)'], {}), '(12, 1000)\n', (2954, 2964), False, 'import random\n'), ((2982, 3002), 'random.randint', 'random.randint', (['(1)', '(6)'], {}), '(1, 6)\n', (2996, 3002), False, 'import random\n'), ((3171, 3206), 'random.randint', 'random.randint', (['(10)', '(hidden_size - 1)'], {}), '(10, hidden_size - 1)\n', (3185, 3206), False, 'import random\n'), ((4123, 4157), 'numpy.random.rand', 'np.random.rand', (['(32)', '(10)', 'input_size'], {}), '(32, 10, input_size)\n', (4137, 4157), True, 'import numpy as np\n'), ((4868, 4892), 'random.randint', 'random.randint', (['(10)', '(1000)'], {}), '(10, 1000)\n', (4882, 4892), False, 'import random\n'), ((4911, 4935), 'random.randint', 'random.randint', (['(10)', '(1000)'], {}), '(10, 1000)\n', (4925, 4935), False, 'import random\n'), ((4953, 4973), 'random.randint', 'random.randint', (['(1)', '(6)'], {}), '(1, 6)\n', (4967, 4973), False, 'import random\n'), ((5975, 6009), 'numpy.random.rand', 'np.random.rand', (['(32)', '(10)', 'input_size'], {}), '(32, 10, input_size)\n', (5989, 6009), True, 'import numpy as np\n'), ((7033, 7048), 'unittest.main', 'unittest.main', ([], {}), '()\n', (7046, 7048), False, 'import unittest\n'), ((1090, 1113), 'random.randint', 'random.randint', (['(-10)', '(10)'], {}), '(-10, 10)\n', (1104, 1113), False, 'import random\n'), ((1137, 1160), 'random.randint', 'random.randint', (['(-10)', '(10)'], {}), '(-10, 10)\n', (1151, 1160), False, 'import random\n'), ((1202, 1225), 'random.randint', 'random.randint', (['(-10)', '(10)'], {}), '(-10, 10)\n', (1216, 1225), False, 'import random\n'), ((3014, 3037), 'random.randint', 'random.randint', (['(-10)', '(10)'], {}), '(-10, 10)\n', (3028, 3037), False, 'import random\n'), ((3061, 3084), 'random.randint', 'random.randint', (['(-10)', '(10)'], {}), '(-10, 10)\n', (3075, 3084), False, 'import random\n'), ((3126, 3149), 'random.randint', 'random.randint', (['(-10)', '(10)'], {}), '(-10, 10)\n', (3140, 3149), False, 'import random\n'), ((4990, 5011), 'random.randint', 'random.randint', (['(-5)', '(5)'], {}), '(-5, 5)\n', (5004, 5011), False, 'import random\n'), ((5036, 5057), 'random.randint', 'random.randint', (['(-5)', '(5)'], {}), '(-5, 5)\n', (5050, 5057), False, 'import random\n'), ((5100, 5121), 'random.randint', 'random.randint', (['(-5)', '(5)'], {}), '(-5, 5)\n', (5114, 5121), False, 'import random\n'), ((6794, 6807), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (6805, 6807), False, 'from collections import OrderedDict\n'), ((6938, 6958), 'oneflow.test_utils.test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (6948, 6958), False, 'from oneflow.test_utils.test_util import GenArgList\n'), ((1248, 1444), 'torch.nn.RNN', 'torch.nn.RNN', ([], {'input_size': 'input_size', 'hidden_size': 'hidden_size', 'num_layers': 'num_layers', 'nonlinearity': 'nonlinearity', 'bias': 'bias', 'batch_first': 'batch_first', 'dropout': '(0)', 'bidirectional': 'bidirectional'}), '(input_size=input_size, hidden_size=hidden_size, num_layers=\n num_layers, nonlinearity=nonlinearity, bias=bias, batch_first=\n batch_first, dropout=0, bidirectional=bidirectional)\n', (1260, 1444), False, 'import torch\n'), ((1752, 1947), 'oneflow.nn.RNN', 'flow.nn.RNN', ([], {'input_size': 'input_size', 'hidden_size': 'hidden_size', 'num_layers': 'num_layers', 'nonlinearity': 'nonlinearity', 'bias': 'bias', 'batch_first': 'batch_first', 'dropout': '(0)', 'bidirectional': 'bidirectional'}), '(input_size=input_size, hidden_size=hidden_size, num_layers=\n num_layers, nonlinearity=nonlinearity, bias=bias, batch_first=\n batch_first, dropout=0, bidirectional=bidirectional)\n', (1763, 1947), True, 'import oneflow as flow\n'), ((2122, 2142), 'oneflow.tensor', 'flow.tensor', (['w_torch'], {}), '(w_torch)\n', (2133, 2142), True, 'import oneflow as flow\n'), ((2202, 2258), 'torch.tensor', 'torch.tensor', (['x'], {'dtype': 'torch.float32', 'requires_grad': '(True)'}), '(x, dtype=torch.float32, requires_grad=True)\n', (2214, 2258), False, 'import torch\n'), ((2283, 2337), 'oneflow.tensor', 'flow.tensor', (['x'], {'dtype': 'flow.float32', 'requires_grad': '(True)'}), '(x, dtype=flow.float32, requires_grad=True)\n', (2294, 2337), True, 'import oneflow as flow\n'), ((3225, 3415), 'torch.nn.LSTM', 'torch.nn.LSTM', ([], {'input_size': 'input_size', 'hidden_size': 'hidden_size', 'num_layers': 'num_layers', 'bias': 'bias', 'batch_first': 'batch_first', 'dropout': '(0)', 'bidirectional': 'bidirectional', 'proj_size': 'proj_size'}), '(input_size=input_size, hidden_size=hidden_size, num_layers=\n num_layers, bias=bias, batch_first=batch_first, dropout=0,\n bidirectional=bidirectional, proj_size=proj_size)\n', (3238, 3415), False, 'import torch\n'), ((3726, 3915), 'oneflow.nn.LSTM', 'flow.nn.LSTM', ([], {'input_size': 'input_size', 'hidden_size': 'hidden_size', 'num_layers': 'num_layers', 'bias': 'bias', 'batch_first': 'batch_first', 'dropout': '(0)', 'bidirectional': 'bidirectional', 'proj_size': 'proj_size'}), '(input_size=input_size, hidden_size=hidden_size, num_layers=\n num_layers, bias=bias, batch_first=batch_first, dropout=0,\n bidirectional=bidirectional, proj_size=proj_size)\n', (3738, 3915), True, 'import oneflow as flow\n'), ((4092, 4112), 'oneflow.tensor', 'flow.tensor', (['w_torch'], {}), '(w_torch)\n', (4103, 4112), True, 'import oneflow as flow\n'), ((4172, 4228), 'torch.tensor', 'torch.tensor', (['x'], {'dtype': 'torch.float32', 'requires_grad': '(True)'}), '(x, dtype=torch.float32, requires_grad=True)\n', (4184, 4228), False, 'import torch\n'), ((4253, 4307), 'oneflow.tensor', 'flow.tensor', (['x'], {'dtype': 'flow.float32', 'requires_grad': '(True)'}), '(x, dtype=flow.float32, requires_grad=True)\n', (4264, 4307), True, 'import oneflow as flow\n'), ((5140, 5308), 'torch.nn.GRU', 'torch.nn.GRU', ([], {'input_size': 'input_size', 'hidden_size': 'hidden_size', 'num_layers': 'num_layers', 'bias': 'bias', 'batch_first': 'batch_first', 'dropout': '(0)', 'bidirectional': 'bidirectional'}), '(input_size=input_size, hidden_size=hidden_size, num_layers=\n num_layers, bias=bias, batch_first=batch_first, dropout=0,\n bidirectional=bidirectional)\n', (5152, 5308), False, 'import torch\n'), ((5609, 5776), 'oneflow.nn.GRU', 'flow.nn.GRU', ([], {'input_size': 'input_size', 'hidden_size': 'hidden_size', 'num_layers': 'num_layers', 'bias': 'bias', 'batch_first': 'batch_first', 'dropout': '(0)', 'bidirectional': 'bidirectional'}), '(input_size=input_size, hidden_size=hidden_size, num_layers=\n num_layers, bias=bias, batch_first=batch_first, dropout=0,\n bidirectional=bidirectional)\n', (5620, 5776), True, 'import oneflow as flow\n'), ((5944, 5964), 'oneflow.tensor', 'flow.tensor', (['w_torch'], {}), '(w_torch)\n', (5955, 5964), True, 'import oneflow as flow\n'), ((6024, 6080), 'torch.tensor', 'torch.tensor', (['x'], {'dtype': 'torch.float32', 'requires_grad': '(True)'}), '(x, dtype=torch.float32, requires_grad=True)\n', (6036, 6080), False, 'import torch\n'), ((6105, 6159), 'oneflow.tensor', 'flow.tensor', (['x'], {'dtype': 'flow.float32', 'requires_grad': '(True)'}), '(x, dtype=flow.float32, requires_grad=True)\n', (6116, 6159), 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.
"""
from typing import List, Tuple
import oneflow as flow
from oneflow.framework.tensor import Tensor, register_tensor_op
@register_tensor_op("stack")
def stack(inputs: Tensor, dim: int = 0) -> None:
"""Concatenates a sequence of tensors along a new dimension.
The returned tensor shares the same underlying data with input tensors.
A :attr:`dim` value within the range `[-input.ndimension() - 1, input.ndimension() + 1]`
can be used. Negative :attr:`dim` will correspond to :meth:`stack`
applied at :attr:`dim` = ``dim + input.ndimension() + 1``.
Args:
inputs (List[oneflow.Tensor]): the list of input tensors. Each tensor should have the same shape.
dim (int): the index at which to insert the concatenated dimension.
Returns:
A `Tensor`
For example:
.. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> x = flow.Tensor(np.random.rand(1, 3, 5))
>>> y = flow.Tensor(np.random.rand(1, 3, 5))
>>> out = flow.stack([x, y], dim = -1)
>>> out.shape
flow.Size([1, 3, 5, 2])
"""
assert isinstance(inputs, (List, Tuple))
input_shape = inputs[0].shape
max_dim = len(input_shape)
if dim < 0:
dim = dim + max_dim + 1
assert dim >= 0 and dim <= max_dim
input_list_length = len(inputs)
unsqueezed = list()
for i in range(input_list_length):
current_shape = inputs[i].shape
assert (
input_shape == current_shape
), "Each tensor should have the same shape ! Found a tensor instance shape is: {}".format(
current_shape
)
unsqueezed.append(inputs[i].unsqueeze(dim))
return flow.cat(unsqueezed, dim)
if __name__ == "__main__":
import doctest
doctest.testmod(raise_on_error=True)
| [
"oneflow.cat",
"oneflow.framework.tensor.register_tensor_op"
] | [((712, 739), 'oneflow.framework.tensor.register_tensor_op', 'register_tensor_op', (['"""stack"""'], {}), "('stack')\n", (730, 739), False, 'from oneflow.framework.tensor import Tensor, register_tensor_op\n'), ((2305, 2330), 'oneflow.cat', 'flow.cat', (['unsqueezed', 'dim'], {}), '(unsqueezed, dim)\n', (2313, 2330), True, 'import oneflow as flow\n'), ((2384, 2420), 'doctest.testmod', 'doctest.testmod', ([], {'raise_on_error': '(True)'}), '(raise_on_error=True)\n', (2399, 2420), False, 'import doctest\n')] |
import numpy as np
import oneflow as flow
import oneflow.core.operator.op_conf_pb2 as op_conf_util
from flow_utils import *
from resnet import resnet50
class Yolov3_tiny:
def __init__(self, cfg, trainable, data_format='NCHW'):
self.class_num = cfg.YOLO.CLASS_NUM
self.anchor_per_scale = cfg.YOLO.ANCHOR_PER_SCALE
self.iou_loss_thresh = cfg.YOLO.IOU_LOSS_THRESH
self.strides = cfg.YOLO.STRIDES
self.focus_loss_alpha = cfg.TRAIN.FOCUS_LOSS_ALPHA
self.focus_loss_gamma = cfg.TRAIN.FOCUS_LOSS_GAMMA
self.loss_giou_alpha = cfg.TRAIN.LOSS_GIOU_ALPHA
self.loss_conf_alpha = cfg.TRAIN.LOSS_CONF_ALPHA
self.loss_preb_alpha = cfg.TRAIN.LOSS_PRED_ALPHA
self.trainable = trainable
self.data_format = data_format
def backbone(self, in_blob):
'''
backbone
:param in_blob: [N, 3, 416, 416]
:return: [[N, 256, 26, 26],[N, 1024, 13, 13]]
'''
backbone_descripts = [
{'op': 'conv', 'kernal_size': 3, 'stride': 1, 'output_channel': 16}, # 416*416*16
{'op': 'max_pool', 'kernal_size': 2, 'stride': 2}, # 208*208*16
{'op': 'conv', 'kernal_size': 3, 'stride': 1, 'output_channel': 32}, # 208*208*32
{'op': 'max_pool', 'kernal_size': 2, 'stride': 2}, # 104*104*16
{'op': 'conv', 'kernal_size': 3, 'stride': 1, 'output_channel': 64}, # 104*104*64
{'op': 'max_pool', 'kernal_size': 2, 'stride': 2}, # 52*52*64
{'op': 'conv', 'kernal_size': 3, 'stride': 1, 'output_channel': 128}, # 52*52*128
{'op': 'max_pool', 'kernal_size': 2, 'stride': 2}, # 26*26*128
{'op': 'conv', 'kernal_size': 3, 'stride': 1, 'output_channel': 256, 'route': True}, # 26*26*256
{'op': 'max_pool', 'kernal_size': 2, 'stride': 2}, # 13*13*256
{'op': 'conv', 'kernal_size': 3, 'stride': 1, 'output_channel': 512}, # 13*13*512
{'op': 'max_pool', 'kernal_size': 2, 'stride': 1}, # 13*13*512
{'op': 'conv', 'kernal_size': 3, 'stride': 1, 'output_channel': 1024, 'route': True}, # 13*13*1024
]
blob = in_blob
routes = []
# backbone
for i, desc in enumerate(backbone_descripts):
if desc['op'] == 'conv':
blob = conv_unit(blob, num_filter=desc['output_channel'],
kernel=[desc['kernal_size'], desc['kernal_size']],
stride=[desc['stride'], desc['stride']],
data_format=self.data_format, use_bias=False,
trainable=self.trainable, prefix='yolo-backbone' + str(i))
elif desc['op'] == 'max_pool':
blob = max_pooling(blob, kernel=desc['kernal_size'], stride=desc['stride'],
data_format=self.data_format,
name='yolo-backbone' + str(i) + 'max_pool')
if 'route' in desc and desc['route'] is not None and desc['route']:
routes.append(blob)
return routes
# def backbone_resnet(self, in_blob):
# routes = resnet50(in_blob, self.trainable, self.trainable)
# return routes
def network(self, in_blob):
'''
:param in_blob: [N, 3, 416, 416]
:return: list[[N, 3 * (5 + num_class), 13, 13], [N, 3 * (5 + num_class), 26, 26]
'''
blobs = self.backbone(in_blob)
# yolo_blob1
blob = conv_unit(blobs[-1], num_filter=256,
kernel=[1, 1], stride=[1, 1],
data_format=self.data_format, use_bias=False,
trainable=self.trainable, prefix='yolo-detect1-layer1')
blob1 = conv_unit(blob, num_filter=512,
kernel=[3, 3], stride=[1, 1],
data_format=self.data_format, use_bias=False,
trainable=self.trainable, prefix='yolo-detect1-layer2')
output_channel = (self.class_num + 5) * self.anchor_per_scale
# blob1 = conv2d_layer(name='yolo-detect1-pred', input=blob1, filters=output_channel, kernel_size=(1,1), strides=1,
# padding='same', data_format=self.data_format, dilation_rate=1, activation=None,
# use_bias=False, trainable=self.trainable)
blob1 = conv2d_layer(name='yolo-detect1-pred', input=blob1, filters=output_channel, kernel_size=(1,1), strides=1,
padding='same', data_format=self.data_format, dilation_rate=1, activation=None,
use_bias=True, trainable=self.trainable)
# yolo_blob2
blob = conv_unit(blob, num_filter=128,
kernel=[1, 1], stride=[1, 1],
data_format=self.data_format, use_bias=False,
trainable=self.trainable, prefix='yolo-detect2-layer1')
blob = upsample(blob, name='yolo-detect2-upsample') # 26*26*128
blob = flow.concat([blob, blobs[0]], name='yolo-detect2-concat', axis=1) # 26*26*384
blob = conv_unit(blob, num_filter=256,
kernel=[3, 3], stride=[1, 1],
data_format=self.data_format, use_bias=False,
trainable=self.trainable, prefix='yolo-detect2-layer2')
blob = conv2d_layer(name='yolo-detect2-pred', input=blob, filters=output_channel, kernel_size=(1,1), strides=1,
padding='same', data_format=self.data_format, dilation_rate=1, activation=None,
use_bias=True, trainable=self.trainable)
conv_sbbox = blob
conv_lbbox = blob1
return [conv_lbbox, conv_sbbox]
def decode(self, feature_map, anchors, stride, prefix='yolo'):
'''
return tensor of shape [batch_size, output_size, output_size, anchor_per_scale, 5 + num_classes]
contains (x, y, w, h, score, probability)
:param feature_map: [N, H, W, 3 * (5 + num_class)]
:param anchors: [3, 2]
:param stride:
:return: (x, y, w, h, score, probability)
[pred_xywh, pred_conf, pred_prob]: [N, H, W, 3, 4+1+class_num]
'''
# [N, H, W, 3, 5 + num_class]
feature_map = flow.reshape(feature_map, shape=(feature_map.shape[0], feature_map.shape[1], feature_map.shape[2],
self.anchor_per_scale, -1))
# shape: [N, H, W, 3, 2]
box_centers = flow.slice(feature_map, begin=[None, None, None, None, 0], size=[None, None, None, None, 2])
# shape: [N, H, W, 3, 2]
box_sizes = flow.slice(feature_map, begin=[None, None, None, None, 2], size=[None, None, None, None, 2])
# shape: [N, H, W, 3, 1]
conf_logits = flow.slice(feature_map, begin=[None, None, None, None, 4], size=[None, None, None, None, 1])
# shape: [N, H, W, 3, class_num]
prob_logits = flow.slice(feature_map, begin=[None, None, None, None, 5],
size=[None, None, None, None, feature_map.shape[-1] - 5])
# obtain the x_y_offset
grid_size = feature_map.shape[1:3]
grid_x = flow.range(grid_size[1], dtype=flow.float32, name=prefix+'_decode_range1')
grid_x = flow.expand_dims(grid_x, axis=0)
like_tensor = flow.constant(value=1.0, dtype=flow.float32, shape=(grid_size[0], grid_size[1]))
grid_x = flow.broadcast_like(grid_x, like_tensor,broadcast_axes=(0, ), name = prefix+'yolo_grid_x')
grid_y = flow.range(grid_size[0], dtype=flow.float32, name=prefix+'_yolo_decode_range2')
grid_y = flow.expand_dims(grid_y, axis=1)
grid_y = flow.broadcast_like(grid_y, like_tensor,broadcast_axes=(1, ), name = prefix+'yolo_grid_y')
x_offset = flow.expand_dims(grid_x, axis=-1)
y_offset = flow.expand_dims(grid_y, axis=-1)
#shape: [1, H, W, 1 ,2]
x_y_offset = flow.concat([x_offset, y_offset], axis=-1)
x_y_offset = flow.expand_dims(x_y_offset, axis=0)
x_y_offset = flow.expand_dims(x_y_offset, axis=-2)
pred_xy = (flow.math.sigmoid(box_centers) + x_y_offset) * stride
pred_wh = (flow.math.exp(box_sizes) * anchors) * stride # anchor relative to the feature map
# shape: [N, H, W, 3, 4]
pred_xywh = flow.concat([pred_xy, pred_wh], axis=-1)
pred_conf = flow.math.sigmoid(conf_logits)
pred_prob = flow.math.sigmoid(prob_logits)
pred = flow.concat([pred_xywh, pred_conf, pred_prob], axis=-1)
# shape:
# pred: [N, H, W, 3, 4+1+class_num]
# x_y_offset: [1, H, W, 1, 2]
return pred, x_y_offset
def bbox_giou(self, boxes1, boxes2):
''' (x, y, w, h)
:param boxes1: [N, H, W, 3, 4] (x, y, w, h)
:param boxes2: [N, H, W, 3, 4] (x, y, w, h)
:return: [N, H, W, 3, 1]
'''
def convert(box_xywh):
box_xy = flow.slice(box_xywh, begin=[None, None, None, None, 0], size=[None, None, None, None, 2])
box_wh = flow.slice(box_xywh, begin=[None, None, None, None, 2], size=[None, None, None, None, 2])
box_lt = box_xy - box_wh * 0.5
box_rb = box_xy + box_wh * 0.5
box_lt = flow.math.minimum(box_lt, box_rb)
box_rb = flow.math.maximum(box_lt, box_rb)
return box_lt, box_rb
boxes1_lt, boxes1_rb = convert(boxes1)
boxes1_wh = boxes1_rb - boxes1_lt
# boxes1_wh = flow.math.clip_by_value(boxes1_rb - boxes1_lt, min_value=0)
boxes1_area = flow.slice(boxes1_wh, begin=[None, None, None, None, 0], size=[None, None, None, None, 1]) * \
flow.slice(boxes1_wh, begin=[None, None, None, None, 1], size=[None, None, None, None, 1])
boxes2_lt, boxes2_rb = convert(boxes2)
boxes2_wh = boxes2_rb - boxes2_lt
# boxes2_wh = flow.math.clip_by_value(boxes2_rb - boxes2_lt, min_value=0)
boxes2_area = flow.slice(boxes2_wh, begin=[None, None, None, None, 0], size=[None, None, None, None, 1]) * \
flow.slice(boxes2_wh, begin=[None, None, None, None, 1], size=[None, None, None, None, 1])
left_up = flow.math.maximum(boxes1_lt, boxes2_lt)
right_down = flow.math.minimum(boxes1_rb, boxes2_rb)
inter_section_wh = flow.math.clip_by_value(right_down - left_up, min_value = 0.0)
inter_area = flow.slice(inter_section_wh, begin=[None, None, None, None, 0], size=[None, None, None, None, 1]) * \
flow.slice(inter_section_wh, begin=[None, None, None, None, 1], size=[None, None, None, None, 1])
union_area = boxes1_area + boxes2_area - inter_area
iou = inter_area / (union_area + 1e-6)
# added 1e-6 in denominator to avoid generation of inf, which may cause nan loss
enclose_left_up = flow.math.minimum(boxes1_lt, boxes2_lt)
enclose_right_down = flow.math.maximum(boxes1_rb, boxes2_rb)
enclose_wh = flow.math.clip_by_value(enclose_right_down - enclose_left_up, min_value = 0.0)
enclose_area = flow.slice(enclose_wh, begin=[None, None, None, None, 0], size=[None, None, None, None, 1]) * \
flow.slice(enclose_wh, begin=[None, None, None, None, 1], size=[None, None, None, None, 1])
giou = iou - 1.0 * (enclose_area - union_area) / (enclose_area + 1e-6)
# added 1e-6 in denominator to avoid generation of inf, which may cause nan loss
return giou
def bbox_iou(self, boxes1, boxes2):
'''
:param boxes1: [N, H, W, 3, 1, 4] (x, y, w, h)
:param boxes2: [N, 1, 1, 1, V 4] (x, y, w, h)
:return: [N, H, W, 3, V, 1]
'''
def convert(box_xywh):
box_xy = flow.slice(box_xywh, begin=[None, None, None, None, None, 0],
size=[None, None, None, None, None, 2])
box_wh = flow.slice(box_xywh, begin=[None, None, None, None, None, 2],
size=[None, None, None, None, None, 2])
box_lt = box_xy - box_wh * 0.5
box_rb = box_xy + box_wh * 0.5
box_lt = flow.math.minimum(box_lt, box_rb)
box_rb = flow.math.maximum(box_lt, box_rb)
return box_lt, box_rb
boxes1_lt, boxes1_rb = convert(boxes1)
boxes1_wh = boxes1_rb - boxes1_lt
boxes1_area = flow.slice(boxes1_wh, begin=[None, None, None, None, None, 0],
size=[None, None, None, None, None, 1]) * \
flow.slice(boxes1_wh, begin=[None, None, None, None, None, 1],
size=[None, None, None, None, None, 1])
boxes2_lt, boxes2_rb = convert(boxes2)
boxes2_wh = boxes2_rb - boxes2_lt
boxes2_area = flow.slice(boxes2_wh, begin=[None, None, None, None, None, 0],
size=[None, None, None, None, None, 1]) * \
flow.slice(boxes2_wh, begin=[None, None, None, None, None, 1],
size=[None, None, None, None, None, 1])
left_up = flow.math.maximum(boxes1_lt, boxes2_lt)
right_down = flow.math.minimum(boxes1_rb, boxes2_rb)
inter_section_wh = flow.math.clip_by_value(right_down - left_up, min_value = 0.0)
inter_area = flow.slice(inter_section_wh, begin=[None, None, None, None, None, 0],
size=[None, None, None, None, None, 1]) * \
flow.slice(inter_section_wh, begin=[None, None, None, None, None, 1],
size=[None, None, None, None, None, 1])
union_area = boxes1_area + boxes2_area - inter_area
iou = 1.0 * inter_area / (union_area + 1e-6)
return iou
def focal(self, target, actual):
focal_loss = flow.math.abs(self.focus_loss_alpha + target - 1) * flow.math.pow(flow.math.abs(target - actual), self.focus_loss_gamma)
# focal_loss = self.focus_loss_alpha * flow.math.pow(flow.math.abs(target - actual), self.focus_loss_gamma)
return focal_loss
def loss_layer(self, feature_map, pred, label, bboxes, stride, prefix = 'loss_layer'):
'''
:param feature_map: [N, H, W, 3*(5+class_num)]
:param pred: [N, H, W, 3, 4+1+class_num]
:param label: [N, H, W, 3, 4+1+class_num]
:param bboxes: [N, V, 4]
:param stride:
:param anchor_per_scale:
:return:
giou_loss:
conf_loss:
prob_loss:
'''
feature_map = flow.reshape(feature_map, shape=(
feature_map.shape[0], feature_map.shape[1], feature_map.shape[2], self.anchor_per_scale, -1))
# shape: [N, H, W, 3, 1]
raw_conf = flow.slice(feature_map, begin=[None, None, None, None, 4], size=[None, None, None, None, 1])
# shape: [N, H, W, 3, class_num]
raw_prob = flow.slice(feature_map, begin=[None, None, None, None, 5],
size=[None, None, None, None, feature_map.shape[-1] - 5])
# [N, H, W, 3, 4]
pred_xywh = flow.slice(pred, begin=[None, None, None, None, 0], size=[None, None, None, None, 4])
pred_conf = flow.slice(pred, begin=[None, None, None, None, 4], size=[None, None, None, None, 1])
#flow.slice(label, begin=[None, None, None, None, 0], size=[None, None, None, None, 4])
label_xywh = flow.slice(label, begin=[None, None, None, None, 0], size=[None, None, None, None, 4])
respond_bbox = flow.slice(label, begin=[None, None, None, None, 4], size=[None, None, None, None, 1])
label_prob = flow.slice(label, begin=[None, None, None, None, 5],
size=[None, None, None, None, label.shape[-1] - 5])
# [N, H, W, 3, 1]
giou = self.bbox_giou(pred_xywh, label_xywh)
# label_w = flow.slice(label, begin=[None, None, None, None, 2], size=[None, None, None, None, 1])
# label_h = flow.slice(label, begin=[None, None, None, None, 3], size=[None, None, None, None, 1])
# bbox_loss_scale = 2.0 - 1.0 * label_w * label_h / ((stride * feature_map.shape[1]) ** 2) #???
# [N, H, W, 3, 1]
# giou_loss = respond_bbox * bbox_loss_scale * (1 - giou)
giou_loss = respond_bbox * (1 - giou)
# [N, 1, 1, 1, V, 4]
bboxes_ = flow.expand_dims(bboxes, axis = 1)
bboxes_ = flow.expand_dims(bboxes_, axis = 1)
bboxes_ = flow.expand_dims(bboxes_, axis = 1)
# [N, H, W, 3, V]
iou = self.bbox_iou(flow.expand_dims(pred_xywh, axis=-2),bboxes_)
iou = flow.squeeze(iou, axis=[-1,])
# [N, H, W, 3, 1]
max_iou = flow.math.reduce_max(iou, axis=-1, keepdims=True)
# respond_bgd = (1.0 - respond_bbox) * (max_iou < self.iou_loss_thresh)
tmp = flow.math.less(max_iou, flow.constant_like(like=max_iou, value=self.iou_loss_thresh, dtype=flow.float32))
# respond_bgd = (1.0 - respond_bbox) * tmp
respond_bgd = flow.where(tmp, 1.0 - respond_bbox,
flow.zeros_like(respond_bbox, dtype=flow.float32))
# [N, H, W, 3, 1]
# ce = flow.nn.sigmoid_cross_entropy_with_logits(labels=respond_bbox, logits=raw_conf)
# alpha_t = respond_bbox*self.focus_loss_alpha+(1.0-respond_bbox)*(1.0-self.focus_loss_alpha)
# conf_loss = alpha_t*flow.math.pow(1.0-flow.math.exp(flow.math.negative(ce)), self.focus_loss_gamma)*ce
# conf_loss = (respond_bbox+respond_bgd)*conf_loss
conf_focal = self.focal(respond_bbox, pred_conf)
conf_loss = conf_focal * (
respond_bbox * flow.nn.sigmoid_cross_entropy_with_logits(labels=respond_bbox, logits=raw_conf)
+
respond_bgd * flow.nn.sigmoid_cross_entropy_with_logits(labels=respond_bbox, logits=raw_conf)
)
# [N, H, W, 3, 1]
prob_loss = respond_bbox * flow.nn.sigmoid_cross_entropy_with_logits(labels=label_prob, logits=raw_prob)
#??
# label_w = flow.slice(label, begin=[None, None, None, None, 2], size=[None, None, None, None, 1])
# label_h = flow.slice(label, begin=[None, None, None, None, 3], size=[None, None, None, None, 1])
# bbox_loss_scale = 2.0 - 1.0 * label_w * label_h / ((stride * feature_map.shape[1]) * (stride * feature_map.shape[2])) #???
# # [N, H, W, 3, 1]
# giou_loss = respond_bbox * bbox_loss_scale * flow.smooth_l1_loss(prediction=pred_xywh, label=label_xywh)
giou_loss = flow.math.reduce_mean(flow.math.reduce_sum(giou_loss, axis=[1, 2, 3, 4]))
conf_loss = flow.math.reduce_mean(flow.math.reduce_sum(conf_loss, axis=[1, 2, 3, 4]))
prob_loss = flow.math.reduce_mean(flow.math.reduce_sum(prob_loss, axis=[1, 2, 3, 4]))
return giou_loss, conf_loss, prob_loss
def compute_loss(self, feature_map_s, feature_map_l, label_sbbox, label_lbbox, true_sbbox, true_lbbox, anchors_s,
anchors_l):
'''
:param feature_map_s: [N, 3 * (5 + num_class), 13, 13]
:param feature_map_l: [N, 3 * (5 + num_class), 26, 26]
:param label_sbbox: [N, 13, 13, 3, 4+1+class_num]
:param label_lbbox: [N, 26, 26, 3, 4+1+class_num]
:param true_sbbox: [N, V, 4]
:param true_lbbox: [N, V, 4]
:param anchors_s: [3,2]
:param anchors_l: [3,2]
:return:
'''
# [N, H, W, 3 * (5 + num_class)]
feature_map_s = flow.transpose(feature_map_s, perm=[0, 2, 3, 1])
# [N, H, W, 3, 4+1+class_num]
pred_s, _ = self.decode(feature_map_s, anchors_s, self.strides[0], prefix= 'decode_s')
loss_sbbox = self.loss_layer(feature_map_s, pred_s, label_sbbox, true_sbbox, self.strides[0], prefix= 'loss_later_s')
# [N, H, W, 3 * (5 + num_class)]
feature_map_l = flow.transpose(feature_map_l, perm=[0, 2, 3, 1])
# [N, H, W, 3, 4+1+class_num]
pred_l, _ = self.decode(feature_map_l, anchors_l, self.strides[1], prefix= 'decode_l')
loss_lbbox = self.loss_layer(feature_map_l, pred_l, label_lbbox, true_lbbox, self.strides[1], prefix= 'loss_later_l')
giou_loss = loss_sbbox[0] + loss_lbbox[0]
conf_loss = loss_sbbox[1] + loss_lbbox[1]
prob_loss = loss_sbbox[2] + loss_lbbox[2]
return giou_loss, conf_loss, prob_loss
def train(self, images, label_sbbox, label_lbbox, true_sbbox, true_lbbox, anchors_s, anchors_l):
'''
:param images: [N, 3, H, W]
:param label_sbbox: [N, 13, 13, 3, 4+1+class_num]
:param label_lbbox: [N, 26, 26, 3, 4+1+class_num]
:param true_sbbox: [N, V, 4]
:param true_lbbox: [N, V, 4]
:param anchors_s: [anchor_per_scale, 2]
:param anchors_l: [anchor_per_scale, 2]
:return:
'''
conv_lbbox, conv_sbbox = self.network(images)
giou_loss, conf_loss, prob_loss = self.compute_loss(conv_sbbox, conv_lbbox, label_sbbox, label_lbbox,
true_sbbox, true_lbbox, anchors_s, anchors_l)
total_loss = self.loss_giou_alpha * giou_loss + self.loss_conf_alpha * conf_loss + self.loss_preb_alpha * prob_loss
return total_loss, giou_loss, conf_loss, prob_loss
# return {
# 'total_loss': total_loss,
# 'giou_loss': giou_loss,
# 'conf_loss': conf_loss,
# 'prob_loss': prob_loss
# }
def predict(self, images, anchors_s, anchors_l):
'''
:param images: [N, 3, 416, 416]
:param anchors_s: [anchor_per_scale, 2]
:param anchors_l: [anchor_per_scale, 2]
:return: [N, -1, 4+1+class_num]
pred_bbox: [N, -1, 4]
pred_conf: [N, -1, 1]
pred_pred: [N, -1, class_num]
'''
conv_lbbox, conv_sbbox = self.network(images)
conv_sbbox = flow.transpose(conv_sbbox, perm=[0, 2, 3, 1])
conv_lbbox = flow.transpose(conv_lbbox, perm=[0, 2, 3, 1])
pred_s,_ = self.decode(conv_sbbox, anchors_s, self.strides[0], prefix= 'decode_s')
pred_l,_ = self.decode(conv_lbbox, anchors_l, self.strides[1], prefix= 'decode_l')
pred_s = flow.reshape(pred_s, [pred_s.shape[0], -1, pred_s.shape[-1]])
pred_l = flow.reshape(pred_l, [pred_l.shape[0], -1, pred_l.shape[-1]])
pred = flow.concat([pred_s, pred_l], axis=-2)
# pred_bbox = flow.slice(pred, begin=[None, None, 0], size=[None, None, 4])
# pred_conf = flow.slice(pred, begin=[None, None, 4], size=[None, None, 1])
# pred_pred = flow.slice(pred, begin=[None, None, 5], size=[None, None, pred.shape[-1]-5])
# return pred_bbox, pred_conf, pred_pred
return pred
| [
"oneflow.transpose",
"oneflow.zeros_like",
"oneflow.math.abs",
"oneflow.math.reduce_max",
"oneflow.range",
"oneflow.math.minimum",
"oneflow.slice",
"oneflow.constant_like",
"oneflow.reshape",
"oneflow.concat",
"oneflow.math.maximum",
"oneflow.math.sigmoid",
"oneflow.expand_dims",
"oneflow.constant",
"oneflow.math.exp",
"oneflow.math.reduce_sum",
"oneflow.nn.sigmoid_cross_entropy_with_logits",
"oneflow.broadcast_like",
"oneflow.math.clip_by_value",
"oneflow.squeeze"
] | [((5093, 5158), 'oneflow.concat', 'flow.concat', (['[blob, blobs[0]]'], {'name': '"""yolo-detect2-concat"""', 'axis': '(1)'}), "([blob, blobs[0]], name='yolo-detect2-concat', axis=1)\n", (5104, 5158), True, 'import oneflow as flow\n'), ((6373, 6503), 'oneflow.reshape', 'flow.reshape', (['feature_map'], {'shape': '(feature_map.shape[0], feature_map.shape[1], feature_map.shape[2], self.\n anchor_per_scale, -1)'}), '(feature_map, shape=(feature_map.shape[0], feature_map.shape[1],\n feature_map.shape[2], self.anchor_per_scale, -1))\n', (6385, 6503), True, 'import oneflow as flow\n'), ((6611, 6707), 'oneflow.slice', 'flow.slice', (['feature_map'], {'begin': '[None, None, None, None, 0]', 'size': '[None, None, None, None, 2]'}), '(feature_map, begin=[None, None, None, None, 0], size=[None, None,\n None, None, 2])\n', (6621, 6707), True, 'import oneflow as flow\n'), ((6757, 6853), 'oneflow.slice', 'flow.slice', (['feature_map'], {'begin': '[None, None, None, None, 2]', 'size': '[None, None, None, None, 2]'}), '(feature_map, begin=[None, None, None, None, 2], size=[None, None,\n None, None, 2])\n', (6767, 6853), True, 'import oneflow as flow\n'), ((6905, 7001), 'oneflow.slice', 'flow.slice', (['feature_map'], {'begin': '[None, None, None, None, 4]', 'size': '[None, None, None, None, 1]'}), '(feature_map, begin=[None, None, None, None, 4], size=[None, None,\n None, None, 1])\n', (6915, 7001), True, 'import oneflow as flow\n'), ((7061, 7181), 'oneflow.slice', 'flow.slice', (['feature_map'], {'begin': '[None, None, None, None, 5]', 'size': '[None, None, None, None, feature_map.shape[-1] - 5]'}), '(feature_map, begin=[None, None, None, None, 5], size=[None, None,\n None, None, feature_map.shape[-1] - 5])\n', (7071, 7181), True, 'import oneflow as flow\n'), ((7304, 7380), 'oneflow.range', 'flow.range', (['grid_size[1]'], {'dtype': 'flow.float32', 'name': "(prefix + '_decode_range1')"}), "(grid_size[1], dtype=flow.float32, name=prefix + '_decode_range1')\n", (7314, 7380), True, 'import oneflow as flow\n'), ((7396, 7428), 'oneflow.expand_dims', 'flow.expand_dims', (['grid_x'], {'axis': '(0)'}), '(grid_x, axis=0)\n', (7412, 7428), True, 'import oneflow as flow\n'), ((7451, 7536), 'oneflow.constant', 'flow.constant', ([], {'value': '(1.0)', 'dtype': 'flow.float32', 'shape': '(grid_size[0], grid_size[1])'}), '(value=1.0, dtype=flow.float32, shape=(grid_size[0], grid_size[1])\n )\n', (7464, 7536), True, 'import oneflow as flow\n'), ((7549, 7643), 'oneflow.broadcast_like', 'flow.broadcast_like', (['grid_x', 'like_tensor'], {'broadcast_axes': '(0,)', 'name': "(prefix + 'yolo_grid_x')"}), "(grid_x, like_tensor, broadcast_axes=(0,), name=prefix +\n 'yolo_grid_x')\n", (7568, 7643), True, 'import oneflow as flow\n'), ((7657, 7742), 'oneflow.range', 'flow.range', (['grid_size[0]'], {'dtype': 'flow.float32', 'name': "(prefix + '_yolo_decode_range2')"}), "(grid_size[0], dtype=flow.float32, name=prefix +\n '_yolo_decode_range2')\n", (7667, 7742), True, 'import oneflow as flow\n'), ((7754, 7786), 'oneflow.expand_dims', 'flow.expand_dims', (['grid_y'], {'axis': '(1)'}), '(grid_y, axis=1)\n', (7770, 7786), True, 'import oneflow as flow\n'), ((7804, 7898), 'oneflow.broadcast_like', 'flow.broadcast_like', (['grid_y', 'like_tensor'], {'broadcast_axes': '(1,)', 'name': "(prefix + 'yolo_grid_y')"}), "(grid_y, like_tensor, broadcast_axes=(1,), name=prefix +\n 'yolo_grid_y')\n", (7823, 7898), True, 'import oneflow as flow\n'), ((7914, 7947), 'oneflow.expand_dims', 'flow.expand_dims', (['grid_x'], {'axis': '(-1)'}), '(grid_x, axis=-1)\n', (7930, 7947), True, 'import oneflow as flow\n'), ((7967, 8000), 'oneflow.expand_dims', 'flow.expand_dims', (['grid_y'], {'axis': '(-1)'}), '(grid_y, axis=-1)\n', (7983, 8000), True, 'import oneflow as flow\n'), ((8054, 8096), 'oneflow.concat', 'flow.concat', (['[x_offset, y_offset]'], {'axis': '(-1)'}), '([x_offset, y_offset], axis=-1)\n', (8065, 8096), True, 'import oneflow as flow\n'), ((8118, 8154), 'oneflow.expand_dims', 'flow.expand_dims', (['x_y_offset'], {'axis': '(0)'}), '(x_y_offset, axis=0)\n', (8134, 8154), True, 'import oneflow as flow\n'), ((8176, 8213), 'oneflow.expand_dims', 'flow.expand_dims', (['x_y_offset'], {'axis': '(-2)'}), '(x_y_offset, axis=-2)\n', (8192, 8213), True, 'import oneflow as flow\n'), ((8443, 8483), 'oneflow.concat', 'flow.concat', (['[pred_xy, pred_wh]'], {'axis': '(-1)'}), '([pred_xy, pred_wh], axis=-1)\n', (8454, 8483), True, 'import oneflow as flow\n'), ((8505, 8535), 'oneflow.math.sigmoid', 'flow.math.sigmoid', (['conf_logits'], {}), '(conf_logits)\n', (8522, 8535), True, 'import oneflow as flow\n'), ((8556, 8586), 'oneflow.math.sigmoid', 'flow.math.sigmoid', (['prob_logits'], {}), '(prob_logits)\n', (8573, 8586), True, 'import oneflow as flow\n'), ((8603, 8658), 'oneflow.concat', 'flow.concat', (['[pred_xywh, pred_conf, pred_prob]'], {'axis': '(-1)'}), '([pred_xywh, pred_conf, pred_prob], axis=-1)\n', (8614, 8658), True, 'import oneflow as flow\n'), ((10318, 10357), 'oneflow.math.maximum', 'flow.math.maximum', (['boxes1_lt', 'boxes2_lt'], {}), '(boxes1_lt, boxes2_lt)\n', (10335, 10357), True, 'import oneflow as flow\n'), ((10379, 10418), 'oneflow.math.minimum', 'flow.math.minimum', (['boxes1_rb', 'boxes2_rb'], {}), '(boxes1_rb, boxes2_rb)\n', (10396, 10418), True, 'import oneflow as flow\n'), ((10447, 10507), 'oneflow.math.clip_by_value', 'flow.math.clip_by_value', (['(right_down - left_up)'], {'min_value': '(0.0)'}), '(right_down - left_up, min_value=0.0)\n', (10470, 10507), True, 'import oneflow as flow\n'), ((10975, 11014), 'oneflow.math.minimum', 'flow.math.minimum', (['boxes1_lt', 'boxes2_lt'], {}), '(boxes1_lt, boxes2_lt)\n', (10992, 11014), True, 'import oneflow as flow\n'), ((11044, 11083), 'oneflow.math.maximum', 'flow.math.maximum', (['boxes1_rb', 'boxes2_rb'], {}), '(boxes1_rb, boxes2_rb)\n', (11061, 11083), True, 'import oneflow as flow\n'), ((11105, 11181), 'oneflow.math.clip_by_value', 'flow.math.clip_by_value', (['(enclose_right_down - enclose_left_up)'], {'min_value': '(0.0)'}), '(enclose_right_down - enclose_left_up, min_value=0.0)\n', (11128, 11181), True, 'import oneflow as flow\n'), ((13231, 13270), 'oneflow.math.maximum', 'flow.math.maximum', (['boxes1_lt', 'boxes2_lt'], {}), '(boxes1_lt, boxes2_lt)\n', (13248, 13270), True, 'import oneflow as flow\n'), ((13292, 13331), 'oneflow.math.minimum', 'flow.math.minimum', (['boxes1_rb', 'boxes2_rb'], {}), '(boxes1_rb, boxes2_rb)\n', (13309, 13331), True, 'import oneflow as flow\n'), ((13360, 13420), 'oneflow.math.clip_by_value', 'flow.math.clip_by_value', (['(right_down - left_up)'], {'min_value': '(0.0)'}), '(right_down - left_up, min_value=0.0)\n', (13383, 13420), True, 'import oneflow as flow\n'), ((14678, 14808), 'oneflow.reshape', 'flow.reshape', (['feature_map'], {'shape': '(feature_map.shape[0], feature_map.shape[1], feature_map.shape[2], self.\n anchor_per_scale, -1)'}), '(feature_map, shape=(feature_map.shape[0], feature_map.shape[1],\n feature_map.shape[2], self.anchor_per_scale, -1))\n', (14690, 14808), True, 'import oneflow as flow\n'), ((14870, 14966), 'oneflow.slice', 'flow.slice', (['feature_map'], {'begin': '[None, None, None, None, 4]', 'size': '[None, None, None, None, 1]'}), '(feature_map, begin=[None, None, None, None, 4], size=[None, None,\n None, None, 1])\n', (14880, 14966), True, 'import oneflow as flow\n'), ((15023, 15143), 'oneflow.slice', 'flow.slice', (['feature_map'], {'begin': '[None, None, None, None, 5]', 'size': '[None, None, None, None, feature_map.shape[-1] - 5]'}), '(feature_map, begin=[None, None, None, None, 5], size=[None, None,\n None, None, feature_map.shape[-1] - 5])\n', (15033, 15143), True, 'import oneflow as flow\n'), ((15218, 15307), 'oneflow.slice', 'flow.slice', (['pred'], {'begin': '[None, None, None, None, 0]', 'size': '[None, None, None, None, 4]'}), '(pred, begin=[None, None, None, None, 0], size=[None, None, None,\n None, 4])\n', (15228, 15307), True, 'import oneflow as flow\n'), ((15324, 15413), 'oneflow.slice', 'flow.slice', (['pred'], {'begin': '[None, None, None, None, 4]', 'size': '[None, None, None, None, 1]'}), '(pred, begin=[None, None, None, None, 4], size=[None, None, None,\n None, 1])\n', (15334, 15413), True, 'import oneflow as flow\n'), ((15528, 15618), 'oneflow.slice', 'flow.slice', (['label'], {'begin': '[None, None, None, None, 0]', 'size': '[None, None, None, None, 4]'}), '(label, begin=[None, None, None, None, 0], size=[None, None, None,\n None, 4])\n', (15538, 15618), True, 'import oneflow as flow\n'), ((15638, 15728), 'oneflow.slice', 'flow.slice', (['label'], {'begin': '[None, None, None, None, 4]', 'size': '[None, None, None, None, 1]'}), '(label, begin=[None, None, None, None, 4], size=[None, None, None,\n None, 1])\n', (15648, 15728), True, 'import oneflow as flow\n'), ((15746, 15854), 'oneflow.slice', 'flow.slice', (['label'], {'begin': '[None, None, None, None, 5]', 'size': '[None, None, None, None, label.shape[-1] - 5]'}), '(label, begin=[None, None, None, None, 5], size=[None, None, None,\n None, label.shape[-1] - 5])\n', (15756, 15854), True, 'import oneflow as flow\n'), ((16467, 16499), 'oneflow.expand_dims', 'flow.expand_dims', (['bboxes'], {'axis': '(1)'}), '(bboxes, axis=1)\n', (16483, 16499), True, 'import oneflow as flow\n'), ((16520, 16553), 'oneflow.expand_dims', 'flow.expand_dims', (['bboxes_'], {'axis': '(1)'}), '(bboxes_, axis=1)\n', (16536, 16553), True, 'import oneflow as flow\n'), ((16574, 16607), 'oneflow.expand_dims', 'flow.expand_dims', (['bboxes_'], {'axis': '(1)'}), '(bboxes_, axis=1)\n', (16590, 16607), True, 'import oneflow as flow\n'), ((16724, 16752), 'oneflow.squeeze', 'flow.squeeze', (['iou'], {'axis': '[-1]'}), '(iou, axis=[-1])\n', (16736, 16752), True, 'import oneflow as flow\n'), ((16798, 16847), 'oneflow.math.reduce_max', 'flow.math.reduce_max', (['iou'], {'axis': '(-1)', 'keepdims': '(True)'}), '(iou, axis=-1, keepdims=True)\n', (16818, 16847), True, 'import oneflow as flow\n'), ((19594, 19642), 'oneflow.transpose', 'flow.transpose', (['feature_map_s'], {'perm': '[0, 2, 3, 1]'}), '(feature_map_s, perm=[0, 2, 3, 1])\n', (19608, 19642), True, 'import oneflow as flow\n'), ((19967, 20015), 'oneflow.transpose', 'flow.transpose', (['feature_map_l'], {'perm': '[0, 2, 3, 1]'}), '(feature_map_l, perm=[0, 2, 3, 1])\n', (19981, 20015), True, 'import oneflow as flow\n'), ((22017, 22062), 'oneflow.transpose', 'flow.transpose', (['conv_sbbox'], {'perm': '[0, 2, 3, 1]'}), '(conv_sbbox, perm=[0, 2, 3, 1])\n', (22031, 22062), True, 'import oneflow as flow\n'), ((22084, 22129), 'oneflow.transpose', 'flow.transpose', (['conv_lbbox'], {'perm': '[0, 2, 3, 1]'}), '(conv_lbbox, perm=[0, 2, 3, 1])\n', (22098, 22129), True, 'import oneflow as flow\n'), ((22329, 22390), 'oneflow.reshape', 'flow.reshape', (['pred_s', '[pred_s.shape[0], -1, pred_s.shape[-1]]'], {}), '(pred_s, [pred_s.shape[0], -1, pred_s.shape[-1]])\n', (22341, 22390), True, 'import oneflow as flow\n'), ((22408, 22469), 'oneflow.reshape', 'flow.reshape', (['pred_l', '[pred_l.shape[0], -1, pred_l.shape[-1]]'], {}), '(pred_l, [pred_l.shape[0], -1, pred_l.shape[-1]])\n', (22420, 22469), True, 'import oneflow as flow\n'), ((22485, 22523), 'oneflow.concat', 'flow.concat', (['[pred_s, pred_l]'], {'axis': '(-2)'}), '([pred_s, pred_l], axis=-2)\n', (22496, 22523), True, 'import oneflow as flow\n'), ((9064, 9157), 'oneflow.slice', 'flow.slice', (['box_xywh'], {'begin': '[None, None, None, None, 0]', 'size': '[None, None, None, None, 2]'}), '(box_xywh, begin=[None, None, None, None, 0], size=[None, None,\n None, None, 2])\n', (9074, 9157), True, 'import oneflow as flow\n'), ((9175, 9268), 'oneflow.slice', 'flow.slice', (['box_xywh'], {'begin': '[None, None, None, None, 2]', 'size': '[None, None, None, None, 2]'}), '(box_xywh, begin=[None, None, None, None, 2], size=[None, None,\n None, None, 2])\n', (9185, 9268), True, 'import oneflow as flow\n'), ((9372, 9405), 'oneflow.math.minimum', 'flow.math.minimum', (['box_lt', 'box_rb'], {}), '(box_lt, box_rb)\n', (9389, 9405), True, 'import oneflow as flow\n'), ((9427, 9460), 'oneflow.math.maximum', 'flow.math.maximum', (['box_lt', 'box_rb'], {}), '(box_lt, box_rb)\n', (9444, 9460), True, 'import oneflow as flow\n'), ((9689, 9783), 'oneflow.slice', 'flow.slice', (['boxes1_wh'], {'begin': '[None, None, None, None, 0]', 'size': '[None, None, None, None, 1]'}), '(boxes1_wh, begin=[None, None, None, None, 0], size=[None, None,\n None, None, 1])\n', (9699, 9783), True, 'import oneflow as flow\n'), ((9806, 9900), 'oneflow.slice', 'flow.slice', (['boxes1_wh'], {'begin': '[None, None, None, None, 1]', 'size': '[None, None, None, None, 1]'}), '(boxes1_wh, begin=[None, None, None, None, 1], size=[None, None,\n None, None, 1])\n', (9816, 9900), True, 'import oneflow as flow\n'), ((10091, 10185), 'oneflow.slice', 'flow.slice', (['boxes2_wh'], {'begin': '[None, None, None, None, 0]', 'size': '[None, None, None, None, 1]'}), '(boxes2_wh, begin=[None, None, None, None, 0], size=[None, None,\n None, None, 1])\n', (10101, 10185), True, 'import oneflow as flow\n'), ((10208, 10302), 'oneflow.slice', 'flow.slice', (['boxes2_wh'], {'begin': '[None, None, None, None, 1]', 'size': '[None, None, None, None, 1]'}), '(boxes2_wh, begin=[None, None, None, None, 1], size=[None, None,\n None, None, 1])\n', (10218, 10302), True, 'import oneflow as flow\n'), ((10531, 10632), 'oneflow.slice', 'flow.slice', (['inter_section_wh'], {'begin': '[None, None, None, None, 0]', 'size': '[None, None, None, None, 1]'}), '(inter_section_wh, begin=[None, None, None, None, 0], size=[None,\n None, None, None, 1])\n', (10541, 10632), True, 'import oneflow as flow\n'), ((10654, 10755), 'oneflow.slice', 'flow.slice', (['inter_section_wh'], {'begin': '[None, None, None, None, 1]', 'size': '[None, None, None, None, 1]'}), '(inter_section_wh, begin=[None, None, None, None, 1], size=[None,\n None, None, None, 1])\n', (10664, 10755), True, 'import oneflow as flow\n'), ((11207, 11302), 'oneflow.slice', 'flow.slice', (['enclose_wh'], {'begin': '[None, None, None, None, 0]', 'size': '[None, None, None, None, 1]'}), '(enclose_wh, begin=[None, None, None, None, 0], size=[None, None,\n None, None, 1])\n', (11217, 11302), True, 'import oneflow as flow\n'), ((11326, 11421), 'oneflow.slice', 'flow.slice', (['enclose_wh'], {'begin': '[None, None, None, None, 1]', 'size': '[None, None, None, None, 1]'}), '(enclose_wh, begin=[None, None, None, None, 1], size=[None, None,\n None, None, 1])\n', (11336, 11421), True, 'import oneflow as flow\n'), ((11873, 11978), 'oneflow.slice', 'flow.slice', (['box_xywh'], {'begin': '[None, None, None, None, None, 0]', 'size': '[None, None, None, None, None, 2]'}), '(box_xywh, begin=[None, None, None, None, None, 0], size=[None,\n None, None, None, None, 2])\n', (11883, 11978), True, 'import oneflow as flow\n'), ((12028, 12133), 'oneflow.slice', 'flow.slice', (['box_xywh'], {'begin': '[None, None, None, None, None, 2]', 'size': '[None, None, None, None, None, 2]'}), '(box_xywh, begin=[None, None, None, None, None, 2], size=[None,\n None, None, None, None, 2])\n', (12038, 12133), True, 'import oneflow as flow\n'), ((12269, 12302), 'oneflow.math.minimum', 'flow.math.minimum', (['box_lt', 'box_rb'], {}), '(box_lt, box_rb)\n', (12286, 12302), True, 'import oneflow as flow\n'), ((12324, 12357), 'oneflow.math.maximum', 'flow.math.maximum', (['box_lt', 'box_rb'], {}), '(box_lt, box_rb)\n', (12341, 12357), True, 'import oneflow as flow\n'), ((12504, 12610), 'oneflow.slice', 'flow.slice', (['boxes1_wh'], {'begin': '[None, None, None, None, None, 0]', 'size': '[None, None, None, None, None, 1]'}), '(boxes1_wh, begin=[None, None, None, None, None, 0], size=[None,\n None, None, None, None, 1])\n', (12514, 12610), True, 'import oneflow as flow\n'), ((12666, 12772), 'oneflow.slice', 'flow.slice', (['boxes1_wh'], {'begin': '[None, None, None, None, None, 1]', 'size': '[None, None, None, None, None, 1]'}), '(boxes1_wh, begin=[None, None, None, None, None, 1], size=[None,\n None, None, None, None, 1])\n', (12676, 12772), True, 'import oneflow as flow\n'), ((12914, 13020), 'oneflow.slice', 'flow.slice', (['boxes2_wh'], {'begin': '[None, None, None, None, None, 0]', 'size': '[None, None, None, None, None, 1]'}), '(boxes2_wh, begin=[None, None, None, None, None, 0], size=[None,\n None, None, None, None, 1])\n', (12924, 13020), True, 'import oneflow as flow\n'), ((13076, 13182), 'oneflow.slice', 'flow.slice', (['boxes2_wh'], {'begin': '[None, None, None, None, None, 1]', 'size': '[None, None, None, None, None, 1]'}), '(boxes2_wh, begin=[None, None, None, None, None, 1], size=[None,\n None, None, None, None, 1])\n', (13086, 13182), True, 'import oneflow as flow\n'), ((13444, 13558), 'oneflow.slice', 'flow.slice', (['inter_section_wh'], {'begin': '[None, None, None, None, None, 0]', 'size': '[None, None, None, None, None, 1]'}), '(inter_section_wh, begin=[None, None, None, None, None, 0], size=\n [None, None, None, None, None, 1])\n', (13454, 13558), True, 'import oneflow as flow\n'), ((13611, 13725), 'oneflow.slice', 'flow.slice', (['inter_section_wh'], {'begin': '[None, None, None, None, None, 1]', 'size': '[None, None, None, None, None, 1]'}), '(inter_section_wh, begin=[None, None, None, None, None, 1], size=\n [None, None, None, None, None, 1])\n', (13621, 13725), True, 'import oneflow as flow\n'), ((13945, 13994), 'oneflow.math.abs', 'flow.math.abs', (['(self.focus_loss_alpha + target - 1)'], {}), '(self.focus_loss_alpha + target - 1)\n', (13958, 13994), True, 'import oneflow as flow\n'), ((16664, 16700), 'oneflow.expand_dims', 'flow.expand_dims', (['pred_xywh'], {'axis': '(-2)'}), '(pred_xywh, axis=-2)\n', (16680, 16700), True, 'import oneflow as flow\n'), ((16966, 17051), 'oneflow.constant_like', 'flow.constant_like', ([], {'like': 'max_iou', 'value': 'self.iou_loss_thresh', 'dtype': 'flow.float32'}), '(like=max_iou, value=self.iou_loss_thresh, dtype=flow.float32\n )\n', (16984, 17051), True, 'import oneflow as flow\n'), ((17190, 17239), 'oneflow.zeros_like', 'flow.zeros_like', (['respond_bbox'], {'dtype': 'flow.float32'}), '(respond_bbox, dtype=flow.float32)\n', (17205, 17239), True, 'import oneflow as flow\n'), ((18038, 18115), 'oneflow.nn.sigmoid_cross_entropy_with_logits', 'flow.nn.sigmoid_cross_entropy_with_logits', ([], {'labels': 'label_prob', 'logits': 'raw_prob'}), '(labels=label_prob, logits=raw_prob)\n', (18079, 18115), True, 'import oneflow as flow\n'), ((18663, 18713), 'oneflow.math.reduce_sum', 'flow.math.reduce_sum', (['giou_loss'], {'axis': '[1, 2, 3, 4]'}), '(giou_loss, axis=[1, 2, 3, 4])\n', (18683, 18713), True, 'import oneflow as flow\n'), ((18757, 18807), 'oneflow.math.reduce_sum', 'flow.math.reduce_sum', (['conf_loss'], {'axis': '[1, 2, 3, 4]'}), '(conf_loss, axis=[1, 2, 3, 4])\n', (18777, 18807), True, 'import oneflow as flow\n'), ((18851, 18901), 'oneflow.math.reduce_sum', 'flow.math.reduce_sum', (['prob_loss'], {'axis': '[1, 2, 3, 4]'}), '(prob_loss, axis=[1, 2, 3, 4])\n', (18871, 18901), True, 'import oneflow as flow\n'), ((8234, 8264), 'oneflow.math.sigmoid', 'flow.math.sigmoid', (['box_centers'], {}), '(box_centers)\n', (8251, 8264), True, 'import oneflow as flow\n'), ((8307, 8331), 'oneflow.math.exp', 'flow.math.exp', (['box_sizes'], {}), '(box_sizes)\n', (8320, 8331), True, 'import oneflow as flow\n'), ((14011, 14041), 'oneflow.math.abs', 'flow.math.abs', (['(target - actual)'], {}), '(target - actual)\n', (14024, 14041), True, 'import oneflow as flow\n'), ((17759, 17838), 'oneflow.nn.sigmoid_cross_entropy_with_logits', 'flow.nn.sigmoid_cross_entropy_with_logits', ([], {'labels': 'respond_bbox', 'logits': 'raw_conf'}), '(labels=respond_bbox, logits=raw_conf)\n', (17800, 17838), True, 'import oneflow as flow\n'), ((17887, 17966), 'oneflow.nn.sigmoid_cross_entropy_with_logits', 'flow.nn.sigmoid_cross_entropy_with_logits', ([], {'labels': 'respond_bbox', 'logits': 'raw_conf'}), '(labels=respond_bbox, logits=raw_conf)\n', (17928, 17966), 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 sys
import random
from oneflow.compatible import single_client as flow
from oneflow.compatible.single_client.python.nn.module import Module
from oneflow.compatible.single_client.python.oneflow_export import (
oneflow_export,
experimental_api,
)
from oneflow.compatible.single_client.python.framework import id_util as id_util
class _DropoutNd(Module):
__constants__ = ["p", "inplace"]
p: float
inplace: bool
def __init__(self, p: float = 0.5, inplace: bool = False) -> None:
super(_DropoutNd, self).__init__()
if p < 0 or p > 1:
raise ValueError(
"dropout probability has to be between 0 and 1, " "but got {}".format(p)
)
self.p = p
self.inplace = inplace
def extra_repr(self) -> str:
return "p={}, inplace={}".format(self.p, self.inplace)
@oneflow_export("nn.Dropout")
@experimental_api
class Dropout(_DropoutNd):
r"""During training, randomly zeroes some of the elements of the input
tensor with probability :attr:`p` using samples from a Bernoulli
distribution. Each channel will be zeroed out independently on every forward
call.
This has proven to be an effective technique for regularization and
preventing the co-adaptation of neurons as described in the paper
"Improving neural networks by preventing co-adaptation of feature
detectors".
Furthermore, the outputs are scaled by a factor of :math:`\frac{1}{1-p}` during
training. This means that during evaluation the module simply computes an
identity function.
Args:
p: probability of an element to be zeroed. Default: 0.5
inplace: If set to ``True``, will do this operation in-place. Default: ``False``
Shape:
- Input: :math:`(*)`. Input can be of any shape
- Output: :math:`(*)`. Output is of the same shape as input
For example:
.. code-block:: python
>>> import numpy as np
>>> import oneflow.compatible.single_client.experimental as flow
>>> flow.enable_eager_execution()
>>> m = flow.nn.Dropout(p=0)
>>> arr = np.array(
... [
... [-0.7797, 0.2264, 0.2458, 0.4163],
... [0.4299, 0.3626, -0.4892, 0.4141],
... [-1.4115, 1.2183, -0.5503, 0.6520],
... ]
... )
>>> x = flow.Tensor(arr)
>>> y = m(x)
>>> y #doctest: +ELLIPSIS
tensor([[-0.7797, 0.2264, 0.2458, 0.4163],
...
[-1.4115, 1.2183, -0.5503, 0.652 ]], dtype=oneflow.float32)
"""
def __init__(self, p: float = 0.5, inplace: bool = False, generator=None):
_DropoutNd.__init__(self, p, inplace)
self.p = p
if generator is None:
generator = flow.Generator()
self.generator = generator
def forward(self, x):
if self.p == 0.0 or not self.training:
return x
return flow.F.dropout(x, self.p, self.generator)
if __name__ == "__main__":
import doctest
doctest.testmod(raise_on_error=True)
| [
"oneflow.compatible.single_client.Generator",
"oneflow.compatible.single_client.F.dropout",
"oneflow.compatible.single_client.python.oneflow_export.oneflow_export"
] | [((1452, 1480), 'oneflow.compatible.single_client.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""nn.Dropout"""'], {}), "('nn.Dropout')\n", (1466, 1480), False, 'from oneflow.compatible.single_client.python.oneflow_export import oneflow_export, experimental_api\n'), ((3653, 3689), 'doctest.testmod', 'doctest.testmod', ([], {'raise_on_error': '(True)'}), '(raise_on_error=True)\n', (3668, 3689), False, 'import doctest\n'), ((3558, 3599), 'oneflow.compatible.single_client.F.dropout', 'flow.F.dropout', (['x', 'self.p', 'self.generator'], {}), '(x, self.p, self.generator)\n', (3572, 3599), True, 'from oneflow.compatible import single_client as flow\n'), ((3396, 3412), 'oneflow.compatible.single_client.Generator', 'flow.Generator', ([], {}), '()\n', (3410, 3412), True, 'from oneflow.compatible import single_client 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 unittest
import os
from collections import OrderedDict
import numpy as np
import oneflow as flow
import tensorflow as tf
import test_global_storage
from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type
import oneflow.typing as oft
gpus = tf.config.experimental.list_physical_devices("GPU")
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
def fused_cast_scale(x, scalar, name):
return (
flow.user_op_builder(name)
.Op("fused_cast_scale")
.Input("x", [x])
.Input("scalar", [scalar])
.Output("y")
.Build()
.InferAndTryRun()
.RemoteBlobList()[0]
)
def compare_with_tensorflow(
device_type, input_shape, in_dtype, out_dtype, test_fuse_cast_scale_pass
):
assert device_type in ["gpu", "cpu"]
flow.clear_default_session()
func_config = flow.FunctionConfig()
func_config.default_data_type(flow.float)
func_config.enable_fuse_cast_scale(True)
@flow.global_function(type="predict", function_config=func_config)
def FusedCastScaleJob():
with flow.scope.placement(device_type, "0:0"):
x = flow.get_variable(
"in",
shape=input_shape,
dtype=flow.float,
initializer=flow.random_uniform_initializer(),
trainable=True,
)
scale = flow.get_variable(
"scale",
shape=(1,),
dtype=flow.float,
initializer=flow.random_uniform_initializer(),
trainable=False,
)
loss = flow.cast(x, dtype=type_name_to_flow_type[in_dtype])
if test_fuse_cast_scale_pass:
loss = flow.cast(
loss, dtype=type_name_to_flow_type[out_dtype]
) * flow.cast(scale, dtype=type_name_to_flow_type[out_dtype])
else:
loss = fused_cast_scale(
loss,
flow.cast(scale, dtype=type_name_to_flow_type[out_dtype]),
name="fused_cast_scale",
)
loss = flow.cast(loss, dtype=flow.float)
flow.watch(x, test_global_storage.Setter("x"))
flow.watch(scale, test_global_storage.Setter("scale"))
flow.watch(loss, test_global_storage.Setter("loss"))
return loss
# OneFlow
of_out = FusedCastScaleJob().get()
# TensorFlow
with tf.GradientTape(persistent=True) as tape:
x = tf.Variable(test_global_storage.Get("x"))
scale = tf.Variable(test_global_storage.Get("scale"))
tf_out = tf.cast(x, dtype=type_name_to_np_type[in_dtype])
tf_out = tf.cast(tf_out, dtype=type_name_to_np_type[out_dtype]) * tf.cast(
scale, dtype=type_name_to_np_type[out_dtype]
)
tf_out = tf.cast(tf_out, dtype=tf.float32)
assert np.allclose(of_out.numpy(), tf_out.numpy(), rtol=1e-5, atol=1e-5)
@flow.unittest.skip_unless_1n1d()
class TestFusedCastScale(flow.unittest.TestCase):
def test_cast(test_case):
arg_dict = OrderedDict()
arg_dict["device_type"] = ["gpu", "cpu"]
arg_dict["input_shape"] = [(5, 4, 3)]
arg_dict["in_dtype"] = ["float16", "float32", "double"]
arg_dict["out_dtype"] = ["float16", "float32", "double"]
arg_dict["test_fuse_cast_scale_pass"] = [True, False]
for arg in GenArgList(arg_dict):
if arg[2] == arg[3]:
continue
if (arg[4] == True) and (arg[2] != "float16" or arg[3] != "float32"):
continue
if arg[0] == "cpu" and (arg[2] == "float16" or arg[3] == "float16"):
continue
compare_with_tensorflow(*arg)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.FunctionConfig",
"oneflow.random_uniform_initializer",
"oneflow.global_function",
"oneflow.user_op_builder",
"oneflow.scope.placement",
"oneflow.unittest.skip_unless_1n1d",
"oneflow.clear_default_session",
"oneflow.cast"
] | [((862, 913), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (906, 913), True, 'import tensorflow as tf\n'), ((3584, 3616), 'oneflow.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (3614, 3616), True, 'import oneflow as flow\n'), ((935, 986), 'tensorflow.config.experimental.set_memory_growth', 'tf.config.experimental.set_memory_growth', (['gpu', '(True)'], {}), '(gpu, True)\n', (975, 986), True, 'import tensorflow as tf\n'), ((1423, 1451), 'oneflow.clear_default_session', 'flow.clear_default_session', ([], {}), '()\n', (1449, 1451), True, 'import oneflow as flow\n'), ((1471, 1492), 'oneflow.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (1490, 1492), True, 'import oneflow as flow\n'), ((1590, 1655), 'oneflow.global_function', 'flow.global_function', ([], {'type': '"""predict"""', 'function_config': 'func_config'}), "(type='predict', function_config=func_config)\n", (1610, 1655), True, 'import oneflow as flow\n'), ((4403, 4418), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4416, 4418), False, 'import unittest\n'), ((3078, 3110), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {'persistent': '(True)'}), '(persistent=True)\n', (3093, 3110), True, 'import tensorflow as tf\n'), ((3253, 3301), 'tensorflow.cast', 'tf.cast', (['x'], {'dtype': 'type_name_to_np_type[in_dtype]'}), '(x, dtype=type_name_to_np_type[in_dtype])\n', (3260, 3301), True, 'import tensorflow as tf\n'), ((3469, 3502), 'tensorflow.cast', 'tf.cast', (['tf_out'], {'dtype': 'tf.float32'}), '(tf_out, dtype=tf.float32)\n', (3476, 3502), True, 'import tensorflow as tf\n'), ((3716, 3729), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3727, 3729), False, 'from collections import OrderedDict\n'), ((4035, 4055), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (4045, 4055), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((1698, 1738), 'oneflow.scope.placement', 'flow.scope.placement', (['device_type', '"""0:0"""'], {}), "(device_type, '0:0')\n", (1718, 1738), True, 'import oneflow as flow\n'), ((2230, 2282), 'oneflow.cast', 'flow.cast', (['x'], {'dtype': 'type_name_to_flow_type[in_dtype]'}), '(x, dtype=type_name_to_flow_type[in_dtype])\n', (2239, 2282), True, 'import oneflow as flow\n'), ((2749, 2782), 'oneflow.cast', 'flow.cast', (['loss'], {'dtype': 'flow.float'}), '(loss, dtype=flow.float)\n', (2758, 2782), True, 'import oneflow as flow\n'), ((3144, 3172), 'test_global_storage.Get', 'test_global_storage.Get', (['"""x"""'], {}), "('x')\n", (3167, 3172), False, 'import test_global_storage\n'), ((3202, 3234), 'test_global_storage.Get', 'test_global_storage.Get', (['"""scale"""'], {}), "('scale')\n", (3225, 3234), False, 'import test_global_storage\n'), ((3319, 3373), 'tensorflow.cast', 'tf.cast', (['tf_out'], {'dtype': 'type_name_to_np_type[out_dtype]'}), '(tf_out, dtype=type_name_to_np_type[out_dtype])\n', (3326, 3373), True, 'import tensorflow as tf\n'), ((3376, 3429), 'tensorflow.cast', 'tf.cast', (['scale'], {'dtype': 'type_name_to_np_type[out_dtype]'}), '(scale, dtype=type_name_to_np_type[out_dtype])\n', (3383, 3429), True, 'import tensorflow as tf\n'), ((2809, 2840), 'test_global_storage.Setter', 'test_global_storage.Setter', (['"""x"""'], {}), "('x')\n", (2835, 2840), False, 'import test_global_storage\n'), ((2872, 2907), 'test_global_storage.Setter', 'test_global_storage.Setter', (['"""scale"""'], {}), "('scale')\n", (2898, 2907), False, 'import test_global_storage\n'), ((2938, 2972), 'test_global_storage.Setter', 'test_global_storage.Setter', (['"""loss"""'], {}), "('loss')\n", (2964, 2972), False, 'import test_global_storage\n'), ((1894, 1927), 'oneflow.random_uniform_initializer', 'flow.random_uniform_initializer', ([], {}), '()\n', (1925, 1927), True, 'import oneflow as flow\n'), ((2129, 2162), 'oneflow.random_uniform_initializer', 'flow.random_uniform_initializer', ([], {}), '()\n', (2160, 2162), True, 'import oneflow as flow\n'), ((2348, 2404), 'oneflow.cast', 'flow.cast', (['loss'], {'dtype': 'type_name_to_flow_type[out_dtype]'}), '(loss, dtype=type_name_to_flow_type[out_dtype])\n', (2357, 2404), True, 'import oneflow as flow\n'), ((2445, 2502), 'oneflow.cast', 'flow.cast', (['scale'], {'dtype': 'type_name_to_flow_type[out_dtype]'}), '(scale, dtype=type_name_to_flow_type[out_dtype])\n', (2454, 2502), True, 'import oneflow as flow\n'), ((2608, 2665), 'oneflow.cast', 'flow.cast', (['scale'], {'dtype': 'type_name_to_flow_type[out_dtype]'}), '(scale, dtype=type_name_to_flow_type[out_dtype])\n', (2617, 2665), True, 'import oneflow as flow\n'), ((1049, 1075), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (1069, 1075), 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 os
import unittest
import numpy as np
import oneflow as flow
def _test(test_case, device_num):
m, k, n = 5, 6, 7
a_shape = (m, k)
b_shape = (k, n)
c_shape = (n,)
flow.config.gpu_device_num(device_num)
func_config = flow.FunctionConfig()
func_config.default_data_type(flow.float32)
func_config.prune_parallel_cast_ops(True)
@flow.global_function("train", function_config=func_config)
def test_fn(
a: flow.typing.Numpy.Placeholder(a_shape),
b: flow.typing.Numpy.Placeholder(b_shape),
c: flow.typing.Numpy.Placeholder(c_shape),
) -> flow.typing.Numpy:
# print(f"a.split_axis: {a.split_axis}")
# print(f"b.split_axis: {b.split_axis}")
# print(f"c.split_axis: {c.split_axis}")
var_a = flow.get_variable(
name="var_a",
shape=a_shape,
dtype=flow.float32,
initializer=flow.ones_initializer(),
distribute=flow.distribute.split(1),
)
# S0 -> S1
a = flow.parallel_cast(a, distribute=flow.distribute.split(1))
a = var_a * a
out = flow.matmul(a, b)
# P -> B
out = flow.parallel_cast(
out,
distribute=flow.distribute.broadcast(),
gradient_distribute=flow.distribute.broadcast(),
)
# S0 -> B
c = flow.parallel_cast(c, distribute=flow.distribute.broadcast())
out = flow.nn.bias_add(out, c)
lr_scheduler = flow.optimizer.PiecewiseConstantScheduler([], [0.001])
flow.optimizer.SGD(lr_scheduler, momentum=0).minimize(out)
return out
a = np.random.rand(*a_shape).astype(np.float32)
b = np.random.rand(*b_shape).astype(np.float32)
c = np.random.rand(*c_shape).astype(np.float32)
out = test_fn(a, b, c)
test_case.assertTrue(np.allclose(out, np.matmul(a, b) + c))
@flow.unittest.skip_unless_1n2d()
@unittest.skipIf(
flow.unittest.env.eager_execution_enabled(),
"Parallel cast SBP doesn't work in eager mode",
)
class TestParallelCast(flow.unittest.TestCase):
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def test_on_gpu(test_case):
_test(test_case, 2)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.matmul",
"oneflow.FunctionConfig",
"oneflow.unittest.env.eager_execution_enabled",
"oneflow.optimizer.PiecewiseConstantScheduler",
"oneflow.optimizer.SGD",
"oneflow.nn.bias_add",
"oneflow.ones_initializer",
"oneflow.global_function",
"oneflow.distribute.split",
"oneflow.distribute.broadcast",
"oneflow.unittest.skip_unless_1n2d",
"oneflow.config.gpu_device_num",
"oneflow.typing.Numpy.Placeholder"
] | [((2474, 2506), 'oneflow.unittest.skip_unless_1n2d', 'flow.unittest.skip_unless_1n2d', ([], {}), '()\n', (2504, 2506), True, 'import oneflow as flow\n'), ((782, 820), 'oneflow.config.gpu_device_num', 'flow.config.gpu_device_num', (['device_num'], {}), '(device_num)\n', (808, 820), True, 'import oneflow as flow\n'), ((839, 860), 'oneflow.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (858, 860), True, 'import oneflow as flow\n'), ((961, 1019), 'oneflow.global_function', 'flow.global_function', (['"""train"""'], {'function_config': 'func_config'}), "('train', function_config=func_config)\n", (981, 1019), True, 'import oneflow as flow\n'), ((2529, 2572), 'oneflow.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (2570, 2572), True, 'import oneflow as flow\n'), ((2849, 2864), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2862, 2864), False, 'import unittest\n'), ((1719, 1736), 'oneflow.matmul', 'flow.matmul', (['a', 'b'], {}), '(a, b)\n', (1730, 1736), True, 'import oneflow as flow\n'), ((2034, 2058), 'oneflow.nn.bias_add', 'flow.nn.bias_add', (['out', 'c'], {}), '(out, c)\n', (2050, 2058), True, 'import oneflow as flow\n'), ((2082, 2136), 'oneflow.optimizer.PiecewiseConstantScheduler', 'flow.optimizer.PiecewiseConstantScheduler', (['[]', '[0.001]'], {}), '([], [0.001])\n', (2123, 2136), True, 'import oneflow as flow\n'), ((2697, 2731), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (2706, 2731), False, 'import os\n'), ((1048, 1086), 'oneflow.typing.Numpy.Placeholder', 'flow.typing.Numpy.Placeholder', (['a_shape'], {}), '(a_shape)\n', (1077, 1086), True, 'import oneflow as flow\n'), ((1099, 1137), 'oneflow.typing.Numpy.Placeholder', 'flow.typing.Numpy.Placeholder', (['b_shape'], {}), '(b_shape)\n', (1128, 1137), True, 'import oneflow as flow\n'), ((1150, 1188), 'oneflow.typing.Numpy.Placeholder', 'flow.typing.Numpy.Placeholder', (['c_shape'], {}), '(c_shape)\n', (1179, 1188), True, 'import oneflow as flow\n'), ((2232, 2256), 'numpy.random.rand', 'np.random.rand', (['*a_shape'], {}), '(*a_shape)\n', (2246, 2256), True, 'import numpy as np\n'), ((2284, 2308), 'numpy.random.rand', 'np.random.rand', (['*b_shape'], {}), '(*b_shape)\n', (2298, 2308), True, 'import numpy as np\n'), ((2336, 2360), 'numpy.random.rand', 'np.random.rand', (['*c_shape'], {}), '(*c_shape)\n', (2350, 2360), True, 'import numpy as np\n'), ((1509, 1532), 'oneflow.ones_initializer', 'flow.ones_initializer', ([], {}), '()\n', (1530, 1532), True, 'import oneflow as flow\n'), ((1557, 1581), 'oneflow.distribute.split', 'flow.distribute.split', (['(1)'], {}), '(1)\n', (1578, 1581), True, 'import oneflow as flow\n'), ((1657, 1681), 'oneflow.distribute.split', 'flow.distribute.split', (['(1)'], {}), '(1)\n', (1678, 1681), True, 'import oneflow as flow\n'), ((1828, 1855), 'oneflow.distribute.broadcast', 'flow.distribute.broadcast', ([], {}), '()\n', (1853, 1855), True, 'import oneflow as flow\n'), ((1889, 1916), 'oneflow.distribute.broadcast', 'flow.distribute.broadcast', ([], {}), '()\n', (1914, 1916), True, 'import oneflow as flow\n'), ((1991, 2018), 'oneflow.distribute.broadcast', 'flow.distribute.broadcast', ([], {}), '()\n', (2016, 2018), True, 'import oneflow as flow\n'), ((2145, 2189), 'oneflow.optimizer.SGD', 'flow.optimizer.SGD', (['lr_scheduler'], {'momentum': '(0)'}), '(lr_scheduler, momentum=0)\n', (2163, 2189), True, 'import oneflow as flow\n'), ((2449, 2464), 'numpy.matmul', 'np.matmul', (['a', 'b'], {}), '(a, b)\n', (2458, 2464), True, 'import numpy as np\n')] |
import oneflow as flow
import oneflow.nn as nn
import oneflow.distribute as distribute_util
def _batch_norm(inputs, name, trainable=True, training=True):
params_shape = [inputs.shape[1]]
# Float32 required to avoid precision-loss when using fp16 input/output
params_dtype = flow.float32 if inputs.dtype == flow.float16 else inputs.dtype
if not flow.current_global_function_desc().IsTrainable() or not trainable:
training = False
with flow.scope.namespace(name):
beta = flow.get_variable(
name="beta",
shape=params_shape,
dtype=params_dtype,
initializer=flow.zeros_initializer(),
trainable=trainable,
distribute=distribute_util.broadcast(),
)
gamma = flow.get_variable(
name="gamma",
shape=params_shape,
dtype=params_dtype,
initializer=flow.ones_initializer(),
trainable=trainable,
distribute=distribute_util.broadcast(),
)
moving_mean = flow.get_variable(
name="moving_mean",
shape=params_shape,
dtype=params_dtype,
initializer=flow.zeros_initializer(),
trainable=False,
distribute=distribute_util.broadcast(),
)
moving_variance = flow.get_variable(
name="moving_variance",
shape=params_shape,
dtype=params_dtype,
initializer=flow.ones_initializer(),
trainable=False,
distribute=distribute_util.broadcast(),
)
builder = (
flow.user_op_builder(name)
.Op("normalization")
.Input("x", [inputs])
.Input("moving_mean", [moving_mean])
.Input("moving_variance", [moving_variance])
.Input("gamma", [gamma])
.Input("beta", [beta])
.Output("y")
.Attr("axis", 1)
.Attr("epsilon", 1.001e-5)
.Attr("training", training)
.Attr("momentum", 0.997)
)
if trainable and training:
builder = builder.Output("mean").Output("inv_variance")
return builder.Build().InferAndTryRun().RemoteBlobList()[0]
def batch_norm(input, name, axis=1, reuse=False, trainable=True):
# use separated BN from real and fake batch
name = name+'_reuse' if reuse else name
return _batch_norm(input, name, trainable=trainable)
def max_pool2d(input, size, strides, name, padding="VALID", data_format="NCHW", reuse=False):
name = name+'_reuse' if reuse else name
return flow.nn.max_pool2d(input, ksize=size, strides=strides, padding=padding, data_format=data_format, name=name) | [
"oneflow.zeros_initializer",
"oneflow.nn.max_pool2d",
"oneflow.ones_initializer",
"oneflow.user_op_builder",
"oneflow.distribute.broadcast",
"oneflow.scope.namespace",
"oneflow.current_global_function_desc"
] | [((2616, 2727), 'oneflow.nn.max_pool2d', 'flow.nn.max_pool2d', (['input'], {'ksize': 'size', 'strides': 'strides', 'padding': 'padding', 'data_format': 'data_format', 'name': 'name'}), '(input, ksize=size, strides=strides, padding=padding,\n data_format=data_format, name=name)\n', (2634, 2727), True, 'import oneflow as flow\n'), ((475, 501), 'oneflow.scope.namespace', 'flow.scope.namespace', (['name'], {}), '(name)\n', (495, 501), True, 'import oneflow as flow\n'), ((655, 679), 'oneflow.zeros_initializer', 'flow.zeros_initializer', ([], {}), '()\n', (677, 679), True, 'import oneflow as flow\n'), ((739, 766), 'oneflow.distribute.broadcast', 'distribute_util.broadcast', ([], {}), '()\n', (764, 766), True, 'import oneflow.distribute as distribute_util\n'), ((933, 956), 'oneflow.ones_initializer', 'flow.ones_initializer', ([], {}), '()\n', (954, 956), True, 'import oneflow as flow\n'), ((1016, 1043), 'oneflow.distribute.broadcast', 'distribute_util.broadcast', ([], {}), '()\n', (1041, 1043), True, 'import oneflow.distribute as distribute_util\n'), ((1222, 1246), 'oneflow.zeros_initializer', 'flow.zeros_initializer', ([], {}), '()\n', (1244, 1246), True, 'import oneflow as flow\n'), ((1302, 1329), 'oneflow.distribute.broadcast', 'distribute_util.broadcast', ([], {}), '()\n', (1327, 1329), True, 'import oneflow.distribute as distribute_util\n'), ((1516, 1539), 'oneflow.ones_initializer', 'flow.ones_initializer', ([], {}), '()\n', (1537, 1539), True, 'import oneflow as flow\n'), ((1595, 1622), 'oneflow.distribute.broadcast', 'distribute_util.broadcast', ([], {}), '()\n', (1620, 1622), True, 'import oneflow.distribute as distribute_util\n'), ((371, 406), 'oneflow.current_global_function_desc', 'flow.current_global_function_desc', ([], {}), '()\n', (404, 406), True, 'import oneflow as flow\n'), ((1661, 1687), 'oneflow.user_op_builder', 'flow.user_op_builder', (['name'], {}), '(name)\n', (1681, 1687), 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 unittest
import oneflow as flow
import oneflow.unittest
import oneflow.nn.functional as F
import torch
@flow.unittest.skip_unless_1n1d()
class TestRepeatInterleave(flow.unittest.TestCase):
def test_repeat_interleave_index_error(test_case):
with test_case.assertRaises(Exception) as context:
x = flow.tensor([[1, 2], [3, 4]])
y = flow.repeat_interleave(x, 3, dim=4)
test_case.assertTrue(
"Dimension out of range (expected to be in range of [-2, 1], but got 4)"
in str(context.exception)
)
def test_repeat_interleave_tensor_shape_error(test_case):
with test_case.assertRaises(Exception) as context:
x = flow.tensor([[1, 2], [3, 4]])
r = flow.tensor([[1, 2], [3, 4]])
y = flow.repeat_interleave(x, r, dim=1)
test_case.assertTrue(
"repeat_interleave only accept 1D vector as repeat"
in str(context.exception)
)
def test_repeat_interleave_dtype_error(test_case):
with test_case.assertRaises(Exception) as context:
x = flow.tensor([[1, 2], [3, 4]])
r = flow.tensor([1.0, 2.0])
y = flow.repeat_interleave(x, r, dim=1)
test_case.assertTrue("repeats has to be Long tensor" in str(context.exception))
def test_repeat_interleave_negative_tensor_error(test_case):
with test_case.assertRaises(Exception) as context:
x = flow.tensor([[1, 2], [3, 4]])
r = flow.tensor([1, -2])
y = flow.repeat_interleave(x, r, dim=1)
test_case.assertTrue("repeats can not be negative" in str(context.exception))
def test_repeat_interleave_negative_tensor_error(test_case):
with test_case.assertRaises(Exception) as context:
x = flow.tensor([[1, 2], [3, 4]])
r = flow.tensor([1, 2])
y = flow.repeat_interleave(x, r, dim=2)
test_case.assertTrue(
"Dimension out of range (expected to be in range of [-2, 1], but got 2)"
in str(context.exception)
)
def test_repeat_interleave_dim_not_match_error(test_case):
with test_case.assertRaises(Exception) as context:
x = flow.tensor([[1, 2], [3, 4]])
r = flow.tensor([1])
y = flow.repeat_interleave(x, r, dim=1)
test_case.assertTrue(
"repeats must have the same size as input along dim"
in str(context.exception)
)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.unittest.skip_unless_1n1d",
"oneflow.tensor",
"oneflow.repeat_interleave"
] | [((703, 735), 'oneflow.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (733, 735), True, 'import oneflow as flow\n'), ((3110, 3125), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3123, 3125), False, 'import unittest\n'), ((918, 947), 'oneflow.tensor', 'flow.tensor', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (929, 947), True, 'import oneflow as flow\n'), ((964, 999), 'oneflow.repeat_interleave', 'flow.repeat_interleave', (['x', '(3)'], {'dim': '(4)'}), '(x, 3, dim=4)\n', (986, 999), True, 'import oneflow as flow\n'), ((1301, 1330), 'oneflow.tensor', 'flow.tensor', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (1312, 1330), True, 'import oneflow as flow\n'), ((1347, 1376), 'oneflow.tensor', 'flow.tensor', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (1358, 1376), True, 'import oneflow as flow\n'), ((1393, 1428), 'oneflow.repeat_interleave', 'flow.repeat_interleave', (['x', 'r'], {'dim': '(1)'}), '(x, r, dim=1)\n', (1415, 1428), True, 'import oneflow as flow\n'), ((1702, 1731), 'oneflow.tensor', 'flow.tensor', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (1713, 1731), True, 'import oneflow as flow\n'), ((1748, 1771), 'oneflow.tensor', 'flow.tensor', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (1759, 1771), True, 'import oneflow as flow\n'), ((1788, 1823), 'oneflow.repeat_interleave', 'flow.repeat_interleave', (['x', 'r'], {'dim': '(1)'}), '(x, r, dim=1)\n', (1810, 1823), True, 'import oneflow as flow\n'), ((2053, 2082), 'oneflow.tensor', 'flow.tensor', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (2064, 2082), True, 'import oneflow as flow\n'), ((2099, 2119), 'oneflow.tensor', 'flow.tensor', (['[1, -2]'], {}), '([1, -2])\n', (2110, 2119), True, 'import oneflow as flow\n'), ((2136, 2171), 'oneflow.repeat_interleave', 'flow.repeat_interleave', (['x', 'r'], {'dim': '(1)'}), '(x, r, dim=1)\n', (2158, 2171), True, 'import oneflow as flow\n'), ((2399, 2428), 'oneflow.tensor', 'flow.tensor', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (2410, 2428), True, 'import oneflow as flow\n'), ((2445, 2464), 'oneflow.tensor', 'flow.tensor', (['[1, 2]'], {}), '([1, 2])\n', (2456, 2464), True, 'import oneflow as flow\n'), ((2481, 2516), 'oneflow.repeat_interleave', 'flow.repeat_interleave', (['x', 'r'], {'dim': '(2)'}), '(x, r, dim=2)\n', (2503, 2516), True, 'import oneflow as flow\n'), ((2819, 2848), 'oneflow.tensor', 'flow.tensor', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (2830, 2848), True, 'import oneflow as flow\n'), ((2865, 2881), 'oneflow.tensor', 'flow.tensor', (['[1]'], {}), '([1])\n', (2876, 2881), True, 'import oneflow as flow\n'), ((2898, 2933), 'oneflow.repeat_interleave', 'flow.repeat_interleave', (['x', 'r'], {'dim': '(1)'}), '(x, r, dim=1)\n', (2920, 2933), 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 global 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
Note:
The Keyword Argument device is mutually exclusive with placement and sbp.
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.from_numpy,
r"""
Creates a ``Tensor`` from a ``numpy.ndarray``.
The returned tensor and ndarray share the same memory. Modifications to the tensor
will be reflected in the ndarray and vice versa.
It currently accepts ndarray with dtypes of numpy.float64, numpy.float32, numpy.float16,
numpy.int64, numpy.int32, numpy.int8, numpy.uint8.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> np_arr = np.arange(6).reshape(2, 3)
>>> t = flow.from_numpy(np_arr)
>>> t
tensor([[0, 1, 2],
[3, 4, 5]], dtype=oneflow.int64)
>>> np_arr[0, 0] = -1
>>> t
tensor([[-1, 1, 2],
[ 3, 4, 5]], dtype=oneflow.int64)
""",
)
add_docstr(
oneflow.Tensor.device,
r"""
The documentation is referenced from:
https://pytorch.org/docs/stable/generated/torch.Tensor.device.html#torch.Tensor.device
Is the :class:`oneflow.device` where this Tensor is, which is invalid for global tensor.
""",
)
add_docstr(
oneflow.Tensor.placement,
r"""
Is the :class:`oneflow.placement` where this Tensor is, which is invalid for local tensor.
""",
)
add_docstr(
oneflow.Tensor.sbp,
r"""
Is the ``oneflow.sbp`` representing that how the data of the global tensor is distributed, which is invalid for local tensor.
""",
)
add_docstr(
oneflow.Tensor.is_global,
r"""
Return whether this Tensor is a global tensor.
""",
)
add_docstr(
oneflow.Tensor.is_lazy,
r"""
Return whether this Tensor is a lazy tensor.
""",
)
add_docstr(
oneflow.Tensor.atan2,
r"""
See :func:`oneflow.atan2`
""",
)
add_docstr(
oneflow.Tensor.expand,
"""
Tensor.expand() -> Tensor
See :func:`oneflow.expand`
""",
)
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.flatten,
"""
See :func:`oneflow.flatten`
""",
)
add_docstr(
oneflow.Tensor.floor,
"""
See :func:`oneflow.floor`
""",
)
add_docstr(
oneflow.Tensor.flip,
"""
See :func:`oneflow.flip`
""",
)
add_docstr(
oneflow.Tensor.in_top_k,
"""
Tensor.in_top_k(targets, predictions, k) -> Tensor
See :func:`oneflow.in_top_k`
""",
)
add_docstr(
oneflow.Tensor.index_select,
"""
Tensor.index_select(dim, index) -> Tensor
See :func:`oneflow.index_select`
""",
)
add_docstr(
oneflow.Tensor.numel,
"""
See :func:`oneflow.numel`
""",
)
add_docstr(
oneflow.Tensor.new_ones,
"""
Tensor.new_ones() -> Tensor
See :func:`oneflow.new_ones`
""",
)
add_docstr(
oneflow.Tensor.to_global,
"""
Tensor.to_global(placement=None, sbp=None, grad_sbp=None) -> Tensor
Creates a global tensor if this tensor is a local tensor, otherwise performs Tensor placement and/or sbp conversion.
Note:
This tensor can be local tensor or global tensor.
- For local tensor
Both placement and sbp are required.
The returned global tensor takes this tensor as its local component in the current rank.
There is no data communication usually, but when sbp is ``oneflow.sbp.broadcast``, the data on rank 0 will be broadcast to other ranks.
- For global tensor
At least one of placement and sbp is required.
If placement and sbp are all the same as this tensor's own placement and sbp, then returns this tensor own.
Args:
placement (flow.placement, optional): the desired placement of returned global tensor. Default: None
sbp (flow.sbp.sbp or tuple of flow.sbp.sbp, optional): the desired sbp of returned global tensor. Default: None
grad_sbp (flow.sbp.sbp or tuple of flow.sbp.sbp, optional): manually specify the sbp of this tensor's grad tensor in the backward pass. If None, the grad tensor sbp will be infered automatically. It is only used if this tensor is a global tensor. Default: None
For local tensor:
.. code-block:: python
>>> # Run on 2 ranks respectively
>>> import oneflow as flow
>>> input = flow.tensor([0., 1.], dtype=flow.float32) # doctest: +SKIP
>>> output = input.to_global(placement=flow.placement("cpu", ranks=[0, 1]), sbp=[flow.sbp.split(0)]) # doctest: +SKIP
>>> print(output.size()) # doctest: +SKIP
>>> print(output) # doctest: +SKIP
.. code-block:: python
>>> # results on rank 0
oneflow.Size([4])
tensor([0., 1., 0., 1.], placement=oneflow.placement(type="cpu", ranks=[0, 1]), sbp=(oneflow.sbp.split(axis=0),), dtype=oneflow.float32)
.. code-block:: python
>>> # results on rank 1
oneflow.Size([4])
tensor([0., 1., 0., 1.], placement=oneflow.placement(type="cpu", ranks=[0, 1]), sbp=(oneflow.sbp.split(axis=0),), dtype=oneflow.float32)
For global tensor:
.. code-block:: python
>>> # Run on 2 ranks respectively
>>> import oneflow as flow
>>> input = flow.tensor([0., 1.], dtype=flow.float32, placement=flow.placement("cpu", ranks=[0, 1]), sbp=[flow.sbp.broadcast]) # doctest: +SKIP
>>> output = input.to_global(placement=flow.placement("cpu", ranks=[0, 1]), sbp=[flow.sbp.split(0)]) # doctest: +SKIP
>>> print(output.size()) # doctest: +SKIP
>>> print(output) # doctest: +SKIP
.. code-block:: python
>>> # results on rank 0
oneflow.Size([2])
tensor([0., 1.], placement=oneflow.placement(type="cpu", ranks=[0, 1]), sbp=(oneflow.sbp.split(axis=0),), dtype=oneflow.float32)
.. code-block:: python
>>> # results on rank 1
oneflow.Size([2])
tensor([0., 1.], placement=oneflow.placement(type="cpu", ranks=[0, 1]), sbp=(oneflow.sbp.split(axis=0),), dtype=oneflow.float32)
""",
)
add_docstr(
oneflow.Tensor.to_consistent,
"""
This interface is no longer available, please use :func:`oneflow.Tensor.to_global` instead.
""",
)
add_docstr(
oneflow.Tensor.to_local,
"""
Tensor.to_local() -> Tensor
Returns the local component of this global tensor in the current rank.
Note:
This tensor should be a global tensor, and it returns a empty tensor if there is no local component in the current rank.
No copy occurred in this operation.
For example:
.. code-block:: python
>>> # Run on 2 ranks respectively
>>> import oneflow as flow
>>> x = flow.tensor([0., 1.], dtype=flow.float32, placement=flow.placement("cpu", ranks=[0, 1]), sbp=[flow.sbp.split(0)]) # doctest: +SKIP
>>> y = x.to_local() # doctest: +SKIP
>>> print(y.size()) # doctest: +SKIP
>>> print(y) # doctest: +SKIP
.. code-block:: python
>>> # results on rank 0
oneflow.Size([1])
tensor([0.], dtype=oneflow.float32)
.. code-block:: python
>>> # results on rank 1
oneflow.Size([1])
tensor([1.], dtype=oneflow.float32)
""",
)
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.sqrt,
"""
See :func:`oneflow.sqrt`
""",
)
add_docstr(
oneflow.Tensor.square,
"""
See :func:`oneflow.square`
""",
)
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.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], dtype=oneflow.int64)
>>> x.unfold(0, 2, 1)
tensor([[1, 2],
[2, 3],
[3, 4],
[4, 5],
[5, 6],
[6, 7]], dtype=oneflow.int64)
>>> x.unfold(0, 2, 2)
tensor([[1, 2],
[3, 4],
[5, 6]], dtype=oneflow.int64)
""",
)
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.abs,
"""
See :func:`oneflow.abs`
""",
)
add_docstr(
oneflow.Tensor.acos,
"""
See :func:`oneflow.acos`
""",
)
add_docstr(
oneflow.Tensor.arccos,
"""
See :func:`oneflow.arccos`
""",
)
add_docstr(
oneflow.Tensor.acosh,
"""
See :func:`oneflow.acosh`
""",
)
add_docstr(
oneflow.Tensor.arccosh,
"""
See :func:`oneflow.arccosh`
""",
)
add_docstr(
oneflow.Tensor.arctanh,
"""
See :func:`oneflow.arctanh`
""",
)
add_docstr(
oneflow.Tensor.argmax,
"""
See :func:`oneflow.argmax`
""",
)
add_docstr(
oneflow.Tensor.argmin,
"""
See :func:`oneflow.argmin`
""",
)
add_docstr(
oneflow.Tensor.argsort,
"""This operator sorts the input Tensor at specified dim and return the indices of the sorted Tensor.
Args:
input (oneflow.Tensor): The input Tensor.
dim (int, optional): dimension to be sorted. Defaults to the last dim (-1).
descending (bool, optional): controls the sorting order (ascending or descending).
Returns:
oneflow.Tensor: The indices of the sorted Tensor.
For example:
.. code-block:: python
>>> import numpy as np
>>> import oneflow as flow
>>> x = np.array([[10, 2, 9, 3, 7],
... [1, 9, 4, 3, 2]]).astype("float32")
>>> input = flow.Tensor(x)
>>> output = flow.argsort(input)
>>> output
tensor([[1, 3, 4, 2, 0],
[0, 4, 3, 2, 1]], dtype=oneflow.int32)
>>> output = flow.argsort(input, descending=True)
>>> output
tensor([[0, 2, 4, 3, 1],
[1, 2, 3, 4, 0]], dtype=oneflow.int32)
>>> output = flow.argsort(input, dim=0)
>>> output
tensor([[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0]], dtype=oneflow.int32)
""",
)
add_docstr(
oneflow.Tensor.argwhere,
"""
See :func:`oneflow.argwhere`
""",
)
add_docstr(
oneflow.Tensor.atanh,
"""
See :func:`oneflow.atanh`
""",
)
add_docstr(
oneflow.Tensor.backward,
"""
The interface is consistent with PyTorch.
The documentation is referenced from: https://pytorch.org/docs/stable/generated/torch.Tensor.backward.html#torch.Tensor.backward.
Computes the gradient of current tensor w.r.t. graph leaves.
The graph is differentiated using the chain rule. If the tensor is non-scalar (i.e. its data has more than one element) and requires gradient, the function additionally requires specifying gradient. It should be a tensor of matching type and location, that contains the gradient of the differentiated function w.r.t. self.
This function accumulates gradients in the leaves - you might need to zero .grad attributes or set them to None before calling it. See Default gradient layouts for details on the memory layout of accumulated gradients.
Note:
If you run any forward ops, create gradient, and/or call backward in a user-specified CUDA stream context, see Stream semantics of backward passes.
Note:
When inputs are provided and a given input is not a leaf, the current implementation will call its grad_fn (though it is not strictly needed to get this gradients). It is an implementation detail on which the user should not rely. See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.
Args:
gradient (Tensor or None): Gradient w.r.t. the tensor. If it is a tensor, it will be automatically converted to a Tensor that does not require grad unless create_graph is True. None values can be specified for scalar Tensors or ones that don’t require grad. If a None value would be acceptable then this argument is optional.
retain_graph (bool, optional): If False, the graph used to compute the grads will be freed. Note that in nearly all cases setting this option to True is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph.
create_graph (bool, optional): If True, graph of the derivative will be constructed, allowing to compute higher order derivative products. Defaults to False.
""",
)
add_docstr(
oneflow.Tensor.grad,
r"""
Return the gradient calculated by autograd functions. This property is None by default.
""",
)
add_docstr(
oneflow.Tensor.grad_fn,
r"""
Return the function that created this tensor if it's ``requires_grad`` is True.
""",
)
add_docstr(
oneflow.Tensor.is_leaf,
r"""
Compatible with PyTorch.
All Tensors that have ``requires_grad`` which is ``False`` will be leaf Tensors by convention.
For Tensor that have ``requires_grad`` which is ``True``, they will be leaf Tensors if they
were created by source operations.
Only leaf Tensors will have their ``grad`` populated during a call to ``backward()``. To get
``grad`` populated for non-leaf Tensors, you can use ``retain_grad()``.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> a = flow.rand(10, requires_grad=False)
>>> a.is_leaf
True
>>> a = flow.rand(10, requires_grad=True)
>>> a.is_leaf
True
>>> b = a.cuda()
>>> b.is_leaf
False
>>> c = a + 2
>>> c.is_leaf
False
""",
)
add_docstr(
oneflow.Tensor.requires_grad,
r"""
Compatible with PyTorch.
Is ``True`` if gradient need to be computed for this Tensor, ``False`` otherwise.
""",
)
add_docstr(
oneflow.Tensor.requires_grad_,
r"""oneflow.Tensor.requires_grad_(requires_grad=True) -> Tensor
Compatible with PyTorch.
Args:
requires_grad (bool): Change the requires_grad flag for this Tensor. Default is ``True``.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> a = flow.rand(10, requires_grad=False)
>>> a.requires_grad
False
>>> a = a.requires_grad_(requires_grad=True)
>>> a.requires_grad
True
""",
)
add_docstr(
oneflow.Tensor.register_hook,
r"""oneflow.Tensor.register_hook(hook)
Registers a backward hook.
The hook will be called every time a gradient with respect to the Tensor is computed.
The hook should have the following signature:
.. code-block::
hook(grad) -> Tensor or None
The hook should not modify its argument, but it can optionally return a new gradient which
will be used in place of ``grad``.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> x = flow.ones(5, requires_grad=True)
>>> def hook(grad):
... return grad * 2
>>> x.register_hook(hook)
>>> y = x * 2
>>> y.sum().backward()
>>> x.grad
tensor([4., 4., 4., 4., 4.], dtype=oneflow.float32)
""",
)
add_docstr(
oneflow.Tensor.retain_grad,
r"""
Compatible with PyTorch.
Enables this Tensor to have their ``grad`` populated during ``backward()``. This is a no-op
for leaf tensors.
""",
)
add_docstr(
oneflow.Tensor.bmm,
"""
See :func:`oneflow.bmm`
""",
)
add_docstr(
oneflow.Tensor.chunk,
"""
See :func:`oneflow.chunk`
""",
)
add_docstr(
oneflow.Tensor.split,
"""
See :func:`oneflow.split`
""",
)
add_docstr(
oneflow.Tensor.swapaxes,
"""
See :func:`oneflow.swapaxes`
""",
)
add_docstr(
oneflow.Tensor.cast,
"""
See :func:`oneflow.cast`
""",
)
add_docstr(
oneflow.Tensor.diag,
"""
See :func:`oneflow.diag`
""",
)
add_docstr(
oneflow.Tensor.dim,
"""
Tensor.dim() → int
Returns the number of dimensions of self tensor.
""",
)
add_docstr(
oneflow.Tensor.element_size,
"""
Tensor.element_size() → int
Returns the size in bytes of an individual element.
""",
)
add_docstr(
oneflow.Tensor.exp,
"""
See :func:`oneflow.exp`
""",
)
add_docstr(
oneflow.Tensor.erf,
"""
Tensor.erf() -> Tensor
See :func:`oneflow.erf`
""",
)
add_docstr(
oneflow.Tensor.erfc,
"""
Tensor.erfc() -> Tensor
See :func:`oneflow.erfc`
""",
)
add_docstr(
oneflow.Tensor.erfinv,
"""
See :func:`oneflow.erfinv`
""",
)
add_docstr(
oneflow.Tensor.erfinv_,
"""
Inplace version of :func:`oneflow.erfinv`
""",
)
add_docstr(
oneflow.Tensor.eq,
"""
See :func:`oneflow.eq`
""",
)
add_docstr(
oneflow.Tensor.lt,
"""
See :func:`oneflow.lt`
""",
)
add_docstr(
oneflow.Tensor.le,
"""
See :func:`oneflow.le`
""",
)
add_docstr(
oneflow.Tensor.ne,
"""
See :func:`oneflow.ne`
""",
)
add_docstr(
oneflow.Tensor.fill_,
"""
Tensor.fill_(value) → Tensor
Fills self tensor with the specified value.
""",
)
add_docstr(
oneflow.Tensor.ge,
"""
See :func:`oneflow.ge`
""",
)
add_docstr(
oneflow.Tensor.gelu,
"""
See :func:`oneflow.gelu`
""",
)
add_docstr(
oneflow.Tensor.get_device,
"""
Tensor.get_device() -> Device ordinal (Integer)
For CUDA tensors, this function returns the device ordinal of the GPU on which the tensor resides. For CPU tensors, an error is thrown.
""",
)
add_docstr(
oneflow.Tensor.gt,
"""
See :func:`oneflow.gt`
""",
)
add_docstr(
oneflow.Tensor.log1p,
"""
See :func:`oneflow.log1p`
""",
)
add_docstr(
oneflow.Tensor.mish,
"""
See :func:`oneflow.mish`
""",
)
add_docstr(
oneflow.Tensor.mul,
"""Tensor.mul(value) -> Tensor
See :func:`oneflow.mul`
""",
)
add_docstr(
oneflow.Tensor.mul_,
"""Tensor.mul_(value) -> Tensor
In-place version of :func:`oneflow.Tensor.mul`.
""",
)
add_docstr(
oneflow.Tensor.div_,
"""Tensor.div_(value) -> Tensor
In-place version of :func:`oneflow.Tensor.div`.
""",
)
add_docstr(
oneflow.Tensor.sub_,
"""Tensor.sub_(value) -> Tensor
In-place version of :func:`oneflow.Tensor.sub`.
""",
)
add_docstr(
oneflow.Tensor.negative,
"""
See :func:`oneflow.negative`
""",
)
add_docstr(
oneflow.Tensor.nelement,
"""
Tensor.nelement() → int
Alias for numel()
""",
)
add_docstr(
oneflow.Tensor.floor_,
r"""
In-place version of :func:`oneflow.floor`
""",
)
add_docstr(
oneflow.Tensor.normal_,
"""
normal_(mean=0, std=1, *, generator=None) -> Tensor
Fills :attr:`self` tensor with elements samples from the normal distribution parameterized by :attr:`mean` and :attr:`std`.
""",
)
add_docstr(
oneflow.Tensor.numpy,
"""
Tensor.numpy() → numpy.ndarray
Returns self tensor as a NumPy ndarray. This tensor and the returned ndarray share the same underlying storage. Changes to
self tensor will be reflected in the ndarray and vice versa.
""",
)
add_docstr(
oneflow.Tensor.pow,
"""
See :func:`oneflow.pow`
""",
)
add_docstr(
oneflow.Tensor.relu,
"""
See :func:`oneflow.relu`
""",
)
add_docstr(
oneflow.Tensor.roll,
"""
See :func:`oneflow.roll`
""",
)
add_docstr(
oneflow.Tensor.round,
"""
See :func:`oneflow.round`
""",
)
add_docstr(
oneflow.Tensor.reciprocal,
"""
See :func:`oneflow.reciprocal`
""",
)
add_docstr(
oneflow.Tensor.add,
"""
See :func:`oneflow.add`
""",
)
add_docstr(
oneflow.Tensor.addmm,
"""
See :func:`oneflow.addmm`
""",
)
add_docstr(
oneflow.Tensor.add_,
"""
In-place version of :func:`oneflow.Tensor.add`.
""",
)
add_docstr(
oneflow.Tensor.asin,
"""
See :func:`oneflow.asin`
""",
)
add_docstr(
oneflow.Tensor.arcsin,
"""
See :func:`oneflow.arcsin`
""",
)
add_docstr(
oneflow.Tensor.arcsinh,
"""
See :func:`oneflow.arcsinh`
""",
)
add_docstr(
oneflow.Tensor.sin,
"""
sin() -> Tensor
See :func:`oneflow.sin`
""",
)
add_docstr(
oneflow.Tensor.cos,
"""
See :func:`oneflow.cos`
""",
)
add_docstr(
oneflow.Tensor.diagonal,
"""
See :func:`oneflow.diagonal`
""",
)
add_docstr(
oneflow.Tensor.log,
"""
See :func:`oneflow.log`
""",
)
add_docstr(
oneflow.Tensor.ndim,
"""
See :func:`oneflow.Tensor.dim`
""",
)
add_docstr(
oneflow.Tensor.rsqrt,
"""
See :func:`oneflow.rsqrt`
""",
)
add_docstr(
oneflow.Tensor.cosh,
"""
See :func:`oneflow.cosh`
""",
)
add_docstr(
oneflow.Tensor.atan,
"""
See :func:`oneflow.atan`
""",
)
add_docstr(
oneflow.Tensor.arctan,
"""
See :func:`oneflow.arctan`
""",
)
add_docstr(
oneflow.Tensor.selu,
"""
See :func:`oneflow.selu`
""",
)
add_docstr(
oneflow.Tensor.sigmoid,
"""
See :func:`oneflow.sigmoid`
""",
)
add_docstr(
oneflow.Tensor.sign,
"""
See :func:`oneflow.sign`
""",
)
add_docstr(
oneflow.Tensor.silu,
"""
See :func:`oneflow.silu`
""",
)
add_docstr(
oneflow.Tensor.sinh,
"""
See :func:`oneflow.sinh`
""",
)
add_docstr(
oneflow.Tensor.size,
"""
The interface is consistent with PyTorch.
Returns the size of the self tensor. If dim is not specified, the returned value is a oneflow.Size, a subclass of tuple. If dim is specified, returns an int holding the size of that dimension.
Args:
idx (int, optional): The dimension for which to retrieve the size.
""",
)
add_docstr(
oneflow.Tensor.softmax,
"""
See :func:`oneflow.softmax`
""",
)
add_docstr(
oneflow.Tensor.softplus,
"""
See :func:`oneflow.softplus`
""",
)
add_docstr(
oneflow.Tensor.softsign,
"""
See :func:`oneflow.softsign`
""",
)
add_docstr(
oneflow.Tensor.tan,
"""
See :func:`oneflow.tan`
""",
)
add_docstr(
oneflow.Tensor.tanh,
"""
See :func:`oneflow.tanh`
""",
)
add_docstr(
oneflow.Tensor.tril,
"""
See :func:`oneflow.tril`
""",
)
add_docstr(
oneflow.Tensor.triu,
"""
See :func:`oneflow.triu`
""",
)
add_docstr(
oneflow.Tensor.uniform_,
"""
Tensor.uniform_(from=0, to=1) → Tensor
Fills self tensor with numbers sampled from the continuous uniform distribution:
.. math::
P(x)=1/(to-from)
""",
)
add_docstr(
oneflow.Tensor.copy_,
"""
The interface is consistent with PyTorch.
Tensor.copy_(src, non_blocking=False) → Tensor
Copies the elements from src into self tensor and returns self.
The src tensor must be broadcastable with the self tensor. It may be of a different data type or reside on a different device.
Args:
src (Tensor): the source tensor to copy from
non_blocking (bool): if True and this copy is between CPU and GPU, the copy may occur asynchronously with respect to the host. For other cases, this argument has no effect.
""",
)
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
""",
)
add_docstr(
oneflow.Tensor.gather,
"""
oneflow.Tensor.gather(dim, index) -> Tensor
See :func:`oneflow.gather`
""",
)
add_docstr(
oneflow.Tensor.clamp,
"""
See :func:`oneflow.clamp`.
""",
)
add_docstr(
oneflow.Tensor.clamp_,
"""
Inplace version of :func:`oneflow.Tensor.clamp`.
""",
)
add_docstr(
oneflow.Tensor.clip,
"""
Alias for :func:`oneflow.Tensor.clamp`.
""",
)
add_docstr(
oneflow.Tensor.clip_,
"""
Alias for :func:`oneflow.Tensor.clamp_`.
""",
)
add_docstr(
oneflow.Tensor.cpu,
r"""Returns a copy of this object in CPU memory.
If this object is already in CPU memory and on the correct device, then no copy is performed and the original object is returned.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> input = flow.tensor([1, 2, 3, 4, 5], device=flow.device("cuda"))
>>> output = input.cpu()
>>> output.device
device(type='cpu', index=0)
""",
)
add_docstr(
oneflow.Tensor.cuda,
r"""Returns a copy of this object in CUDA memory.
If this object is already in CUDA memory and on the correct device, then no copy is performed and the original object is returned.
Args:
device (flow.device): The destination GPU device. Defaults to the current CUDA device.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> input = flow.Tensor([1, 2, 3, 4, 5])
>>> output = input.cuda()
>>> output.device
device(type='cuda', index=0)
""",
)
add_docstr(
oneflow.Tensor.repeat,
"""
Tensor.repeat(*size) -> Tensor
See :func:`oneflow.repeat`
""",
)
add_docstr(
oneflow.Tensor.t,
"""
Tensor.t() → Tensor
See :func:`oneflow.t`
""",
)
add_docstr(
oneflow.Tensor.tile,
"""
Tensor.tile(*dims) -> Tensor
See :func:`oneflow.tile`
""",
)
add_docstr(
oneflow.Tensor.T,
"""
Is this Tensor with its dimensions reversed.
If `n` is the number of dimensions in `x`, `x.T` is equivalent to `x.permute(n-1, n-2, ..., 0)`.
""",
)
add_docstr(
oneflow.Tensor.fmod,
"""
Tensor.fmod(other) -> Tensor
See :func:`oneflow.fmod`
""",
)
add_docstr(
oneflow.Tensor.logical_and,
"""
logical_and() -> Tensor
See :func:`oneflow.logical_and`
""",
)
add_docstr(
oneflow.Tensor.logical_or,
"""
logical_or() -> Tensor
See :func:`oneflow.logical_or`
""",
)
add_docstr(
oneflow.Tensor.logical_xor,
"""
logical_xor() -> Tensor
See :func:`oneflow.logical_xor`
""",
)
add_docstr(
oneflow.Tensor.masked_fill,
"""
See :func:`oneflow.masked_fill`
""",
)
add_docstr(
oneflow.Tensor.masked_select,
"""
See :func:`oneflow.masked_select`
""",
)
add_docstr(
oneflow.Tensor.sub,
"""
See :func:`oneflow.sub`
""",
)
add_docstr(
oneflow.Tensor.div,
"""
See :func:`oneflow.div`
""",
)
add_docstr(
oneflow.Tensor.ceil,
"""
See :func:`oneflow.ceil`
""",
)
add_docstr(
oneflow.Tensor.expm1,
"""
See :func:`oneflow.expm1`
""",
)
add_docstr(
oneflow.Tensor.topk,
"""
See :func:`oneflow.topk`
""",
)
add_docstr(
oneflow.Tensor.nms,
"""
See :func:`oneflow.nms`
""",
)
add_docstr(
oneflow.Tensor.nonzero,
"""
nonzero(input, as_tuple=False) -> Tensor
See :func:`oneflow.nonzero`
""",
)
add_docstr(
oneflow.Tensor.max,
"""
input.max(dim, index) -> Tensor
See :func:`oneflow.max`
""",
)
add_docstr(
oneflow.Tensor.min,
"""
input.min(dim, index) -> Tensor
See :func:`oneflow.min`
""",
)
add_docstr(
oneflow.Tensor.sum,
"""
input.sum(dim, index) -> Tensor
See :func:`oneflow.sum`
""",
)
add_docstr(
oneflow.Tensor.mean,
"""
input.mean(dim, index) -> Tensor
See :func:`oneflow.mean`
""",
)
add_docstr(
oneflow.Tensor.prod,
"""
input.prod(dim, index) -> Tensor
See :func:`oneflow.prod`
""",
)
add_docstr(
oneflow.Tensor.reshape,
"""
See :func:`oneflow.reshape`
""",
)
add_docstr(
oneflow.Tensor.view,
"""
The interface is consistent with PyTorch.
The documentation is referenced from: https://pytorch.org/docs/stable/generated/torch.Tensor.view.html
Returns a new tensor with the same data as the :attr:`self` tensor but of a
different :attr:`shape`.
The returned tensor shares the same data and must have the same number
of elements, but may have a different size. For a tensor to be viewed, the new
view size must be compatible with its original size and stride, i.e., each new
view dimension must either be a subspace of an original dimension, or only span
across original dimensions :math:`d, d+1, \\dots, d+k` that satisfy the following
contiguity-like condition that :math:`\\forall i = d, \\dots, d+k-1`,
.. math::
\\text{stride}[i] = \\text{stride}[i+1] \\times \\text{size}[i+1]
Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape`
without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a
:meth:`view` can be performed, it is advisable to use :meth:`reshape`, which
returns a view if the shapes are compatible, and copies (equivalent to calling
:meth:`contiguous`) otherwise.
Args:
input: A Tensor.
*shape: flow.Size or int...
Returns:
A Tensor has the same type as `input`.
For example:
.. code-block:: python
>>> import numpy as np
>>> import oneflow as flow
>>> x = np.array(
... [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
... ).astype(np.float32)
>>> input = flow.Tensor(x)
>>> y = input.view(2, 2, 2, -1).numpy().shape
>>> y
(2, 2, 2, 2)
""",
)
add_docstr(
oneflow.Tensor.sort,
"""
See :func:`oneflow.sort`
""",
)
add_docstr(
oneflow.Tensor.type_as,
r"""Returns this tensor cast to the type of the given tensor.
This is a no-op if the tensor is already of the correct type.
Args:
input (Tensor): the input tensor.
target (Tensor): the tensor which has the desired type.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.float32)
>>> target = flow.tensor(np.random.randn(4, 5, 6), dtype = flow.int32)
>>> input = input.type_as(target)
>>> input.dtype
oneflow.int32
""",
)
add_docstr(
oneflow.Tensor.int,
r"""`Tensor.int()` is equivalent to `Tensor.to(flow.int32)`. See to().
Args:
input (Tensor): the input tensor.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.float32)
>>> input = input.int()
>>> input.dtype
oneflow.int32
""",
)
add_docstr(
oneflow.Tensor.long,
r"""`Tensor.long()` is equivalent to `Tensor.to(flow.int64)`. See to().
Args:
input (Tensor): the input tensor.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.float32)
>>> input = input.long()
>>> input.dtype
oneflow.int64
""",
)
add_docstr(
oneflow.Tensor.float,
r"""`Tensor.float()` is equivalent to `Tensor.to(flow.float32)`. See to().
Args:
input (Tensor): the input tensor.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.int)
>>> input = input.float()
>>> input.dtype
oneflow.float32
""",
)
add_docstr(
oneflow.Tensor.double,
r"""`Tensor.double()` is equivalent to `Tensor.to(flow.float64)`. See to().
Args:
input (Tensor): the input tensor.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.int)
>>> input = input.double()
>>> input.dtype
oneflow.float64
""",
)
add_docstr(
oneflow.Tensor.is_floating_point,
"""
See :func:`oneflow.is_floating_point`
""",
)
add_docstr(
oneflow.Tensor.item,
r"""Returns the value of this tensor as a standard Python number. This only works for tensors with one element.
For other cases, see tolist().
This operation is not differentiable.
Args:
input (Tensor): the input tensor.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> x = flow.tensor([1.0])
>>> x.item()
1.0
""",
)
add_docstr(
oneflow.Tensor.tolist,
r"""Returns the tensor as a (nested) list. For scalars, a standard Python number is returned,
just like with `item()`. Tensors are automatically moved to the CPU first if necessary.
This operation is not differentiable.
Args:
input (Tensor): the input tensor.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> input = flow.tensor([[1,2,3], [4,5,6]])
>>> input.tolist()
[[1, 2, 3], [4, 5, 6]]
""",
)
add_docstr(
oneflow.Tensor.where,
"""
See :func:`oneflow.where`
""",
)
| [
"oneflow.framework.docstr.utils.add_docstr"
] | [((660, 1875), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.tensor', '"""\n Constructs a tensor with data, return a global 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 Note:\n The Keyword Argument device is mutually exclusive with placement and sbp.\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 global 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 Note:\n The Keyword Argument device is mutually exclusive with placement and sbp.\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, 1875), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((1880, 2690), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.from_numpy', '"""\n Creates a ``Tensor`` from a ``numpy.ndarray``.\n\n The returned tensor and ndarray share the same memory. Modifications to the tensor\n will be reflected in the ndarray and vice versa.\n\n It currently accepts ndarray with dtypes of numpy.float64, numpy.float32, numpy.float16,\n numpy.int64, numpy.int32, numpy.int8, numpy.uint8.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n >>> np_arr = np.arange(6).reshape(2, 3)\n >>> t = flow.from_numpy(np_arr)\n >>> t\n tensor([[0, 1, 2],\n [3, 4, 5]], dtype=oneflow.int64)\n >>> np_arr[0, 0] = -1\n >>> t\n tensor([[-1, 1, 2],\n [ 3, 4, 5]], dtype=oneflow.int64)\n """'], {}), '(oneflow.from_numpy,\n """\n Creates a ``Tensor`` from a ``numpy.ndarray``.\n\n The returned tensor and ndarray share the same memory. Modifications to the tensor\n will be reflected in the ndarray and vice versa.\n\n It currently accepts ndarray with dtypes of numpy.float64, numpy.float32, numpy.float16,\n numpy.int64, numpy.int32, numpy.int8, numpy.uint8.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n >>> np_arr = np.arange(6).reshape(2, 3)\n >>> t = flow.from_numpy(np_arr)\n >>> t\n tensor([[0, 1, 2],\n [3, 4, 5]], dtype=oneflow.int64)\n >>> np_arr[0, 0] = -1\n >>> t\n tensor([[-1, 1, 2],\n [ 3, 4, 5]], dtype=oneflow.int64)\n """\n )\n', (1890, 2690), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((2696, 2982), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.device', '"""\n The documentation is referenced from:\n https://pytorch.org/docs/stable/generated/torch.Tensor.device.html#torch.Tensor.device\n \n Is the :class:`oneflow.device` where this Tensor is, which is invalid for global tensor.\n """'], {}), '(oneflow.Tensor.device,\n """\n The documentation is referenced from:\n https://pytorch.org/docs/stable/generated/torch.Tensor.device.html#torch.Tensor.device\n \n Is the :class:`oneflow.device` where this Tensor is, which is invalid for global tensor.\n """\n )\n', (2706, 2982), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((2987, 3140), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.placement', '"""\n Is the :class:`oneflow.placement` where this Tensor is, which is invalid for local tensor.\n """'], {}), '(oneflow.Tensor.placement,\n """\n Is the :class:`oneflow.placement` where this Tensor is, which is invalid for local tensor.\n """\n )\n', (2997, 3140), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((3145, 3327), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.sbp', '"""\n Is the ``oneflow.sbp`` representing that how the data of the global tensor is distributed, which is invalid for local tensor.\n """'], {}), '(oneflow.Tensor.sbp,\n """\n Is the ``oneflow.sbp`` representing that how the data of the global tensor is distributed, which is invalid for local tensor.\n """\n )\n', (3155, 3327), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((3332, 3436), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.is_global', '"""\n Return whether this Tensor is a global tensor.\n """'], {}), '(oneflow.Tensor.is_global,\n """\n Return whether this Tensor is a global tensor.\n """)\n', (3342, 3436), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((3446, 3546), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.is_lazy', '"""\n Return whether this Tensor is a lazy tensor.\n """'], {}), '(oneflow.Tensor.is_lazy,\n """\n Return whether this Tensor is a lazy tensor.\n """)\n', (3456, 3546), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((3556, 3631), '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', (3566, 3631), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((3645, 3757), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.expand', '"""\n Tensor.expand() -> Tensor\n\n See :func:`oneflow.expand`\n """'], {}), '(oneflow.Tensor.expand,\n """\n Tensor.expand() -> Tensor\n\n See :func:`oneflow.expand`\n """)\n', (3655, 3757), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((3766, 4188), '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', (3776, 4188), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4192, 4271), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.flatten', '"""\n See :func:`oneflow.flatten`\n """'], {}), '(oneflow.Tensor.flatten, """\n See :func:`oneflow.flatten`\n """)\n', (4202, 4271), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4284, 4359), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.floor', '"""\n See :func:`oneflow.floor`\n """'], {}), '(oneflow.Tensor.floor, """\n See :func:`oneflow.floor`\n """)\n', (4294, 4359), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4372, 4445), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.flip', '"""\n See :func:`oneflow.flip`\n """'], {}), '(oneflow.Tensor.flip, """\n See :func:`oneflow.flip`\n """)\n', (4382, 4445), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4458, 4604), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.in_top_k', '"""\n Tensor.in_top_k(targets, predictions, k) -> Tensor\n\n See :func:`oneflow.in_top_k`\n """'], {}), '(oneflow.Tensor.in_top_k,\n """\n Tensor.in_top_k(targets, predictions, k) -> Tensor\n\n See :func:`oneflow.in_top_k`\n """\n )\n', (4468, 4604), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4608, 4753), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.index_select', '"""\n Tensor.index_select(dim, index) -> Tensor\n\n See :func:`oneflow.index_select`\n """'], {}), '(oneflow.Tensor.index_select,\n """\n Tensor.index_select(dim, index) -> Tensor\n\n See :func:`oneflow.index_select`\n """\n )\n', (4618, 4753), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4757, 4832), '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', (4767, 4832), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4845, 4968), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.new_ones', '"""\n Tensor.new_ones() -> Tensor\n\n See :func:`oneflow.new_ones`\n """'], {}), '(oneflow.Tensor.new_ones,\n """\n Tensor.new_ones() -> Tensor\n\n See :func:`oneflow.new_ones`\n """\n )\n', (4855, 4968), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((4972, 8177), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.to_global', '"""\n Tensor.to_global(placement=None, sbp=None, grad_sbp=None) -> Tensor\n\n Creates a global tensor if this tensor is a local tensor, otherwise performs Tensor placement and/or sbp conversion.\n\n Note:\n This tensor can be local tensor or global tensor.\n\n - For local tensor\n\n Both placement and sbp are required.\n\n The returned global tensor takes this tensor as its local component in the current rank.\n\n There is no data communication usually, but when sbp is ``oneflow.sbp.broadcast``, the data on rank 0 will be broadcast to other ranks.\n\n - For global tensor\n\n At least one of placement and sbp is required.\n\n If placement and sbp are all the same as this tensor\'s own placement and sbp, then returns this tensor own.\n \n Args:\n placement (flow.placement, optional): the desired placement of returned global tensor. Default: None\n sbp (flow.sbp.sbp or tuple of flow.sbp.sbp, optional): the desired sbp of returned global tensor. Default: None\n grad_sbp (flow.sbp.sbp or tuple of flow.sbp.sbp, optional): manually specify the sbp of this tensor\'s grad tensor in the backward pass. If None, the grad tensor sbp will be infered automatically. It is only used if this tensor is a global tensor. Default: None\n\n For local tensor:\n\n .. code-block:: python\n\n >>> # Run on 2 ranks respectively\n >>> import oneflow as flow\n >>> input = flow.tensor([0., 1.], dtype=flow.float32) # doctest: +SKIP\n >>> output = input.to_global(placement=flow.placement("cpu", ranks=[0, 1]), sbp=[flow.sbp.split(0)]) # doctest: +SKIP\n >>> print(output.size()) # doctest: +SKIP\n >>> print(output) # doctest: +SKIP\n\n .. code-block:: python\n\n >>> # results on rank 0\n oneflow.Size([4])\n tensor([0., 1., 0., 1.], placement=oneflow.placement(type="cpu", ranks=[0, 1]), sbp=(oneflow.sbp.split(axis=0),), dtype=oneflow.float32) \n \n .. code-block:: python\n\n >>> # results on rank 1\n oneflow.Size([4])\n tensor([0., 1., 0., 1.], placement=oneflow.placement(type="cpu", ranks=[0, 1]), sbp=(oneflow.sbp.split(axis=0),), dtype=oneflow.float32)\n\n For global tensor:\n\n .. code-block:: python\n\n >>> # Run on 2 ranks respectively\n >>> import oneflow as flow\n >>> input = flow.tensor([0., 1.], dtype=flow.float32, placement=flow.placement("cpu", ranks=[0, 1]), sbp=[flow.sbp.broadcast]) # doctest: +SKIP\n >>> output = input.to_global(placement=flow.placement("cpu", ranks=[0, 1]), sbp=[flow.sbp.split(0)]) # doctest: +SKIP\n >>> print(output.size()) # doctest: +SKIP\n >>> print(output) # doctest: +SKIP\n\n .. code-block:: python\n\n >>> # results on rank 0\n oneflow.Size([2])\n tensor([0., 1.], placement=oneflow.placement(type="cpu", ranks=[0, 1]), sbp=(oneflow.sbp.split(axis=0),), dtype=oneflow.float32)\n\n .. code-block:: python\n\n >>> # results on rank 1\n oneflow.Size([2])\n tensor([0., 1.], placement=oneflow.placement(type="cpu", ranks=[0, 1]), sbp=(oneflow.sbp.split(axis=0),), dtype=oneflow.float32)\n """'], {}), '(oneflow.Tensor.to_global,\n """\n Tensor.to_global(placement=None, sbp=None, grad_sbp=None) -> Tensor\n\n Creates a global tensor if this tensor is a local tensor, otherwise performs Tensor placement and/or sbp conversion.\n\n Note:\n This tensor can be local tensor or global tensor.\n\n - For local tensor\n\n Both placement and sbp are required.\n\n The returned global tensor takes this tensor as its local component in the current rank.\n\n There is no data communication usually, but when sbp is ``oneflow.sbp.broadcast``, the data on rank 0 will be broadcast to other ranks.\n\n - For global tensor\n\n At least one of placement and sbp is required.\n\n If placement and sbp are all the same as this tensor\'s own placement and sbp, then returns this tensor own.\n \n Args:\n placement (flow.placement, optional): the desired placement of returned global tensor. Default: None\n sbp (flow.sbp.sbp or tuple of flow.sbp.sbp, optional): the desired sbp of returned global tensor. Default: None\n grad_sbp (flow.sbp.sbp or tuple of flow.sbp.sbp, optional): manually specify the sbp of this tensor\'s grad tensor in the backward pass. If None, the grad tensor sbp will be infered automatically. It is only used if this tensor is a global tensor. Default: None\n\n For local tensor:\n\n .. code-block:: python\n\n >>> # Run on 2 ranks respectively\n >>> import oneflow as flow\n >>> input = flow.tensor([0., 1.], dtype=flow.float32) # doctest: +SKIP\n >>> output = input.to_global(placement=flow.placement("cpu", ranks=[0, 1]), sbp=[flow.sbp.split(0)]) # doctest: +SKIP\n >>> print(output.size()) # doctest: +SKIP\n >>> print(output) # doctest: +SKIP\n\n .. code-block:: python\n\n >>> # results on rank 0\n oneflow.Size([4])\n tensor([0., 1., 0., 1.], placement=oneflow.placement(type="cpu", ranks=[0, 1]), sbp=(oneflow.sbp.split(axis=0),), dtype=oneflow.float32) \n \n .. code-block:: python\n\n >>> # results on rank 1\n oneflow.Size([4])\n tensor([0., 1., 0., 1.], placement=oneflow.placement(type="cpu", ranks=[0, 1]), sbp=(oneflow.sbp.split(axis=0),), dtype=oneflow.float32)\n\n For global tensor:\n\n .. code-block:: python\n\n >>> # Run on 2 ranks respectively\n >>> import oneflow as flow\n >>> input = flow.tensor([0., 1.], dtype=flow.float32, placement=flow.placement("cpu", ranks=[0, 1]), sbp=[flow.sbp.broadcast]) # doctest: +SKIP\n >>> output = input.to_global(placement=flow.placement("cpu", ranks=[0, 1]), sbp=[flow.sbp.split(0)]) # doctest: +SKIP\n >>> print(output.size()) # doctest: +SKIP\n >>> print(output) # doctest: +SKIP\n\n .. code-block:: python\n\n >>> # results on rank 0\n oneflow.Size([2])\n tensor([0., 1.], placement=oneflow.placement(type="cpu", ranks=[0, 1]), sbp=(oneflow.sbp.split(axis=0),), dtype=oneflow.float32)\n\n .. code-block:: python\n\n >>> # results on rank 1\n oneflow.Size([2])\n tensor([0., 1.], placement=oneflow.placement(type="cpu", ranks=[0, 1]), sbp=(oneflow.sbp.split(axis=0),), dtype=oneflow.float32)\n """\n )\n', (4982, 8177), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((8181, 8339), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.to_consistent', '"""\n This interface is no longer available, please use :func:`oneflow.Tensor.to_global` instead.\n """'], {}), '(oneflow.Tensor.to_consistent,\n """\n This interface is no longer available, please use :func:`oneflow.Tensor.to_global` instead.\n """\n )\n', (8191, 8339), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((8343, 9355), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.to_local', '"""\n Tensor.to_local() -> Tensor\n\n Returns the local component of this global tensor in the current rank.\n\n Note:\n This tensor should be a global tensor, and it returns a empty tensor if there is no local component in the current rank.\n\n No copy occurred in this operation.\n\n For example:\n\n .. code-block:: python\n\n >>> # Run on 2 ranks respectively\n >>> import oneflow as flow\n >>> x = flow.tensor([0., 1.], dtype=flow.float32, placement=flow.placement("cpu", ranks=[0, 1]), sbp=[flow.sbp.split(0)]) # doctest: +SKIP\n >>> y = x.to_local() # doctest: +SKIP\n >>> print(y.size()) # doctest: +SKIP\n >>> print(y) # doctest: +SKIP\n\n .. code-block:: python\n\n >>> # results on rank 0\n oneflow.Size([1])\n tensor([0.], dtype=oneflow.float32)\n\n .. code-block:: python\n\n >>> # results on rank 1\n oneflow.Size([1])\n tensor([1.], dtype=oneflow.float32)\n """'], {}), '(oneflow.Tensor.to_local,\n """\n Tensor.to_local() -> Tensor\n\n Returns the local component of this global tensor in the current rank.\n\n Note:\n This tensor should be a global tensor, and it returns a empty tensor if there is no local component in the current rank.\n\n No copy occurred in this operation.\n\n For example:\n\n .. code-block:: python\n\n >>> # Run on 2 ranks respectively\n >>> import oneflow as flow\n >>> x = flow.tensor([0., 1.], dtype=flow.float32, placement=flow.placement("cpu", ranks=[0, 1]), sbp=[flow.sbp.split(0)]) # doctest: +SKIP\n >>> y = x.to_local() # doctest: +SKIP\n >>> print(y.size()) # doctest: +SKIP\n >>> print(y) # doctest: +SKIP\n\n .. code-block:: python\n\n >>> # results on rank 0\n oneflow.Size([1])\n tensor([0.], dtype=oneflow.float32)\n\n .. code-block:: python\n\n >>> # results on rank 1\n oneflow.Size([1])\n tensor([1.], dtype=oneflow.float32)\n """\n )\n', (8353, 9355), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((9359, 9446), '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', (9369, 9446), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((9455, 9579), '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', (9465, 9579), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((9583, 9656), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.sqrt', '"""\n See :func:`oneflow.sqrt`\n """'], {}), '(oneflow.Tensor.sqrt, """\n See :func:`oneflow.sqrt`\n """)\n', (9593, 9656), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((9669, 9746), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.square', '"""\n See :func:`oneflow.square`\n """'], {}), '(oneflow.Tensor.square, """\n See :func:`oneflow.square`\n """)\n', (9679, 9746), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((9759, 9830), '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', (9769, 9830), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((9843, 9914), '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', (9853, 9914), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((9927, 10006), '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', (9937, 10006), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((10019, 11400), '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], dtype=oneflow.int64)\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]], dtype=oneflow.int64)\n >>> x.unfold(0, 2, 2)\n tensor([[1, 2],\n [3, 4],\n [5, 6]], dtype=oneflow.int64)\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], dtype=oneflow.int64)\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]], dtype=oneflow.int64)\n >>> x.unfold(0, 2, 2)\n tensor([[1, 2],\n [3, 4],\n [5, 6]], dtype=oneflow.int64)\n """\n )\n', (10029, 11400), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((11404, 11481), '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', (11414, 11481), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((11494, 11571), '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', (11504, 11571), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((11584, 11671), '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', (11594, 11671), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((11680, 11759), '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', (11690, 11759), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((11772, 11843), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.abs', '"""\n See :func:`oneflow.abs`\n """'], {}), '(oneflow.Tensor.abs, """\n See :func:`oneflow.abs`\n """)\n', (11782, 11843), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((11856, 11929), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.acos', '"""\n See :func:`oneflow.acos`\n """'], {}), '(oneflow.Tensor.acos, """\n See :func:`oneflow.acos`\n """)\n', (11866, 11929), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((11942, 12019), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.arccos', '"""\n See :func:`oneflow.arccos`\n """'], {}), '(oneflow.Tensor.arccos, """\n See :func:`oneflow.arccos`\n """)\n', (11952, 12019), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((12032, 12107), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.acosh', '"""\n See :func:`oneflow.acosh`\n """'], {}), '(oneflow.Tensor.acosh, """\n See :func:`oneflow.acosh`\n """)\n', (12042, 12107), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((12120, 12199), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.arccosh', '"""\n See :func:`oneflow.arccosh`\n """'], {}), '(oneflow.Tensor.arccosh, """\n See :func:`oneflow.arccosh`\n """)\n', (12130, 12199), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((12212, 12291), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.arctanh', '"""\n See :func:`oneflow.arctanh`\n """'], {}), '(oneflow.Tensor.arctanh, """\n See :func:`oneflow.arctanh`\n """)\n', (12222, 12291), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((12304, 12381), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.argmax', '"""\n See :func:`oneflow.argmax`\n """'], {}), '(oneflow.Tensor.argmax, """\n See :func:`oneflow.argmax`\n """)\n', (12314, 12381), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((12394, 12471), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.argmin', '"""\n See :func:`oneflow.argmin`\n """'], {}), '(oneflow.Tensor.argmin, """\n See :func:`oneflow.argmin`\n """)\n', (12404, 12471), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((12484, 13669), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.argsort', '"""This operator sorts the input Tensor at specified dim and return the indices of the sorted Tensor.\n\n Args:\n input (oneflow.Tensor): The input Tensor.\n dim (int, optional): dimension to be sorted. Defaults to the last dim (-1).\n descending (bool, optional): controls the sorting order (ascending or descending).\n\n Returns:\n oneflow.Tensor: The indices of the sorted Tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import numpy as np\n >>> import oneflow as flow\n >>> x = np.array([[10, 2, 9, 3, 7],\n ... [1, 9, 4, 3, 2]]).astype("float32")\n >>> input = flow.Tensor(x)\n >>> output = flow.argsort(input)\n >>> output\n tensor([[1, 3, 4, 2, 0],\n [0, 4, 3, 2, 1]], dtype=oneflow.int32)\n >>> output = flow.argsort(input, descending=True)\n >>> output\n tensor([[0, 2, 4, 3, 1],\n [1, 2, 3, 4, 0]], dtype=oneflow.int32)\n >>> output = flow.argsort(input, dim=0)\n >>> output\n tensor([[1, 0, 1, 0, 1],\n [0, 1, 0, 1, 0]], dtype=oneflow.int32)\n\n """'], {}), '(oneflow.Tensor.argsort,\n """This operator sorts the input Tensor at specified dim and return the indices of the sorted Tensor.\n\n Args:\n input (oneflow.Tensor): The input Tensor.\n dim (int, optional): dimension to be sorted. Defaults to the last dim (-1).\n descending (bool, optional): controls the sorting order (ascending or descending).\n\n Returns:\n oneflow.Tensor: The indices of the sorted Tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import numpy as np\n >>> import oneflow as flow\n >>> x = np.array([[10, 2, 9, 3, 7],\n ... [1, 9, 4, 3, 2]]).astype("float32")\n >>> input = flow.Tensor(x)\n >>> output = flow.argsort(input)\n >>> output\n tensor([[1, 3, 4, 2, 0],\n [0, 4, 3, 2, 1]], dtype=oneflow.int32)\n >>> output = flow.argsort(input, descending=True)\n >>> output\n tensor([[0, 2, 4, 3, 1],\n [1, 2, 3, 4, 0]], dtype=oneflow.int32)\n >>> output = flow.argsort(input, dim=0)\n >>> output\n tensor([[1, 0, 1, 0, 1],\n [0, 1, 0, 1, 0]], dtype=oneflow.int32)\n\n """\n )\n', (12494, 13669), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((13673, 13758), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.argwhere', '"""\n See :func:`oneflow.argwhere`\n """'], {}), '(oneflow.Tensor.argwhere,\n """\n See :func:`oneflow.argwhere`\n """)\n', (13683, 13758), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((13767, 13842), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.atanh', '"""\n See :func:`oneflow.atanh`\n """'], {}), '(oneflow.Tensor.atanh, """\n See :func:`oneflow.atanh`\n """)\n', (13777, 13842), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((13855, 16002), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.backward', '"""\n The interface is consistent with PyTorch.\n The documentation is referenced from: https://pytorch.org/docs/stable/generated/torch.Tensor.backward.html#torch.Tensor.backward.\n\n Computes the gradient of current tensor w.r.t. graph leaves.\n\n The graph is differentiated using the chain rule. If the tensor is non-scalar (i.e. its data has more than one element) and requires gradient, the function additionally requires specifying gradient. It should be a tensor of matching type and location, that contains the gradient of the differentiated function w.r.t. self.\n\n This function accumulates gradients in the leaves - you might need to zero .grad attributes or set them to None before calling it. See Default gradient layouts for details on the memory layout of accumulated gradients.\n\n Note:\n If you run any forward ops, create gradient, and/or call backward in a user-specified CUDA stream context, see Stream semantics of backward passes.\n Note:\n When inputs are provided and a given input is not a leaf, the current implementation will call its grad_fn (though it is not strictly needed to get this gradients). It is an implementation detail on which the user should not rely. See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.\n\n Args:\n gradient (Tensor or None): Gradient w.r.t. the tensor. If it is a tensor, it will be automatically converted to a Tensor that does not require grad unless create_graph is True. None values can be specified for scalar Tensors or ones that don’t require grad. If a None value would be acceptable then this argument is optional.\n\n retain_graph (bool, optional): If False, the graph used to compute the grads will be freed. Note that in nearly all cases setting this option to True is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph.\n\n create_graph (bool, optional): If True, graph of the derivative will be constructed, allowing to compute higher order derivative products. Defaults to False.\n """'], {}), '(oneflow.Tensor.backward,\n """\n The interface is consistent with PyTorch.\n The documentation is referenced from: https://pytorch.org/docs/stable/generated/torch.Tensor.backward.html#torch.Tensor.backward.\n\n Computes the gradient of current tensor w.r.t. graph leaves.\n\n The graph is differentiated using the chain rule. If the tensor is non-scalar (i.e. its data has more than one element) and requires gradient, the function additionally requires specifying gradient. It should be a tensor of matching type and location, that contains the gradient of the differentiated function w.r.t. self.\n\n This function accumulates gradients in the leaves - you might need to zero .grad attributes or set them to None before calling it. See Default gradient layouts for details on the memory layout of accumulated gradients.\n\n Note:\n If you run any forward ops, create gradient, and/or call backward in a user-specified CUDA stream context, see Stream semantics of backward passes.\n Note:\n When inputs are provided and a given input is not a leaf, the current implementation will call its grad_fn (though it is not strictly needed to get this gradients). It is an implementation detail on which the user should not rely. See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.\n\n Args:\n gradient (Tensor or None): Gradient w.r.t. the tensor. If it is a tensor, it will be automatically converted to a Tensor that does not require grad unless create_graph is True. None values can be specified for scalar Tensors or ones that don’t require grad. If a None value would be acceptable then this argument is optional.\n\n retain_graph (bool, optional): If False, the graph used to compute the grads will be freed. Note that in nearly all cases setting this option to True is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph.\n\n create_graph (bool, optional): If True, graph of the derivative will be constructed, allowing to compute higher order derivative products. Defaults to False.\n """\n )\n', (13865, 16002), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((16006, 16151), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.grad', '"""\n Return the gradient calculated by autograd functions. This property is None by default.\n """'], {}), '(oneflow.Tensor.grad,\n """\n Return the gradient calculated by autograd functions. This property is None by default.\n """\n )\n', (16016, 16151), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((16156, 16296), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.grad_fn', '"""\n Return the function that created this tensor if it\'s ``requires_grad`` is True.\n """'], {}), '(oneflow.Tensor.grad_fn,\n """\n Return the function that created this tensor if it\'s ``requires_grad`` is True.\n """\n )\n', (16166, 16296), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((16301, 17168), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.is_leaf', '"""\n Compatible with PyTorch.\n\n All Tensors that have ``requires_grad`` which is ``False`` will be leaf Tensors by convention.\n\n For Tensor that have ``requires_grad`` which is ``True``, they will be leaf Tensors if they\n were created by source operations.\n\n Only leaf Tensors will have their ``grad`` populated during a call to ``backward()``. To get\n ``grad`` populated for non-leaf Tensors, you can use ``retain_grad()``.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> a = flow.rand(10, requires_grad=False)\n >>> a.is_leaf\n True\n >>> a = flow.rand(10, requires_grad=True)\n >>> a.is_leaf\n True\n >>> b = a.cuda()\n >>> b.is_leaf\n False\n >>> c = a + 2\n >>> c.is_leaf\n False\n """'], {}), '(oneflow.Tensor.is_leaf,\n """\n Compatible with PyTorch.\n\n All Tensors that have ``requires_grad`` which is ``False`` will be leaf Tensors by convention.\n\n For Tensor that have ``requires_grad`` which is ``True``, they will be leaf Tensors if they\n were created by source operations.\n\n Only leaf Tensors will have their ``grad`` populated during a call to ``backward()``. To get\n ``grad`` populated for non-leaf Tensors, you can use ``retain_grad()``.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> a = flow.rand(10, requires_grad=False)\n >>> a.is_leaf\n True\n >>> a = flow.rand(10, requires_grad=True)\n >>> a.is_leaf\n True\n >>> b = a.cuda()\n >>> b.is_leaf\n False\n >>> c = a + 2\n >>> c.is_leaf\n False\n """\n )\n', (16311, 17168), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((17173, 17351), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.requires_grad', '"""\n Compatible with PyTorch.\n\n Is ``True`` if gradient need to be computed for this Tensor, ``False`` otherwise.\n """'], {}), '(oneflow.Tensor.requires_grad,\n """\n Compatible with PyTorch.\n\n Is ``True`` if gradient need to be computed for this Tensor, ``False`` otherwise.\n """\n )\n', (17183, 17351), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((17356, 17885), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.requires_grad_', '"""oneflow.Tensor.requires_grad_(requires_grad=True) -> Tensor\n Compatible with PyTorch.\n\n Args:\n requires_grad (bool): Change the requires_grad flag for this Tensor. Default is ``True``.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> a = flow.rand(10, requires_grad=False)\n >>> a.requires_grad\n False\n >>> a = a.requires_grad_(requires_grad=True)\n >>> a.requires_grad\n True\n """'], {}), '(oneflow.Tensor.requires_grad_,\n """oneflow.Tensor.requires_grad_(requires_grad=True) -> Tensor\n Compatible with PyTorch.\n\n Args:\n requires_grad (bool): Change the requires_grad flag for this Tensor. Default is ``True``.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> a = flow.rand(10, requires_grad=False)\n >>> a.requires_grad\n False\n >>> a = a.requires_grad_(requires_grad=True)\n >>> a.requires_grad\n True\n """\n )\n', (17366, 17885), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((17890, 18712), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.register_hook', '"""oneflow.Tensor.register_hook(hook)\n\n Registers a backward hook.\n\n The hook will be called every time a gradient with respect to the Tensor is computed.\n The hook should have the following signature:\n\n .. code-block:: \n\n hook(grad) -> Tensor or None\n\n\n The hook should not modify its argument, but it can optionally return a new gradient which\n will be used in place of ``grad``.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> x = flow.ones(5, requires_grad=True)\n >>> def hook(grad):\n ... return grad * 2\n >>> x.register_hook(hook)\n >>> y = x * 2\n >>> y.sum().backward()\n >>> x.grad\n tensor([4., 4., 4., 4., 4.], dtype=oneflow.float32)\n """'], {}), '(oneflow.Tensor.register_hook,\n """oneflow.Tensor.register_hook(hook)\n\n Registers a backward hook.\n\n The hook will be called every time a gradient with respect to the Tensor is computed.\n The hook should have the following signature:\n\n .. code-block:: \n\n hook(grad) -> Tensor or None\n\n\n The hook should not modify its argument, but it can optionally return a new gradient which\n will be used in place of ``grad``.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> x = flow.ones(5, requires_grad=True)\n >>> def hook(grad):\n ... return grad * 2\n >>> x.register_hook(hook)\n >>> y = x * 2\n >>> y.sum().backward()\n >>> x.grad\n tensor([4., 4., 4., 4., 4.], dtype=oneflow.float32)\n """\n )\n', (17900, 18712), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((18717, 18925), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.retain_grad', '"""\n Compatible with PyTorch.\n\n Enables this Tensor to have their ``grad`` populated during ``backward()``. This is a no-op\n for leaf tensors.\n """'], {}), '(oneflow.Tensor.retain_grad,\n """\n Compatible with PyTorch.\n\n Enables this Tensor to have their ``grad`` populated during ``backward()``. This is a no-op\n for leaf tensors.\n """\n )\n', (18727, 18925), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((18930, 19001), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.bmm', '"""\n See :func:`oneflow.bmm`\n """'], {}), '(oneflow.Tensor.bmm, """\n See :func:`oneflow.bmm`\n """)\n', (18940, 19001), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((19014, 19089), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.chunk', '"""\n See :func:`oneflow.chunk`\n """'], {}), '(oneflow.Tensor.chunk, """\n See :func:`oneflow.chunk`\n """)\n', (19024, 19089), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((19102, 19177), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.split', '"""\n See :func:`oneflow.split`\n """'], {}), '(oneflow.Tensor.split, """\n See :func:`oneflow.split`\n """)\n', (19112, 19177), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((19190, 19275), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.swapaxes', '"""\n See :func:`oneflow.swapaxes`\n """'], {}), '(oneflow.Tensor.swapaxes,\n """\n See :func:`oneflow.swapaxes`\n """)\n', (19200, 19275), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((19284, 19357), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.cast', '"""\n See :func:`oneflow.cast`\n """'], {}), '(oneflow.Tensor.cast, """\n See :func:`oneflow.cast`\n """)\n', (19294, 19357), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((19370, 19443), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.diag', '"""\n See :func:`oneflow.diag`\n """'], {}), '(oneflow.Tensor.diag, """\n See :func:`oneflow.diag`\n """)\n', (19380, 19443), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((19456, 19585), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.dim', '"""\n Tensor.dim() → int\n\n Returns the number of dimensions of self tensor.\n """'], {}), '(oneflow.Tensor.dim,\n """\n Tensor.dim() → int\n\n Returns the number of dimensions of self tensor.\n """\n )\n', (19466, 19585), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((19589, 19740), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.element_size', '"""\n Tensor.element_size() → int\n\n Returns the size in bytes of an individual element.\n\n """'], {}), '(oneflow.Tensor.element_size,\n """\n Tensor.element_size() → int\n\n Returns the size in bytes of an individual element.\n\n """\n )\n', (19599, 19740), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((19744, 19815), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.exp', '"""\n See :func:`oneflow.exp`\n """'], {}), '(oneflow.Tensor.exp, """\n See :func:`oneflow.exp`\n """)\n', (19754, 19815), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((19828, 19931), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.erf', '"""\n Tensor.erf() -> Tensor\n\n See :func:`oneflow.erf`\n """'], {}), '(oneflow.Tensor.erf,\n """\n Tensor.erf() -> Tensor\n\n See :func:`oneflow.erf`\n """)\n', (19838, 19931), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((19940, 20046), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.erfc', '"""\n Tensor.erfc() -> Tensor\n\n See :func:`oneflow.erfc`\n """'], {}), '(oneflow.Tensor.erfc,\n """\n Tensor.erfc() -> Tensor\n\n See :func:`oneflow.erfc`\n """)\n', (19950, 20046), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((20055, 20132), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.erfinv', '"""\n See :func:`oneflow.erfinv`\n """'], {}), '(oneflow.Tensor.erfinv, """\n See :func:`oneflow.erfinv`\n """)\n', (20065, 20132), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((20145, 20242), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.erfinv_', '"""\n Inplace version of :func:`oneflow.erfinv`\n """'], {}), '(oneflow.Tensor.erfinv_,\n """\n Inplace version of :func:`oneflow.erfinv`\n """)\n', (20155, 20242), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((20251, 20320), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.eq', '"""\n See :func:`oneflow.eq`\n """'], {}), '(oneflow.Tensor.eq, """\n See :func:`oneflow.eq`\n """)\n', (20261, 20320), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((20333, 20402), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.lt', '"""\n See :func:`oneflow.lt`\n """'], {}), '(oneflow.Tensor.lt, """\n See :func:`oneflow.lt`\n """)\n', (20343, 20402), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((20415, 20484), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.le', '"""\n See :func:`oneflow.le`\n """'], {}), '(oneflow.Tensor.le, """\n See :func:`oneflow.le`\n """)\n', (20425, 20484), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((20497, 20566), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.ne', '"""\n See :func:`oneflow.ne`\n """'], {}), '(oneflow.Tensor.ne, """\n See :func:`oneflow.ne`\n """)\n', (20507, 20566), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((20579, 20715), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.fill_', '"""\n Tensor.fill_(value) → Tensor\n\n Fills self tensor with the specified value.\n """'], {}), '(oneflow.Tensor.fill_,\n """\n Tensor.fill_(value) → Tensor\n\n Fills self tensor with the specified value.\n """\n )\n', (20589, 20715), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((20719, 20788), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.ge', '"""\n See :func:`oneflow.ge`\n """'], {}), '(oneflow.Tensor.ge, """\n See :func:`oneflow.ge`\n """)\n', (20729, 20788), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((20801, 20874), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.gelu', '"""\n See :func:`oneflow.gelu`\n """'], {}), '(oneflow.Tensor.gelu, """\n See :func:`oneflow.gelu`\n """)\n', (20811, 20874), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((20887, 21141), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.get_device', '"""\n Tensor.get_device() -> Device ordinal (Integer)\n\n For CUDA tensors, this function returns the device ordinal of the GPU on which the tensor resides. For CPU tensors, an error is thrown.\n\n\n """'], {}), '(oneflow.Tensor.get_device,\n """\n Tensor.get_device() -> Device ordinal (Integer)\n\n For CUDA tensors, this function returns the device ordinal of the GPU on which the tensor resides. For CPU tensors, an error is thrown.\n\n\n """\n )\n', (20897, 21141), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((21145, 21214), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.gt', '"""\n See :func:`oneflow.gt`\n """'], {}), '(oneflow.Tensor.gt, """\n See :func:`oneflow.gt`\n """)\n', (21155, 21214), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((21227, 21302), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.log1p', '"""\n See :func:`oneflow.log1p`\n """'], {}), '(oneflow.Tensor.log1p, """\n See :func:`oneflow.log1p`\n """)\n', (21237, 21302), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((21315, 21388), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.mish', '"""\n See :func:`oneflow.mish`\n """'], {}), '(oneflow.Tensor.mish, """\n See :func:`oneflow.mish`\n """)\n', (21325, 21388), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((21401, 21503), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.mul', '"""Tensor.mul(value) -> Tensor\n See :func:`oneflow.mul`\n """'], {}), '(oneflow.Tensor.mul,\n """Tensor.mul(value) -> Tensor\n See :func:`oneflow.mul`\n """)\n', (21411, 21503), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((21512, 21646), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.mul_', '"""Tensor.mul_(value) -> Tensor\n\n In-place version of :func:`oneflow.Tensor.mul`.\n """'], {}), '(oneflow.Tensor.mul_,\n """Tensor.mul_(value) -> Tensor\n\n In-place version of :func:`oneflow.Tensor.mul`.\n """\n )\n', (21522, 21646), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((21650, 21783), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.div_', '"""Tensor.div_(value) -> Tensor\n In-place version of :func:`oneflow.Tensor.div`.\n """'], {}), '(oneflow.Tensor.div_,\n """Tensor.div_(value) -> Tensor\n In-place version of :func:`oneflow.Tensor.div`.\n """\n )\n', (21660, 21783), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((21787, 21920), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.sub_', '"""Tensor.sub_(value) -> Tensor\n In-place version of :func:`oneflow.Tensor.sub`.\n """'], {}), '(oneflow.Tensor.sub_,\n """Tensor.sub_(value) -> Tensor\n In-place version of :func:`oneflow.Tensor.sub`.\n """\n )\n', (21797, 21920), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((21924, 22009), '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', (21934, 22009), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((22018, 22121), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.nelement', '"""\n Tensor.nelement() → int\n\n Alias for numel()\n """'], {}), '(oneflow.Tensor.nelement,\n """\n Tensor.nelement() → int\n\n Alias for numel()\n """)\n', (22028, 22121), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((22130, 22227), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.floor_', '"""\n In-place version of :func:`oneflow.floor`\n\n """'], {}), '(oneflow.Tensor.floor_,\n """\n In-place version of :func:`oneflow.floor`\n\n """)\n', (22140, 22227), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((22237, 22478), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.normal_', '"""\n normal_(mean=0, std=1, *, generator=None) -> Tensor\n\n Fills :attr:`self` tensor with elements samples from the normal distribution parameterized by :attr:`mean` and :attr:`std`.\n """'], {}), '(oneflow.Tensor.normal_,\n """\n normal_(mean=0, std=1, *, generator=None) -> Tensor\n\n Fills :attr:`self` tensor with elements samples from the normal distribution parameterized by :attr:`mean` and :attr:`std`.\n """\n )\n', (22247, 22478), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((22482, 22765), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.numpy', '"""\n Tensor.numpy() → numpy.ndarray\n\n Returns self tensor as a NumPy ndarray. This tensor and the returned ndarray share the same underlying storage. Changes to\n self tensor will be reflected in the ndarray and vice versa.\n """'], {}), '(oneflow.Tensor.numpy,\n """\n Tensor.numpy() → numpy.ndarray\n\n Returns self tensor as a NumPy ndarray. This tensor and the returned ndarray share the same underlying storage. Changes to\n self tensor will be reflected in the ndarray and vice versa.\n """\n )\n', (22492, 22765), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((22769, 22840), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.pow', '"""\n See :func:`oneflow.pow`\n """'], {}), '(oneflow.Tensor.pow, """\n See :func:`oneflow.pow`\n """)\n', (22779, 22840), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((22853, 22926), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.relu', '"""\n See :func:`oneflow.relu`\n """'], {}), '(oneflow.Tensor.relu, """\n See :func:`oneflow.relu`\n """)\n', (22863, 22926), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((22939, 23012), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.roll', '"""\n See :func:`oneflow.roll`\n """'], {}), '(oneflow.Tensor.roll, """\n See :func:`oneflow.roll`\n """)\n', (22949, 23012), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((23025, 23100), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.round', '"""\n See :func:`oneflow.round`\n """'], {}), '(oneflow.Tensor.round, """\n See :func:`oneflow.round`\n """)\n', (23035, 23100), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((23113, 23202), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.reciprocal', '"""\n See :func:`oneflow.reciprocal`\n """'], {}), '(oneflow.Tensor.reciprocal,\n """\n See :func:`oneflow.reciprocal`\n """)\n', (23123, 23202), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((23211, 23282), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.add', '"""\n See :func:`oneflow.add`\n """'], {}), '(oneflow.Tensor.add, """\n See :func:`oneflow.add`\n """)\n', (23221, 23282), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((23295, 23370), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.addmm', '"""\n See :func:`oneflow.addmm`\n """'], {}), '(oneflow.Tensor.addmm, """\n See :func:`oneflow.addmm`\n """)\n', (23305, 23370), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((23383, 23483), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.add_', '"""\n In-place version of :func:`oneflow.Tensor.add`.\n """'], {}), '(oneflow.Tensor.add_,\n """\n In-place version of :func:`oneflow.Tensor.add`.\n """)\n', (23393, 23483), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((23492, 23565), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.asin', '"""\n See :func:`oneflow.asin`\n """'], {}), '(oneflow.Tensor.asin, """\n See :func:`oneflow.asin`\n """)\n', (23502, 23565), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((23578, 23655), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.arcsin', '"""\n See :func:`oneflow.arcsin`\n """'], {}), '(oneflow.Tensor.arcsin, """\n See :func:`oneflow.arcsin`\n """)\n', (23588, 23655), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((23668, 23747), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.arcsinh', '"""\n See :func:`oneflow.arcsinh`\n """'], {}), '(oneflow.Tensor.arcsinh, """\n See :func:`oneflow.arcsinh`\n """)\n', (23678, 23747), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((23760, 23856), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.sin', '"""\n sin() -> Tensor\n\n See :func:`oneflow.sin`\n """'], {}), '(oneflow.Tensor.sin,\n """\n sin() -> Tensor\n\n See :func:`oneflow.sin`\n """)\n', (23770, 23856), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((23865, 23936), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.cos', '"""\n See :func:`oneflow.cos`\n """'], {}), '(oneflow.Tensor.cos, """\n See :func:`oneflow.cos`\n """)\n', (23875, 23936), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((23949, 24034), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.diagonal', '"""\n See :func:`oneflow.diagonal`\n """'], {}), '(oneflow.Tensor.diagonal,\n """\n See :func:`oneflow.diagonal`\n """)\n', (23959, 24034), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((24043, 24114), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.log', '"""\n See :func:`oneflow.log`\n """'], {}), '(oneflow.Tensor.log, """\n See :func:`oneflow.log`\n """)\n', (24053, 24114), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((24127, 24206), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.ndim', '"""\n See :func:`oneflow.Tensor.dim`\n """'], {}), '(oneflow.Tensor.ndim, """\n See :func:`oneflow.Tensor.dim`\n """)\n', (24137, 24206), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((24219, 24294), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.rsqrt', '"""\n See :func:`oneflow.rsqrt`\n """'], {}), '(oneflow.Tensor.rsqrt, """\n See :func:`oneflow.rsqrt`\n """)\n', (24229, 24294), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((24307, 24380), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.cosh', '"""\n See :func:`oneflow.cosh`\n """'], {}), '(oneflow.Tensor.cosh, """\n See :func:`oneflow.cosh`\n """)\n', (24317, 24380), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((24393, 24466), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.atan', '"""\n See :func:`oneflow.atan`\n """'], {}), '(oneflow.Tensor.atan, """\n See :func:`oneflow.atan`\n """)\n', (24403, 24466), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((24479, 24556), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.arctan', '"""\n See :func:`oneflow.arctan`\n """'], {}), '(oneflow.Tensor.arctan, """\n See :func:`oneflow.arctan`\n """)\n', (24489, 24556), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((24569, 24642), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.selu', '"""\n See :func:`oneflow.selu`\n """'], {}), '(oneflow.Tensor.selu, """\n See :func:`oneflow.selu`\n """)\n', (24579, 24642), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((24655, 24734), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.sigmoid', '"""\n See :func:`oneflow.sigmoid`\n """'], {}), '(oneflow.Tensor.sigmoid, """\n See :func:`oneflow.sigmoid`\n """)\n', (24665, 24734), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((24747, 24820), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.sign', '"""\n See :func:`oneflow.sign`\n """'], {}), '(oneflow.Tensor.sign, """\n See :func:`oneflow.sign`\n """)\n', (24757, 24820), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((24833, 24906), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.silu', '"""\n See :func:`oneflow.silu`\n """'], {}), '(oneflow.Tensor.silu, """\n See :func:`oneflow.silu`\n """)\n', (24843, 24906), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((24919, 24992), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.sinh', '"""\n See :func:`oneflow.sinh`\n """'], {}), '(oneflow.Tensor.sinh, """\n See :func:`oneflow.sinh`\n """)\n', (24929, 24992), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((25005, 25390), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.size', '"""\n The interface is consistent with PyTorch.\n\n Returns the size of the self tensor. If dim is not specified, the returned value is a oneflow.Size, a subclass of tuple. If dim is specified, returns an int holding the size of that dimension.\n\n Args:\n idx (int, optional): The dimension for which to retrieve the size.\n\n\n """'], {}), '(oneflow.Tensor.size,\n """\n The interface is consistent with PyTorch.\n\n Returns the size of the self tensor. If dim is not specified, the returned value is a oneflow.Size, a subclass of tuple. If dim is specified, returns an int holding the size of that dimension.\n\n Args:\n idx (int, optional): The dimension for which to retrieve the size.\n\n\n """\n )\n', (25015, 25390), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((25394, 25473), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.softmax', '"""\n See :func:`oneflow.softmax`\n """'], {}), '(oneflow.Tensor.softmax, """\n See :func:`oneflow.softmax`\n """)\n', (25404, 25473), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((25486, 25571), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.softplus', '"""\n See :func:`oneflow.softplus`\n """'], {}), '(oneflow.Tensor.softplus,\n """\n See :func:`oneflow.softplus`\n """)\n', (25496, 25571), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((25580, 25665), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.softsign', '"""\n See :func:`oneflow.softsign`\n """'], {}), '(oneflow.Tensor.softsign,\n """\n See :func:`oneflow.softsign`\n """)\n', (25590, 25665), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((25674, 25745), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.tan', '"""\n See :func:`oneflow.tan`\n """'], {}), '(oneflow.Tensor.tan, """\n See :func:`oneflow.tan`\n """)\n', (25684, 25745), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((25758, 25831), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.tanh', '"""\n See :func:`oneflow.tanh`\n """'], {}), '(oneflow.Tensor.tanh, """\n See :func:`oneflow.tanh`\n """)\n', (25768, 25831), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((25844, 25917), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.tril', '"""\n See :func:`oneflow.tril`\n """'], {}), '(oneflow.Tensor.tril, """\n See :func:`oneflow.tril`\n """)\n', (25854, 25917), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((25930, 26003), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.triu', '"""\n See :func:`oneflow.triu`\n """'], {}), '(oneflow.Tensor.triu, """\n See :func:`oneflow.triu`\n """)\n', (25940, 26003), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((26016, 26243), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.uniform_', '"""\n Tensor.uniform_(from=0, to=1) → Tensor\n\n Fills self tensor with numbers sampled from the continuous uniform distribution:\n\n .. math::\n P(x)=1/(to-from)\n\n """'], {}), '(oneflow.Tensor.uniform_,\n """\n Tensor.uniform_(from=0, to=1) → Tensor\n\n Fills self tensor with numbers sampled from the continuous uniform distribution:\n\n .. math::\n P(x)=1/(to-from)\n\n """\n )\n', (26026, 26243), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((26247, 26847), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.copy_', '"""\n The interface is consistent with PyTorch.\n\n Tensor.copy_(src, non_blocking=False) → Tensor\n\n Copies the elements from src into self tensor and returns self.\n\n The src tensor must be broadcastable with the self tensor. It may be of a different data type or reside on a different device.\n\n Args:\n\n src (Tensor): the source tensor to copy from\n\n non_blocking (bool): if True and this copy is between CPU and GPU, the copy may occur asynchronously with respect to the host. For other cases, this argument has no effect.\n """'], {}), '(oneflow.Tensor.copy_,\n """\n The interface is consistent with PyTorch.\n\n Tensor.copy_(src, non_blocking=False) → Tensor\n\n Copies the elements from src into self tensor and returns self.\n\n The src tensor must be broadcastable with the self tensor. It may be of a different data type or reside on a different device.\n\n Args:\n\n src (Tensor): the source tensor to copy from\n\n non_blocking (bool): if True and this copy is between CPU and GPU, the copy may occur asynchronously with respect to the host. For other cases, this argument has no effect.\n """\n )\n', (26257, 26847), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((26851, 27895), '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', (26861, 27895), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((27899, 28035), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.gather', '"""\n oneflow.Tensor.gather(dim, index)\xa0->\xa0Tensor\n\n See :func:`oneflow.gather`\n\n """'], {}), '(oneflow.Tensor.gather,\n """\n oneflow.Tensor.gather(dim, index)\xa0->\xa0Tensor\n\n See :func:`oneflow.gather`\n\n """\n )\n', (27909, 28035), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((28039, 28115), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.clamp', '"""\n See :func:`oneflow.clamp`.\n """'], {}), '(oneflow.Tensor.clamp, """\n See :func:`oneflow.clamp`.\n """)\n', (28049, 28115), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((28128, 28231), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.clamp_', '"""\n Inplace version of :func:`oneflow.Tensor.clamp`.\n """'], {}), '(oneflow.Tensor.clamp_,\n """\n Inplace version of :func:`oneflow.Tensor.clamp`.\n """)\n', (28138, 28231), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((28240, 28332), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.clip', '"""\n Alias for :func:`oneflow.Tensor.clamp`.\n """'], {}), '(oneflow.Tensor.clip,\n """\n Alias for :func:`oneflow.Tensor.clamp`.\n """)\n', (28250, 28332), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((28341, 28435), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.clip_', '"""\n Alias for :func:`oneflow.Tensor.clamp_`.\n """'], {}), '(oneflow.Tensor.clip_,\n """\n Alias for :func:`oneflow.Tensor.clamp_`.\n """)\n', (28351, 28435), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((28444, 28929), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.cpu', '"""Returns a copy of this object in CPU memory.\n If this object is already in CPU memory and on the correct device, then no copy is performed and the original object is returned.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n\n >>> input = flow.tensor([1, 2, 3, 4, 5], device=flow.device("cuda"))\n >>> output = input.cpu()\n >>> output.device\n device(type=\'cpu\', index=0)\n """'], {}), '(oneflow.Tensor.cpu,\n """Returns a copy of this object in CPU memory.\n If this object is already in CPU memory and on the correct device, then no copy is performed and the original object is returned.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n\n >>> input = flow.tensor([1, 2, 3, 4, 5], device=flow.device("cuda"))\n >>> output = input.cpu()\n >>> output.device\n device(type=\'cpu\', index=0)\n """\n )\n', (28454, 28929), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((28934, 29503), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.cuda', '"""Returns a copy of this object in CUDA memory.\n If this object is already in CUDA memory and on the correct device, then no copy is performed and the original object is returned.\n\n Args:\n device (flow.device): The destination GPU device. Defaults to the current CUDA device.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n\n >>> input = flow.Tensor([1, 2, 3, 4, 5])\n >>> output = input.cuda()\n >>> output.device\n device(type=\'cuda\', index=0)\n """'], {}), '(oneflow.Tensor.cuda,\n """Returns a copy of this object in CUDA memory.\n If this object is already in CUDA memory and on the correct device, then no copy is performed and the original object is returned.\n\n Args:\n device (flow.device): The destination GPU device. Defaults to the current CUDA device.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n\n >>> input = flow.Tensor([1, 2, 3, 4, 5])\n >>> output = input.cuda()\n >>> output.device\n device(type=\'cuda\', index=0)\n """\n )\n', (28944, 29503), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((29509, 29631), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.repeat', '"""\n Tensor.repeat(*size) -> Tensor\n\n See :func:`oneflow.repeat`\n """'], {}), '(oneflow.Tensor.repeat,\n """\n Tensor.repeat(*size) -> Tensor\n\n See :func:`oneflow.repeat`\n """\n )\n', (29519, 29631), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((29635, 29731), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.t', '"""\n Tensor.t() → Tensor\n\n See :func:`oneflow.t`\n """'], {}), '(oneflow.Tensor.t,\n """\n Tensor.t() → Tensor\n\n See :func:`oneflow.t`\n """)\n', (29645, 29731), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((29740, 29851), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.tile', '"""\n Tensor.tile(*dims) -> Tensor\n\n See :func:`oneflow.tile`\n """'], {}), '(oneflow.Tensor.tile,\n """\n Tensor.tile(*dims) -> Tensor\n\n See :func:`oneflow.tile`\n """)\n', (29750, 29851), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((29860, 30061), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.T', '"""\n Is this Tensor with its dimensions reversed.\n\n If `n` is the number of dimensions in `x`, `x.T` is equivalent to `x.permute(n-1, n-2, ..., 0)`.\n """'], {}), '(oneflow.Tensor.T,\n """\n Is this Tensor with its dimensions reversed.\n\n If `n` is the number of dimensions in `x`, `x.T` is equivalent to `x.permute(n-1, n-2, ..., 0)`.\n """\n )\n', (29870, 30061), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((30065, 30182), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.fmod', '"""\n Tensor.fmod(other) -> Tensor\n\n See :func:`oneflow.fmod`\n\n """'], {}), '(oneflow.Tensor.fmod,\n """\n Tensor.fmod(other) -> Tensor\n\n See :func:`oneflow.fmod`\n\n """\n )\n', (30075, 30182), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((30186, 30312), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.logical_and', '"""\n logical_and() -> Tensor\n\n See :func:`oneflow.logical_and`\n\n """'], {}), '(oneflow.Tensor.logical_and,\n """\n logical_and() -> Tensor\n\n See :func:`oneflow.logical_and`\n\n """\n )\n', (30196, 30312), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((30316, 30440), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.logical_or', '"""\n\n logical_or() -> Tensor\n\n See :func:`oneflow.logical_or`\n\n """'], {}), '(oneflow.Tensor.logical_or,\n """\n\n logical_or() -> Tensor\n\n See :func:`oneflow.logical_or`\n\n """\n )\n', (30326, 30440), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((30444, 30570), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.logical_xor', '"""\n logical_xor() -> Tensor\n\n See :func:`oneflow.logical_xor`\n\n """'], {}), '(oneflow.Tensor.logical_xor,\n """\n logical_xor() -> Tensor\n\n See :func:`oneflow.logical_xor`\n\n """\n )\n', (30454, 30570), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((30574, 30665), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.masked_fill', '"""\n See :func:`oneflow.masked_fill`\n """'], {}), '(oneflow.Tensor.masked_fill,\n """\n See :func:`oneflow.masked_fill`\n """)\n', (30584, 30665), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((30674, 30769), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.masked_select', '"""\n See :func:`oneflow.masked_select`\n """'], {}), '(oneflow.Tensor.masked_select,\n """\n See :func:`oneflow.masked_select`\n """)\n', (30684, 30769), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((30778, 30849), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.sub', '"""\n See :func:`oneflow.sub`\n """'], {}), '(oneflow.Tensor.sub, """\n See :func:`oneflow.sub`\n """)\n', (30788, 30849), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((30862, 30934), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.div', '"""\n See :func:`oneflow.div`\n\n """'], {}), '(oneflow.Tensor.div, """\n See :func:`oneflow.div`\n\n """)\n', (30872, 30934), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((30947, 31020), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.ceil', '"""\n See :func:`oneflow.ceil`\n """'], {}), '(oneflow.Tensor.ceil, """\n See :func:`oneflow.ceil`\n """)\n', (30957, 31020), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((31033, 31108), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.expm1', '"""\n See :func:`oneflow.expm1`\n """'], {}), '(oneflow.Tensor.expm1, """\n See :func:`oneflow.expm1`\n """)\n', (31043, 31108), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((31121, 31194), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.topk', '"""\n See :func:`oneflow.topk`\n """'], {}), '(oneflow.Tensor.topk, """\n See :func:`oneflow.topk`\n """)\n', (31131, 31194), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((31207, 31278), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.nms', '"""\n See :func:`oneflow.nms`\n """'], {}), '(oneflow.Tensor.nms, """\n See :func:`oneflow.nms`\n """)\n', (31217, 31278), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((31291, 31425), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.nonzero', '"""\n nonzero(input, as_tuple=False) -> Tensor\n\n See :func:`oneflow.nonzero`\n """'], {}), '(oneflow.Tensor.nonzero,\n """\n nonzero(input, as_tuple=False) -> Tensor\n\n See :func:`oneflow.nonzero`\n """\n )\n', (31301, 31425), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((31429, 31546), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.max', '"""\n input.max(dim, index) -> Tensor\n\n See :func:`oneflow.max`\n """'], {}), '(oneflow.Tensor.max,\n """\n input.max(dim, index) -> Tensor\n\n See :func:`oneflow.max`\n """\n )\n', (31439, 31546), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((31550, 31667), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.min', '"""\n input.min(dim, index) -> Tensor\n\n See :func:`oneflow.min`\n """'], {}), '(oneflow.Tensor.min,\n """\n input.min(dim, index) -> Tensor\n\n See :func:`oneflow.min`\n """\n )\n', (31560, 31667), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((31671, 31788), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.sum', '"""\n input.sum(dim, index) -> Tensor\n\n See :func:`oneflow.sum`\n """'], {}), '(oneflow.Tensor.sum,\n """\n input.sum(dim, index) -> Tensor\n\n See :func:`oneflow.sum`\n """\n )\n', (31681, 31788), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((31792, 31912), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.mean', '"""\n input.mean(dim, index) -> Tensor\n\n See :func:`oneflow.mean`\n """'], {}), '(oneflow.Tensor.mean,\n """\n input.mean(dim, index) -> Tensor\n\n See :func:`oneflow.mean`\n """\n )\n', (31802, 31912), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((31916, 32036), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.prod', '"""\n input.prod(dim, index) -> Tensor\n\n See :func:`oneflow.prod`\n """'], {}), '(oneflow.Tensor.prod,\n """\n input.prod(dim, index) -> Tensor\n\n See :func:`oneflow.prod`\n """\n )\n', (31926, 32036), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((32040, 32119), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.reshape', '"""\n See :func:`oneflow.reshape`\n """'], {}), '(oneflow.Tensor.reshape, """\n See :func:`oneflow.reshape`\n """)\n', (32050, 32119), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((32132, 33899), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.view', '"""\n The interface is consistent with PyTorch.\n The documentation is referenced from: https://pytorch.org/docs/stable/generated/torch.Tensor.view.html\n\n Returns a new tensor with the same data as the :attr:`self` tensor but of a\n different :attr:`shape`.\n\n The returned tensor shares the same data and must have the same number\n of elements, but may have a different size. For a tensor to be viewed, the new\n view size must be compatible with its original size and stride, i.e., each new\n view dimension must either be a subspace of an original dimension, or only span\n across original dimensions :math:`d, d+1, \\\\dots, d+k` that satisfy the following\n contiguity-like condition that :math:`\\\\forall i = d, \\\\dots, d+k-1`,\n\n .. math::\n\n \\\\text{stride}[i] = \\\\text{stride}[i+1] \\\\times \\\\text{size}[i+1]\n\n Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape`\n without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a\n :meth:`view` can be performed, it is advisable to use :meth:`reshape`, which\n returns a view if the shapes are compatible, and copies (equivalent to calling\n :meth:`contiguous`) otherwise.\n\n Args:\n input: A Tensor.\n *shape: flow.Size or int...\n Returns:\n A Tensor has the same type as `input`.\n\n For example:\n\n .. code-block:: python\n\n >>> import numpy as np\n >>> import oneflow as flow\n\n >>> x = np.array(\n ... [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]\n ... ).astype(np.float32)\n >>> input = flow.Tensor(x)\n\n >>> y = input.view(2, 2, 2, -1).numpy().shape\n >>> y\n (2, 2, 2, 2)\n """'], {}), '(oneflow.Tensor.view,\n """\n The interface is consistent with PyTorch.\n The documentation is referenced from: https://pytorch.org/docs/stable/generated/torch.Tensor.view.html\n\n Returns a new tensor with the same data as the :attr:`self` tensor but of a\n different :attr:`shape`.\n\n The returned tensor shares the same data and must have the same number\n of elements, but may have a different size. For a tensor to be viewed, the new\n view size must be compatible with its original size and stride, i.e., each new\n view dimension must either be a subspace of an original dimension, or only span\n across original dimensions :math:`d, d+1, \\\\dots, d+k` that satisfy the following\n contiguity-like condition that :math:`\\\\forall i = d, \\\\dots, d+k-1`,\n\n .. math::\n\n \\\\text{stride}[i] = \\\\text{stride}[i+1] \\\\times \\\\text{size}[i+1]\n\n Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape`\n without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a\n :meth:`view` can be performed, it is advisable to use :meth:`reshape`, which\n returns a view if the shapes are compatible, and copies (equivalent to calling\n :meth:`contiguous`) otherwise.\n\n Args:\n input: A Tensor.\n *shape: flow.Size or int...\n Returns:\n A Tensor has the same type as `input`.\n\n For example:\n\n .. code-block:: python\n\n >>> import numpy as np\n >>> import oneflow as flow\n\n >>> x = np.array(\n ... [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]\n ... ).astype(np.float32)\n >>> input = flow.Tensor(x)\n\n >>> y = input.view(2, 2, 2, -1).numpy().shape\n >>> y\n (2, 2, 2, 2)\n """\n )\n', (32142, 33899), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((33903, 33976), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.sort', '"""\n See :func:`oneflow.sort`\n """'], {}), '(oneflow.Tensor.sort, """\n See :func:`oneflow.sort`\n """)\n', (33913, 33976), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((33989, 34649), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.type_as', '"""Returns this tensor cast to the type of the given tensor.\n This is a no-op if the tensor is already of the correct type.\n\n Args:\n input (Tensor): the input tensor.\n target (Tensor): the tensor which has the desired type.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n\n >>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.float32)\n >>> target = flow.tensor(np.random.randn(4, 5, 6), dtype = flow.int32)\n >>> input = input.type_as(target)\n >>> input.dtype\n oneflow.int32\n """'], {}), '(oneflow.Tensor.type_as,\n """Returns this tensor cast to the type of the given tensor.\n This is a no-op if the tensor is already of the correct type.\n\n Args:\n input (Tensor): the input tensor.\n target (Tensor): the tensor which has the desired type.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n\n >>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.float32)\n >>> target = flow.tensor(np.random.randn(4, 5, 6), dtype = flow.int32)\n >>> input = input.type_as(target)\n >>> input.dtype\n oneflow.int32\n """\n )\n', (33999, 34649), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((34654, 35096), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.int', '"""`Tensor.int()` is equivalent to `Tensor.to(flow.int32)`. See to().\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n\n >>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.float32)\n >>> input = input.int()\n >>> input.dtype\n oneflow.int32\n """'], {}), '(oneflow.Tensor.int,\n """`Tensor.int()` is equivalent to `Tensor.to(flow.int32)`. See to().\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n\n >>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.float32)\n >>> input = input.int()\n >>> input.dtype\n oneflow.int32\n """\n )\n', (34664, 35096), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((35101, 35546), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.long', '"""`Tensor.long()` is equivalent to `Tensor.to(flow.int64)`. See to().\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n\n >>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.float32)\n >>> input = input.long()\n >>> input.dtype\n oneflow.int64\n """'], {}), '(oneflow.Tensor.long,\n """`Tensor.long()` is equivalent to `Tensor.to(flow.int64)`. See to().\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n\n >>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.float32)\n >>> input = input.long()\n >>> input.dtype\n oneflow.int64\n """\n )\n', (35111, 35546), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((35551, 35999), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.float', '"""`Tensor.float()` is equivalent to `Tensor.to(flow.float32)`. See to().\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n\n >>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.int)\n >>> input = input.float()\n >>> input.dtype\n oneflow.float32\n """'], {}), '(oneflow.Tensor.float,\n """`Tensor.float()` is equivalent to `Tensor.to(flow.float32)`. See to().\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n\n >>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.int)\n >>> input = input.float()\n >>> input.dtype\n oneflow.float32\n """\n )\n', (35561, 35999), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((36004, 36455), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.double', '"""`Tensor.double()` is equivalent to `Tensor.to(flow.float64)`. See to().\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n\n >>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.int)\n >>> input = input.double()\n >>> input.dtype\n oneflow.float64\n """'], {}), '(oneflow.Tensor.double,\n """`Tensor.double()` is equivalent to `Tensor.to(flow.float64)`. See to().\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> import numpy as np\n\n >>> input = flow.tensor(np.random.randn(1, 2, 3), dtype=flow.int)\n >>> input = input.double()\n >>> input.dtype\n oneflow.float64\n """\n )\n', (36014, 36455), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((36460, 36563), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.is_floating_point', '"""\n See :func:`oneflow.is_floating_point`\n """'], {}), '(oneflow.Tensor.is_floating_point,\n """\n See :func:`oneflow.is_floating_point`\n """)\n', (36470, 36563), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((36572, 37014), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.item', '"""Returns the value of this tensor as a standard Python number. This only works for tensors with one element.\n For other cases, see tolist().\n\n This operation is not differentiable.\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> x = flow.tensor([1.0])\n >>> x.item()\n 1.0\n """'], {}), '(oneflow.Tensor.item,\n """Returns the value of this tensor as a standard Python number. This only works for tensors with one element.\n For other cases, see tolist().\n\n This operation is not differentiable.\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> x = flow.tensor([1.0])\n >>> x.item()\n 1.0\n """\n )\n', (36582, 37014), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((37019, 37544), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.tolist', '"""Returns the tensor as a (nested) list. For scalars, a standard Python number is returned,\n just like with `item()`. Tensors are automatically moved to the CPU first if necessary.\n\n This operation is not differentiable.\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> input = flow.tensor([[1,2,3], [4,5,6]])\n >>> input.tolist()\n [[1, 2, 3], [4, 5, 6]]\n """'], {}), '(oneflow.Tensor.tolist,\n """Returns the tensor as a (nested) list. For scalars, a standard Python number is returned,\n just like with `item()`. Tensors are automatically moved to the CPU first if necessary.\n\n This operation is not differentiable.\n\n Args:\n input (Tensor): the input tensor.\n\n For example:\n\n .. code-block:: python\n\n >>> import oneflow as flow\n >>> input = flow.tensor([[1,2,3], [4,5,6]])\n >>> input.tolist()\n [[1, 2, 3], [4, 5, 6]]\n """\n )\n', (37029, 37544), False, 'from oneflow.framework.docstr.utils import add_docstr\n'), ((37549, 37624), 'oneflow.framework.docstr.utils.add_docstr', 'add_docstr', (['oneflow.Tensor.where', '"""\n See :func:`oneflow.where`\n """'], {}), '(oneflow.Tensor.where, """\n See :func:`oneflow.where`\n """)\n', (37559, 37624), 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
import oneflow._oneflow_internal
import oneflow.eager.gradient_util as gradient_util
import oneflow.framework.compile_context as compile_ctx
import oneflow.framework.hob as hob
import oneflow.support.enable_if as enable_if
blob_register = oneflow._oneflow_internal.GetDefaultBlobRegister()
def Forward(op_conf, scope_symbol=None):
if scope_symbol is None:
scope_symbol = oneflow.current_scope()
func = enable_if.unique([LazyInfer, EagerForward])
return func(compile_ctx.CurJobAddOp, op_conf, scope_symbol)
def OpKernelForward(op_conf, opkernel_object):
func = enable_if.unique([LazyOpKernelInfer, EagerOpKernelForward])
return func(compile_ctx.CurJobAddOp, op_conf, opkernel_object)
def ConsistentForward(op_conf, scope_symbol=None):
if scope_symbol is None:
scope_symbol = oneflow.current_scope()
func = enable_if.unique([LazyInfer, EagerForward])
return func(compile_ctx.CurJobAddConsistentOp, op_conf, scope_symbol)
def OpKernelConsistentForward(op_conf, opkernel_object):
func = enable_if.unique([LazyOpKernelInfer, EagerOpKernelForward])
return func(compile_ctx.CurJobAddConsistentOp, op_conf, opkernel_object)
@enable_if.condition(hob.in_global_mode & ~hob.eager_execution_enabled)
def LazyInfer(add_and_infer, op_conf, scope_symbol=None):
return add_and_infer(op_conf, scope_symbol)
@enable_if.condition(hob.in_global_mode & ~hob.eager_execution_enabled)
def LazyOpKernelInfer(add_and_infer, op_conf, opkernel_object):
return add_and_infer(op_conf, opkernel_object.scope_symbol)
@enable_if.condition(hob.in_global_mode & hob.eager_execution_enabled)
def EagerForward(add_and_infer, op_conf, scope_symbol=None):
op_attribute = add_and_infer(op_conf, scope_symbol)
parallel_conf = scope_symbol.device_parallel_desc_symbol.parallel_conf
import oneflow.eager.op_executor as op_executor
op_executor.Interpret(op_attribute, parallel_conf, blob_register)
bw_blob_register = gradient_util.GetDefaultBackwardBlobRegister()
gradient_util.TrySetBackwardUsedBlobObject(
op_attribute, blob_register, bw_blob_register
)
return op_attribute
@enable_if.condition(hob.in_global_mode & hob.eager_execution_enabled)
def EagerOpKernelForward(add_and_infer, op_conf, opkernel_object):
op_attribute = add_and_infer(op_conf, opkernel_object.scope_symbol)
import oneflow.eager.op_executor as op_executor
op_executor.OpKernelCall(opkernel_object, op_attribute, blob_register)
bw_blob_register = gradient_util.GetDefaultBackwardBlobRegister()
gradient_util.TrySetBackwardUsedBlobObject(
op_attribute, blob_register, bw_blob_register
)
return op_attribute
| [
"oneflow.support.enable_if.unique",
"oneflow.support.enable_if.condition",
"oneflow.eager.op_executor.Interpret",
"oneflow.eager.op_executor.OpKernelCall",
"oneflow.eager.gradient_util.GetDefaultBackwardBlobRegister",
"oneflow.current_scope",
"oneflow.eager.gradient_util.TrySetBackwardUsedBlobObject",
"oneflow._oneflow_internal.GetDefaultBlobRegister"
] | [((845, 895), 'oneflow._oneflow_internal.GetDefaultBlobRegister', 'oneflow._oneflow_internal.GetDefaultBlobRegister', ([], {}), '()\n', (893, 895), False, 'import oneflow\n'), ((1789, 1859), 'oneflow.support.enable_if.condition', 'enable_if.condition', (['(hob.in_global_mode & ~hob.eager_execution_enabled)'], {}), '(hob.in_global_mode & ~hob.eager_execution_enabled)\n', (1808, 1859), True, 'import oneflow.support.enable_if as enable_if\n'), ((1969, 2039), 'oneflow.support.enable_if.condition', 'enable_if.condition', (['(hob.in_global_mode & ~hob.eager_execution_enabled)'], {}), '(hob.in_global_mode & ~hob.eager_execution_enabled)\n', (1988, 2039), True, 'import oneflow.support.enable_if as enable_if\n'), ((2171, 2240), 'oneflow.support.enable_if.condition', 'enable_if.condition', (['(hob.in_global_mode & hob.eager_execution_enabled)'], {}), '(hob.in_global_mode & hob.eager_execution_enabled)\n', (2190, 2240), True, 'import oneflow.support.enable_if as enable_if\n'), ((2761, 2830), 'oneflow.support.enable_if.condition', 'enable_if.condition', (['(hob.in_global_mode & hob.eager_execution_enabled)'], {}), '(hob.in_global_mode & hob.eager_execution_enabled)\n', (2780, 2830), True, 'import oneflow.support.enable_if as enable_if\n'), ((1026, 1069), 'oneflow.support.enable_if.unique', 'enable_if.unique', (['[LazyInfer, EagerForward]'], {}), '([LazyInfer, EagerForward])\n', (1042, 1069), True, 'import oneflow.support.enable_if as enable_if\n'), ((1194, 1253), 'oneflow.support.enable_if.unique', 'enable_if.unique', (['[LazyOpKernelInfer, EagerOpKernelForward]'], {}), '([LazyOpKernelInfer, EagerOpKernelForward])\n', (1210, 1253), True, 'import oneflow.support.enable_if as enable_if\n'), ((1461, 1504), 'oneflow.support.enable_if.unique', 'enable_if.unique', (['[LazyInfer, EagerForward]'], {}), '([LazyInfer, EagerForward])\n', (1477, 1504), True, 'import oneflow.support.enable_if as enable_if\n'), ((1649, 1708), 'oneflow.support.enable_if.unique', 'enable_if.unique', (['[LazyOpKernelInfer, EagerOpKernelForward]'], {}), '([LazyOpKernelInfer, EagerOpKernelForward])\n', (1665, 1708), True, 'import oneflow.support.enable_if as enable_if\n'), ((2490, 2555), 'oneflow.eager.op_executor.Interpret', 'op_executor.Interpret', (['op_attribute', 'parallel_conf', 'blob_register'], {}), '(op_attribute, parallel_conf, blob_register)\n', (2511, 2555), True, 'import oneflow.eager.op_executor as op_executor\n'), ((2579, 2625), 'oneflow.eager.gradient_util.GetDefaultBackwardBlobRegister', 'gradient_util.GetDefaultBackwardBlobRegister', ([], {}), '()\n', (2623, 2625), True, 'import oneflow.eager.gradient_util as gradient_util\n'), ((2630, 2723), 'oneflow.eager.gradient_util.TrySetBackwardUsedBlobObject', 'gradient_util.TrySetBackwardUsedBlobObject', (['op_attribute', 'blob_register', 'bw_blob_register'], {}), '(op_attribute, blob_register,\n bw_blob_register)\n', (2672, 2723), True, 'import oneflow.eager.gradient_util as gradient_util\n'), ((3027, 3097), 'oneflow.eager.op_executor.OpKernelCall', 'op_executor.OpKernelCall', (['opkernel_object', 'op_attribute', 'blob_register'], {}), '(opkernel_object, op_attribute, blob_register)\n', (3051, 3097), True, 'import oneflow.eager.op_executor as op_executor\n'), ((3121, 3167), 'oneflow.eager.gradient_util.GetDefaultBackwardBlobRegister', 'gradient_util.GetDefaultBackwardBlobRegister', ([], {}), '()\n', (3165, 3167), True, 'import oneflow.eager.gradient_util as gradient_util\n'), ((3172, 3265), 'oneflow.eager.gradient_util.TrySetBackwardUsedBlobObject', 'gradient_util.TrySetBackwardUsedBlobObject', (['op_attribute', 'blob_register', 'bw_blob_register'], {}), '(op_attribute, blob_register,\n bw_blob_register)\n', (3214, 3265), True, 'import oneflow.eager.gradient_util as gradient_util\n'), ((991, 1014), 'oneflow.current_scope', 'oneflow.current_scope', ([], {}), '()\n', (1012, 1014), False, 'import oneflow\n'), ((1426, 1449), 'oneflow.current_scope', 'oneflow.current_scope', ([], {}), '()\n', (1447, 1449), False, 'import oneflow\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 oneflow
import oneflow.core.operator.op_conf_pb2 as op_conf_util
import oneflow.core.register.logical_blob_id_pb2 as logical_blob_id_util
import oneflow.python.framework.interpret_util as interpret_util
import oneflow.python.framework.id_util as id_util
import oneflow.python.framework.remote_blob as remote_blob_util
import oneflow.python.framework.hob as hob
import oneflow.python.lib.core.enable_if as enable_if
from oneflow.python.oneflow_export import oneflow_export
from typing import Union, Tuple, List, Optional, Sequence, Callable
import oneflow_api
@oneflow_export("advanced.distribute_clone")
def api_distribute_clone(
x: oneflow_api.BlobDesc, name: Optional[str] = None
) -> Tuple[oneflow_api.BlobDesc]:
func = enable_if.unique([distribute_clone])
return func(x, name=name)
@enable_if.condition(hob.in_global_mode)
def distribute_clone(x, name=None):
if name is None:
name = id_util.UniqueStr("DistributeClone_")
op_conf = op_conf_util.OperatorConf()
op_conf.name = name
setattr(op_conf.distribute_clone_conf, "in", x.unique_name)
parallel_size = oneflow.current_scope().device_parallel_desc_symbol.parallel_num
op_conf.distribute_clone_conf.out.extend(
["out_%d" % i for i in range(parallel_size)]
)
interpret_util.ConsistentForward(op_conf)
ret = []
for i in range(parallel_size):
out = "out_%d" % i
lbi = logical_blob_id_util.LogicalBlobId()
lbi.op_name = op_conf.name
lbi.blob_name = out
ret.append(remote_blob_util.RemoteBlob(lbi))
return tuple(ret)
@oneflow_export("advanced.distribute_add")
def api_distribute_add(
xs: Sequence[oneflow_api.BlobDesc], name: Optional[str] = None
) -> oneflow_api.BlobDesc:
func = enable_if.unique([distribute_add])
return func(xs, name=name)
@enable_if.condition(hob.in_global_mode)
def distribute_add(xs, name=None):
assert oneflow.current_scope().device_parallel_desc_symbol.parallel_num == len(xs)
if name is None:
name = id_util.UniqueStr("DistributeAdd_")
op_conf = op_conf_util.OperatorConf()
op_conf.name = name
getattr(op_conf.distribute_add_conf, "in").extend(
[_SoleConsistentLbn(x) for x in xs]
)
op_conf.distribute_add_conf.out = "out"
interpret_util.ConsistentForward(op_conf)
lbi = logical_blob_id_util.LogicalBlobId()
lbi.op_name = op_conf.name
lbi.blob_name = "out"
return remote_blob_util.RemoteBlob(lbi)
@oneflow_export("advanced.distribute_split")
def api_distribute_split(
x: oneflow_api.BlobDesc, axis: int = 0, name: Optional[str] = None
) -> Tuple[oneflow_api.BlobDesc]:
func = enable_if.unique([distribute_split])
return func(x, axis=axis, name=name)
@enable_if.condition(hob.in_global_mode)
def distribute_split(x, axis=0, name=None):
if name is None:
name = id_util.UniqueStr("DistributeSplit_")
op_conf = op_conf_util.OperatorConf()
op_conf.name = name
setattr(op_conf.distribute_split_conf, "in", x.unique_name)
op_conf.distribute_split_conf.axis = axis
parallel_size = oneflow.current_scope().device_parallel_desc_symbol.parallel_num
op_conf.distribute_split_conf.out.extend(
["out_%d" % i for i in range(parallel_size)]
)
interpret_util.ConsistentForward(op_conf)
ret = []
for i in range(parallel_size):
out = "out_%d" % i
lbi = logical_blob_id_util.LogicalBlobId()
lbi.op_name = op_conf.name
lbi.blob_name = out
ret.append(remote_blob_util.RemoteBlob(lbi))
return tuple(ret)
@oneflow_export("advanced.distribute_concat")
def api_distribute_concat(
xs: Sequence[oneflow_api.BlobDesc], axis: int = 0, name: Optional[str] = None
) -> oneflow_api.BlobDesc:
func = enable_if.unique([distribute_concat])
return func(xs, axis=axis, name=name)
@enable_if.condition(hob.in_global_mode)
def distribute_concat(xs, axis=0, name=None):
assert oneflow.current_scope().device_parallel_desc_symbol.parallel_num == len(xs)
if name is None:
name = id_util.UniqueStr("DistributeConcat_")
op_conf = op_conf_util.OperatorConf()
op_conf.name = name
getattr(op_conf.distribute_concat_conf, "in").extend(
[_SoleConsistentLbn(x) for x in xs]
)
op_conf.distribute_concat_conf.axis = axis
op_conf.distribute_concat_conf.out = "out"
interpret_util.ConsistentForward(op_conf)
lbi = logical_blob_id_util.LogicalBlobId()
lbi.op_name = op_conf.name
lbi.blob_name = "out"
return remote_blob_util.RemoteBlob(lbi)
@oneflow_export("advanced.distribute_map")
def api_distribute_map(
xs: Union[Sequence[oneflow_api.BlobDesc], oneflow_api.BlobDesc],
f: Callable[[oneflow_api.BlobDesc, oneflow_api.BlobDesc], oneflow_api.BlobDesc],
axis: int = 0,
) -> Tuple[oneflow_api.BlobDesc]:
func = enable_if.unqiue([distribute_map])
return func(xs, f, axis=axis)
@enable_if.condition(hob.in_global_mode)
def distribute_map(xs, f, axis=0):
_AssertInputOrOutput(xs)
if isinstance(xs, (list, tuple)) == False:
xs = [xs]
splitted_xs = [oneflow.advanced.distribute_split(x, axis=axis) for x in xs]
results = [_UnderSingleDevicePlacementScope(f, *x) for x in zip(*splitted_xs)]
output_is_not_container = all(
[isinstance(x, oneflow_api.ConsistentBlob) for x in results]
)
results = [_TryWrapTuple(x) for x in results]
result = [oneflow.advanced.distribute_concat(x, axis=axis) for x in zip(*results)]
if output_is_not_container:
return result[0]
return tuple(result)
@oneflow_export("cast_to_current_logical_view")
def cast_to_current_logical_view(x: oneflow_api.BlobDesc,) -> oneflow_api.BlobDesc:
if (
isinstance(x, oneflow_api.ConsistentBlob)
and oneflow.scope.mirrored_view_enabled()
) or (
isinstance(x, oneflow_api.MirroredBlob)
and oneflow.scope.consistent_view_enabled()
):
x = oneflow.identity(x)
return x
def _SoleConsistentLbn(blob):
assert blob.parallel_size == 1
if isinstance(blob, oneflow_api.ConsistentBlob):
return blob.unique_name
if isinstance(blob, oneflow_api.MirroredBlob):
return blob.sub_consistent_blob_list[0].unique_name
raise NotImplementedError
def _AssertInputOrOutput(xs):
assert isinstance(xs, (list, tuple, oneflow_api.ConsistentBlob))
if isinstance(xs, (list, tuple)):
assert len(xs) > 0
assert all([isinstance(x, oneflow_api.ConsistentBlob) for x in xs])
def _TryWrapTuple(ys):
_AssertInputOrOutput(ys)
if isinstance(ys, (list, tuple)) == False:
ys = (ys,)
return ys
def _UnderSingleDevicePlacementScope(f, *args):
parallel_desc_symbol = oneflow.current_scope().device_parallel_desc_symbol
for machine_id, device_id in _EachMachineIdAndDeviceId(parallel_desc_symbol):
mch_dev_str = "@%d:%d" % (machine_id, device_id)
with oneflow.scope.placement(parallel_desc_symbol.device_tag, mch_dev_str):
return f(*args)
def _EachMachineIdAndDeviceId(parallel_desc_symbol):
for (
machine_id,
device_id_list,
) in parallel_desc_symbol.machine_id2device_id_list.items():
for device_id in device_id_list:
yield machine_id, device_id
| [
"oneflow.advanced.distribute_split",
"oneflow.scope.consistent_view_enabled",
"oneflow.scope.placement",
"oneflow.core.operator.op_conf_pb2.OperatorConf",
"oneflow.python.framework.remote_blob.RemoteBlob",
"oneflow.python.lib.core.enable_if.unqiue",
"oneflow.python.lib.core.enable_if.condition",
"oneflow.python.lib.core.enable_if.unique",
"oneflow.advanced.distribute_concat",
"oneflow.core.register.logical_blob_id_pb2.LogicalBlobId",
"oneflow.identity",
"oneflow.current_scope",
"oneflow.python.framework.id_util.UniqueStr",
"oneflow.python.framework.interpret_util.ConsistentForward",
"oneflow.scope.mirrored_view_enabled",
"oneflow.python.oneflow_export.oneflow_export"
] | [((1199, 1242), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""advanced.distribute_clone"""'], {}), "('advanced.distribute_clone')\n", (1213, 1242), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((1440, 1479), 'oneflow.python.lib.core.enable_if.condition', 'enable_if.condition', (['hob.in_global_mode'], {}), '(hob.in_global_mode)\n', (1459, 1479), True, 'import oneflow.python.lib.core.enable_if as enable_if\n'), ((2223, 2264), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""advanced.distribute_add"""'], {}), "('advanced.distribute_add')\n", (2237, 2264), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((2463, 2502), 'oneflow.python.lib.core.enable_if.condition', 'enable_if.condition', (['hob.in_global_mode'], {}), '(hob.in_global_mode)\n', (2482, 2502), True, 'import oneflow.python.lib.core.enable_if as enable_if\n'), ((3109, 3152), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""advanced.distribute_split"""'], {}), "('advanced.distribute_split')\n", (3123, 3152), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((3376, 3415), 'oneflow.python.lib.core.enable_if.condition', 'enable_if.condition', (['hob.in_global_mode'], {}), '(hob.in_global_mode)\n', (3395, 3415), True, 'import oneflow.python.lib.core.enable_if as enable_if\n'), ((4213, 4257), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""advanced.distribute_concat"""'], {}), "('advanced.distribute_concat')\n", (4227, 4257), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((4488, 4527), 'oneflow.python.lib.core.enable_if.condition', 'enable_if.condition', (['hob.in_global_mode'], {}), '(hob.in_global_mode)\n', (4507, 4527), True, 'import oneflow.python.lib.core.enable_if as enable_if\n'), ((5201, 5242), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""advanced.distribute_map"""'], {}), "('advanced.distribute_map')\n", (5215, 5242), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((5557, 5596), 'oneflow.python.lib.core.enable_if.condition', 'enable_if.condition', (['hob.in_global_mode'], {}), '(hob.in_global_mode)\n', (5576, 5596), True, 'import oneflow.python.lib.core.enable_if as enable_if\n'), ((6221, 6267), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""cast_to_current_logical_view"""'], {}), "('cast_to_current_logical_view')\n", (6235, 6267), False, 'from oneflow.python.oneflow_export import oneflow_export\n'), ((1370, 1406), 'oneflow.python.lib.core.enable_if.unique', 'enable_if.unique', (['[distribute_clone]'], {}), '([distribute_clone])\n', (1386, 1406), True, 'import oneflow.python.lib.core.enable_if as enable_if\n'), ((1604, 1631), 'oneflow.core.operator.op_conf_pb2.OperatorConf', 'op_conf_util.OperatorConf', ([], {}), '()\n', (1629, 1631), True, 'import oneflow.core.operator.op_conf_pb2 as op_conf_util\n'), ((1914, 1955), 'oneflow.python.framework.interpret_util.ConsistentForward', 'interpret_util.ConsistentForward', (['op_conf'], {}), '(op_conf)\n', (1946, 1955), True, 'import oneflow.python.framework.interpret_util as interpret_util\n'), ((2394, 2428), 'oneflow.python.lib.core.enable_if.unique', 'enable_if.unique', (['[distribute_add]'], {}), '([distribute_add])\n', (2410, 2428), True, 'import oneflow.python.lib.core.enable_if as enable_if\n'), ((2711, 2738), 'oneflow.core.operator.op_conf_pb2.OperatorConf', 'op_conf_util.OperatorConf', ([], {}), '()\n', (2736, 2738), True, 'import oneflow.core.operator.op_conf_pb2 as op_conf_util\n'), ((2916, 2957), 'oneflow.python.framework.interpret_util.ConsistentForward', 'interpret_util.ConsistentForward', (['op_conf'], {}), '(op_conf)\n', (2948, 2957), True, 'import oneflow.python.framework.interpret_util as interpret_util\n'), ((2968, 3004), 'oneflow.core.register.logical_blob_id_pb2.LogicalBlobId', 'logical_blob_id_util.LogicalBlobId', ([], {}), '()\n', (3002, 3004), True, 'import oneflow.core.register.logical_blob_id_pb2 as logical_blob_id_util\n'), ((3073, 3105), 'oneflow.python.framework.remote_blob.RemoteBlob', 'remote_blob_util.RemoteBlob', (['lbi'], {}), '(lbi)\n', (3100, 3105), True, 'import oneflow.python.framework.remote_blob as remote_blob_util\n'), ((3295, 3331), 'oneflow.python.lib.core.enable_if.unique', 'enable_if.unique', (['[distribute_split]'], {}), '([distribute_split])\n', (3311, 3331), True, 'import oneflow.python.lib.core.enable_if as enable_if\n'), ((3548, 3575), 'oneflow.core.operator.op_conf_pb2.OperatorConf', 'op_conf_util.OperatorConf', ([], {}), '()\n', (3573, 3575), True, 'import oneflow.core.operator.op_conf_pb2 as op_conf_util\n'), ((3904, 3945), 'oneflow.python.framework.interpret_util.ConsistentForward', 'interpret_util.ConsistentForward', (['op_conf'], {}), '(op_conf)\n', (3936, 3945), True, 'import oneflow.python.framework.interpret_util as interpret_util\n'), ((4405, 4442), 'oneflow.python.lib.core.enable_if.unique', 'enable_if.unique', (['[distribute_concat]'], {}), '([distribute_concat])\n', (4421, 4442), True, 'import oneflow.python.lib.core.enable_if as enable_if\n'), ((4750, 4777), 'oneflow.core.operator.op_conf_pb2.OperatorConf', 'op_conf_util.OperatorConf', ([], {}), '()\n', (4775, 4777), True, 'import oneflow.core.operator.op_conf_pb2 as op_conf_util\n'), ((5008, 5049), 'oneflow.python.framework.interpret_util.ConsistentForward', 'interpret_util.ConsistentForward', (['op_conf'], {}), '(op_conf)\n', (5040, 5049), True, 'import oneflow.python.framework.interpret_util as interpret_util\n'), ((5060, 5096), 'oneflow.core.register.logical_blob_id_pb2.LogicalBlobId', 'logical_blob_id_util.LogicalBlobId', ([], {}), '()\n', (5094, 5096), True, 'import oneflow.core.register.logical_blob_id_pb2 as logical_blob_id_util\n'), ((5165, 5197), 'oneflow.python.framework.remote_blob.RemoteBlob', 'remote_blob_util.RemoteBlob', (['lbi'], {}), '(lbi)\n', (5192, 5197), True, 'import oneflow.python.framework.remote_blob as remote_blob_util\n'), ((5485, 5519), 'oneflow.python.lib.core.enable_if.unqiue', 'enable_if.unqiue', (['[distribute_map]'], {}), '([distribute_map])\n', (5501, 5519), True, 'import oneflow.python.lib.core.enable_if as enable_if\n'), ((1552, 1589), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""DistributeClone_"""'], {}), "('DistributeClone_')\n", (1569, 1589), True, 'import oneflow.python.framework.id_util as id_util\n'), ((2045, 2081), 'oneflow.core.register.logical_blob_id_pb2.LogicalBlobId', 'logical_blob_id_util.LogicalBlobId', ([], {}), '()\n', (2079, 2081), True, 'import oneflow.core.register.logical_blob_id_pb2 as logical_blob_id_util\n'), ((2661, 2696), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""DistributeAdd_"""'], {}), "('DistributeAdd_')\n", (2678, 2696), True, 'import oneflow.python.framework.id_util as id_util\n'), ((3496, 3533), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""DistributeSplit_"""'], {}), "('DistributeSplit_')\n", (3513, 3533), True, 'import oneflow.python.framework.id_util as id_util\n'), ((4035, 4071), 'oneflow.core.register.logical_blob_id_pb2.LogicalBlobId', 'logical_blob_id_util.LogicalBlobId', ([], {}), '()\n', (4069, 4071), True, 'import oneflow.core.register.logical_blob_id_pb2 as logical_blob_id_util\n'), ((4697, 4735), 'oneflow.python.framework.id_util.UniqueStr', 'id_util.UniqueStr', (['"""DistributeConcat_"""'], {}), "('DistributeConcat_')\n", (4714, 4735), True, 'import oneflow.python.framework.id_util as id_util\n'), ((5745, 5792), 'oneflow.advanced.distribute_split', 'oneflow.advanced.distribute_split', (['x'], {'axis': 'axis'}), '(x, axis=axis)\n', (5778, 5792), False, 'import oneflow\n'), ((6063, 6111), 'oneflow.advanced.distribute_concat', 'oneflow.advanced.distribute_concat', (['x'], {'axis': 'axis'}), '(x, axis=axis)\n', (6097, 6111), False, 'import oneflow\n'), ((6591, 6610), 'oneflow.identity', 'oneflow.identity', (['x'], {}), '(x)\n', (6607, 6610), False, 'import oneflow\n'), ((7370, 7393), 'oneflow.current_scope', 'oneflow.current_scope', ([], {}), '()\n', (7391, 7393), False, 'import oneflow\n'), ((1740, 1763), 'oneflow.current_scope', 'oneflow.current_scope', ([], {}), '()\n', (1761, 1763), False, 'import oneflow\n'), ((2164, 2196), 'oneflow.python.framework.remote_blob.RemoteBlob', 'remote_blob_util.RemoteBlob', (['lbi'], {}), '(lbi)\n', (2191, 2196), True, 'import oneflow.python.framework.remote_blob as remote_blob_util\n'), ((3730, 3753), 'oneflow.current_scope', 'oneflow.current_scope', ([], {}), '()\n', (3751, 3753), False, 'import oneflow\n'), ((4154, 4186), 'oneflow.python.framework.remote_blob.RemoteBlob', 'remote_blob_util.RemoteBlob', (['lbi'], {}), '(lbi)\n', (4181, 4186), True, 'import oneflow.python.framework.remote_blob as remote_blob_util\n'), ((6423, 6460), 'oneflow.scope.mirrored_view_enabled', 'oneflow.scope.mirrored_view_enabled', ([], {}), '()\n', (6458, 6460), False, 'import oneflow\n'), ((6532, 6571), 'oneflow.scope.consistent_view_enabled', 'oneflow.scope.consistent_view_enabled', ([], {}), '()\n', (6569, 6571), False, 'import oneflow\n'), ((7574, 7643), 'oneflow.scope.placement', 'oneflow.scope.placement', (['parallel_desc_symbol.device_tag', 'mch_dev_str'], {}), '(parallel_desc_symbol.device_tag, mch_dev_str)\n', (7597, 7643), False, 'import oneflow\n'), ((2549, 2572), 'oneflow.current_scope', 'oneflow.current_scope', ([], {}), '()\n', (2570, 2572), False, 'import oneflow\n'), ((4585, 4608), 'oneflow.current_scope', 'oneflow.current_scope', ([], {}), '()\n', (4606, 4608), False, 'import oneflow\n')] |
# coding=utf-8
import numpy as np
from numpy import random
import oneflow as flow
import oneflow.nn as nn
import resnet50_model
# resnet50 bs 32, use_disjoint_set=False: threshold ~800MB
# memory policy:
# 1: only reuse the memory block with exactly the same size
# 2: reuse the memory block with the same size or larger
dtr_enabled = True
threshold = "800MB"
debug_level = 1
memory_policy = 1
use_disjoint_set = True
print(f'dtr_enabled: {dtr_enabled}, threshold: {threshold}, debug_level: {debug_level}, memory_policy: {memory_policy}, use_disjoint_set: {use_disjoint_set}')
flow.enable_dtr(dtr_enabled, threshold, debug_level, memory_policy, use_disjoint_set)
seed = 20
flow.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
def sync():
flow._oneflow_internal.eager.multi_client.Sync()
def display():
flow._oneflow_internal.dtr.display()
# init model
model = resnet50_model.resnet50(norm_layer=nn.Identity)
# model.load_state_dict(flow.load('/tmp/abcde'))
flow.save(model.state_dict(), '/tmp/abcde')
criterion = nn.CrossEntropyLoss()
cuda0 = flow.device('cuda:0')
# enable module to use cuda
model.to(cuda0)
criterion.to(cuda0)
learning_rate = 1e-3
# optimizer = flow.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9)
optimizer = flow.optim.SGD(model.parameters(), lr=learning_rate, momentum=0)
batch_size = 32
# generate random data and label
train_data = flow.tensor(
np.random.uniform(size=(batch_size, 3, 224, 224)).astype(np.float32), device=cuda0
)
train_label = flow.tensor(
(np.random.uniform(size=(batch_size,)) * 1000).astype(np.int32), dtype=flow.int32, device=cuda0
)
# run forward, backward and update parameters
for epoch in range(300):
logits = model(train_data)
loss = criterion(logits, train_label)
print('forward over')
# loss.print_ptr()
loss.backward()
print('backward over')
optimizer.step()
print('step over')
optimizer.zero_grad(True)
if debug_level > 0:
sync()
display()
print('loss: ', loss.numpy())
| [
"oneflow._oneflow_internal.dtr.display",
"oneflow.nn.CrossEntropyLoss",
"oneflow._oneflow_internal.eager.multi_client.Sync",
"oneflow.manual_seed",
"oneflow.device",
"oneflow.enable_dtr"
] | [((584, 673), 'oneflow.enable_dtr', 'flow.enable_dtr', (['dtr_enabled', 'threshold', 'debug_level', 'memory_policy', 'use_disjoint_set'], {}), '(dtr_enabled, threshold, debug_level, memory_policy,\n use_disjoint_set)\n', (599, 673), True, 'import oneflow as flow\n'), ((681, 703), 'oneflow.manual_seed', 'flow.manual_seed', (['seed'], {}), '(seed)\n', (697, 703), True, 'import oneflow as flow\n'), ((704, 724), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (718, 724), True, 'import numpy as np\n'), ((725, 742), 'numpy.random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (736, 742), False, 'from numpy import random\n'), ((891, 938), 'resnet50_model.resnet50', 'resnet50_model.resnet50', ([], {'norm_layer': 'nn.Identity'}), '(norm_layer=nn.Identity)\n', (914, 938), False, 'import resnet50_model\n'), ((1045, 1066), 'oneflow.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (1064, 1066), True, 'import oneflow.nn as nn\n'), ((1076, 1097), 'oneflow.device', 'flow.device', (['"""cuda:0"""'], {}), "('cuda:0')\n", (1087, 1097), True, 'import oneflow as flow\n'), ((761, 809), 'oneflow._oneflow_internal.eager.multi_client.Sync', 'flow._oneflow_internal.eager.multi_client.Sync', ([], {}), '()\n', (807, 809), True, 'import oneflow as flow\n'), ((831, 867), 'oneflow._oneflow_internal.dtr.display', 'flow._oneflow_internal.dtr.display', ([], {}), '()\n', (865, 867), True, 'import oneflow as flow\n'), ((1424, 1473), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(batch_size, 3, 224, 224)'}), '(size=(batch_size, 3, 224, 224))\n', (1441, 1473), True, 'import numpy as np\n'), ((1541, 1578), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(batch_size,)'}), '(size=(batch_size,))\n', (1558, 1578), True, 'import numpy as np\n')] |
import oneflow as flow
import oneflow.nn as nn
class SEModule(nn.Module):
def __init__(
self,
channels,
reduction=16,
rd_channels=None,
act_layer=nn.ReLU,
gate_layer=nn.Sigmoid,
mlp_bias=False,
):
super(SEModule, self).__init__()
rd_channels = channels // reduction if rd_channels is None else rd_channels
self.fc1 = nn.Conv2d(channels, rd_channels, 1, bias=mlp_bias)
self.act = act_layer(inplace=True)
self.fc2 = nn.Conv2d(rd_channels, channels, 1, bias=mlp_bias)
self.gate = gate_layer()
def forward(self, x):
x_avg = self.fc2(self.act(self.fc1(x.mean((2, 3), keepdim=True))))
x_attn = self.gate(x_avg)
return x * x_attn
| [
"oneflow.nn.Conv2d"
] | [((407, 457), 'oneflow.nn.Conv2d', 'nn.Conv2d', (['channels', 'rd_channels', '(1)'], {'bias': 'mlp_bias'}), '(channels, rd_channels, 1, bias=mlp_bias)\n', (416, 457), True, 'import oneflow.nn as nn\n'), ((520, 570), 'oneflow.nn.Conv2d', 'nn.Conv2d', (['rd_channels', 'channels', '(1)'], {'bias': 'mlp_bias'}), '(rd_channels, channels, 1, bias=mlp_bias)\n', (529, 570), True, 'import oneflow.nn as nn\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 collections import OrderedDict
from functools import partial
from typing import Iterator, Optional, Set, Union, List
import oneflow._C
import oneflow._oneflow_internal
import oneflow.framework.graph_build_util as graph_build_util
from oneflow.env import get_rank
from oneflow.framework.tensor import Tensor, TensorTuple
from oneflow.nn.module import Module
from oneflow.nn.modules.container import *
from oneflow.nn.utils.container import *
from oneflow.nn.parameter import Parameter
from oneflow.nn.graph.block_config import BlockConfig
from oneflow.nn.graph.util import add_indent, seq_to_func_return
def get_block_cls(item):
if isinstance(item, Sequential):
return SequentialBlock
elif isinstance(item, ModuleList):
return ModuleListBlock
elif isinstance(item, ModuleDict):
return ModuleDictBlock
elif isinstance(item, ParameterList):
return ParameterListBlock
elif isinstance(item, ParameterDict):
return ParameterDictBlock
elif isinstance(item, Module):
return ModuleBlock
elif isinstance(item, Tensor):
return TensorBlock
else:
raise NotImplementedError()
class BlockType:
NONE = "NONE"
MODULE = "MODULE"
PARAMETER = "PARAMETER"
BUFFER = "BUFFER"
class Block(object):
def __init__(
self, prefix: str = "", name: str = "",
):
self._name = name
self._name_prefix = prefix
self._type = BlockType.NONE
self._origin = None
self._scope = None
self._prev_scope = None
self.config = BlockConfig()
@property
def name(self):
return self._name
@property
def name_prefix(self):
return self._name_prefix
@property
def type(self):
return self._type
@property
def prev_scope(self):
if self._prev_scope is None:
self._prev_scope = oneflow._oneflow_internal.GetCurrentScope()
return self._prev_scope
@property
def scope(self):
if self._scope is None:
self._scope = graph_build_util.make_new_block_scope(self.prev_scope, self)
return self._scope
def scope_context(self):
return graph_build_util.BlockScopeContext(self.prev_scope, self.scope)
class ModuleBlock(Block):
def __init__(
self, prefix: str = "", name: str = "", origin: Module = None,
):
assert not isinstance(origin, Block)
super().__init__(prefix, name)
self._debug = False
self._debug_min_s_level = 2
self._debug_max_v_level = 0
self._type = BlockType.MODULE
self._is_executing_forward = False
self._modules = OrderedDict()
self._parameters = OrderedDict()
self._buffers = OrderedDict()
self._args_repr = []
self._outs_repr = []
self.set_origin(origin)
@property
def origin(self):
return self._origin
def set_origin(self, origin):
self._origin = origin
if origin is None:
return
assert isinstance(origin, Module)
for (n, m) in list(origin.named_children()):
self.__setattr__(
n, get_block_cls(m)(self._name_prefix + self._name + ".", n, m)
)
for (n, p) in list(origin.named_parameters("", False)):
self.__setattr__(
n, get_block_cls(p)(self._name_prefix + self._name + ".", n, p)
)
for (n, b) in list(origin.named_buffers("", False)):
self.__setattr__(
n, get_block_cls(b)(self._name_prefix + self._name + ".", n, b)
)
def debug(
self,
v_level: int = 0,
ranks: Optional[Union[int, List[int]]] = None,
mode: bool = True,
) -> None:
assert isinstance(mode, bool)
assert isinstance(v_level, int)
if ranks is None:
rank_list = [0]
elif isinstance(ranks, int):
rank_list = [ranks]
elif isinstance(ranks, list):
rank_list = ranks
else:
raise ValueError("ranks must be int or List[int].")
my_rank = get_rank()
if -1 in rank_list or my_rank in rank_list:
self._debug = mode
if self._debug:
self._debug_min_s_level = 0
self._debug_max_v_level = v_level
if self._type == BlockType.MODULE:
def _set_child(d):
for (_, n) in d.items():
n.debug(v_level, ranks, mode)
_set_child(self._modules)
def __call__(self, *args):
assert self._type == BlockType.MODULE
self._print(0, 1, self._shallow_repr())
for idx, arg in enumerate(args):
meta_repr_str = (
arg._meta_repr() if isinstance(arg, Tensor) else str(type(arg))
)
in_str = (
"(INPUT:_"
+ self.name_prefix
+ self.name
+ "-input_"
+ str(idx)
+ ":"
+ meta_repr_str
+ ")"
)
if not isinstance(arg, Tensor):
in_str = "[WARNING]" + in_str
self._args_repr.append(in_str)
self._print(0, 1, in_str)
def _print_state(d):
for (_, n) in d.items():
self._print(0, 1, n._shallow_repr())
_print_state(self._parameters)
_print_state(self._buffers)
# NOTE: The original nn.Moudle's __call__ method is ignored, which means
# that hooks of nn.Modules are ignored. It is not recommended
# to use hooks of nn.Module in nn.Graph for the moment.
# result = self._origin.__class__.__call__(self, *args)
result = self.__block_forward(*args)
outputs = ()
if not (type(result) is tuple or type(result) is list):
outputs = (result,)
else:
outputs = result
for idx, out in enumerate(outputs):
out_repr = out._meta_repr() if isinstance(out, Tensor) else str(type(out))
out_str = (
"(OUTPUT:_"
+ self.name_prefix
+ self.name
+ "-output_"
+ str(idx)
+ ":"
+ out_repr
+ ")"
)
if not isinstance(out, Tensor):
out_str = "[WARNING]" + out_str
self._outs_repr.append(out_str)
self._print(0, 1, out_str)
return result
def __block_forward(self, *args):
self._is_executing_forward = True
args = self.__pre_forward_mapping_out_scope(*args)
with self.scope_context():
result = self._origin.__class__.forward(self, *args)
result = self.__post_forward_mapping_out_scope(result)
result = seq_to_func_return(result)
self._is_executing_forward = False
return result
def __pre_forward_mapping_out_scope(self, *args):
# Insert identity op when doing activation checkpointing or pipeline execution.
# Identity op outside activation checkpointing scope will be the endpoint of an activation checkpointing segment.
# Identity op as the first op of a pipeline stage will make backward op depends on the identity op within the stage,
# otherwise the backward op may depends the op in former stage which will make graph creates unnessary buffers.
if self.config.activation_checkpointing or (
self.config.stage_id is not None and self.config.stage_id >= 0
):
def insert_identity(t):
assert isinstance(t, Tensor)
return oneflow._C.identity(t)
args = self.__mapping_io(
"input", insert_identity, "insert_identity", *args,
)
return args
def __post_forward_mapping_out_scope(self, *args):
# Insert identity op when doing activation checkpointing or pipeline execution.
if self.config.activation_checkpointing or (
self.config.stage_id is not None and self.config.stage_id >= 0
):
def insert_identity(t):
assert isinstance(t, Tensor)
return oneflow._C.identity(t)
args = self.__mapping_io(
"output", insert_identity, "insert_identity", *args,
)
return args
def add_module(self, name: str, module: Optional[Module]) -> None:
self.__setattr__(
name,
get_block_cls(module)(self._name_prefix + self._name + ".", name, module),
)
def register_parameter(self, name: str, param: Optional[Parameter]) -> None:
self.__setattr__(
name,
get_block_cls(param)(self._name_prefix + self._name + ".", name, param),
)
def modules(self, memo: Optional[Set["Block"]] = None) -> Iterator["Block"]:
assert self._type == BlockType.MODULE
if memo is None:
memo = set()
if self not in memo:
memo.add(self)
yield self
for (name, module) in self._modules.items():
if module is None:
continue
for m in module.modules(memo):
yield m
def __mapping_io(self, io_type, func, func_desc, *args):
assert isinstance(func_desc, str)
assert io_type in ("input", "output")
mapped_args = []
def mapping_tensor(item):
assert isinstance(item, Tensor)
return func(item)
for idx, arg in enumerate(args):
if isinstance(arg, list):
seq_args = list()
for i in range(len(arg)):
is_tensor, name, repr_str = self.__io_tensor_check_and_gen(
arg[i], io_type, idx, i
)
if is_tensor:
seq_args.append(mapping_tensor(arg[i]))
self._print(
0,
1,
f"{repr_str} is a Tensor, {func_desc} transformation has been done.",
)
else:
self._print(
0,
0,
f"{repr_str} is not a Tensor, {func_desc} transformation will be ignored.",
)
seq_args.append(arg[i])
mapped_args.append(seq_args)
elif isinstance(arg, Tensor):
is_tensor, name, repr_str = self.__io_tensor_check_and_gen(
arg, io_type, idx
)
assert is_tensor
mapped_args.append(mapping_tensor(arg))
self._print(
0,
1,
f"{repr_str} is a Tensor, {func_desc} transformation has been done.",
)
else:
is_tensor, name, repr_str = self.__io_tensor_check_and_gen(
arg, io_type, idx
)
assert not is_tensor
mapped_args.append(arg)
self._print(
0,
0,
f"{repr_str} is not a Tensor or a list of Tensor, {func_desc} transformation will be ignored.",
)
return tuple(mapped_args)
def __io_tensor_check_and_gen(self, item, io_type, idx, second_idx=None):
assert io_type in ("input", "output")
name = (
"_"
+ self.name_prefix
+ self.name
+ "-"
+ io_type
+ "_"
+ str(idx)
+ ("" if second_idx is None else "_" + str(second_idx))
)
if isinstance(item, Tensor):
repr_str = (
"(" + io_type.upper() + ":" + name + ":" + item._meta_repr() + ")"
)
return True, name, repr_str
else:
repr_str = (
"[WARNING]("
+ io_type.upper()
+ ":"
+ name
+ ":"
+ str(type(item))
+ ")"
)
return False, name, repr_str
def __members(self, get_members_fn, recurse=True) -> Iterator["Block"]:
assert self._type == BlockType.MODULE
memo = set()
modules = self.modules() if recurse else [self]
for module in modules:
members = get_members_fn(module)
for (k, v) in members:
if v is None or v in memo:
continue
memo.add(v)
yield v
def parameters(self, recurse: bool = True) -> Iterator["Block"]:
assert self._type == BlockType.MODULE
gen = self.__members(lambda module: module._parameters.items(), recurse=recurse)
for elem in gen:
yield elem
def buffers(self, recurse: bool = True) -> Iterator["Block"]:
assert self._type == BlockType.MODULE
gen = self.__members(lambda module: module._buffers.items(), recurse=recurse)
for elem in gen:
yield elem
def __setattr__(self, name: str, value=None) -> None:
if value is None or not isinstance(value, Block):
self.__dict__[name] = value
else:
dicts_or_sets = (
self.__dict__,
self._modules,
self._parameters,
self._buffers,
)
for d in dicts_or_sets:
if name in d:
raise AttributeError(
"'{}' object has duplicated attribute named '{}'".format(
self._name, name
)
)
if value.type == BlockType.MODULE:
self._modules[name] = value
elif value.type == BlockType.PARAMETER:
self._parameters[name] = value
elif value.type == BlockType.BUFFER:
self._buffers[name] = value
else:
raise AttributeError(
"'{}' object are not allowed to set attribute named '{}'".format(
type(self).__name__, name
)
)
def __getattr__(self, name: str):
if name in self.__dict__:
return self.__dict__[name]
# support get module
if "_modules" in self.__dict__:
modules = self.__dict__["_modules"]
if name in modules:
return modules[name]
# support get parameter
p_state = self._get_from_states(name, "_parameters")
if p_state is not None:
return p_state
# support get buffer
b_state = self._get_from_states(name, "_buffers")
if b_state is not None:
return b_state
# support none parameter or buffer
if name in self._origin._parameters:
p_none = self._origin._parameters[name]
assert p_none is None
return None
if name in self._origin._buffers:
b_none = self._origin._buffers[name]
assert b_none is None
return None
# support get normal attr
if name in self._origin.__dict__:
return self._origin.__dict__[name]
# support get function
if hasattr(self._origin, name):
return partial(getattr(self._origin.__class__, name), self)
raise AttributeError(
"'{}' '{}' object '{}' in nn.Graph has no attribute '{}'".format(
self._type, type(self).__name__, self._name_prefix + self.name, name
)
)
def _get_from_states(self, name, states_name):
if states_name not in self.__dict__:
return None
_states = self.__dict__[states_name]
if name not in _states:
return None
_s_block = _states[name]
if graph_build_util.lazy_mode.is_enabled():
_s_block.try_build()
return _s_block.lazy_origin
elif (
not graph_build_util.lazy_mode.is_enabled()
) and self._is_executing_forward:
# eager and inside nn.Graph.build()
return _s_block.origin
else:
# outside nn.Graph.build()
return _s_block
def __repr__(self):
lines = None
child_lines = []
if (self.config is not None) and (not self.config._is_null):
child_lines.append(add_indent(repr(self.config), 2))
if len(self._args_repr) > 0:
for in_str in self._args_repr:
input_str = add_indent(in_str, 2)
child_lines.append(input_str)
def _append_child(d):
for (_, n) in d.items():
n_str = repr(n)
n_str = add_indent(n_str, 2)
child_lines.append(n_str)
_append_child(self._parameters)
_append_child(self._buffers)
_append_child(self._modules)
if len(self._outs_repr) > 0:
for out_str in self._outs_repr:
output_str = add_indent(out_str, 2)
child_lines.append(output_str)
if len(child_lines) > 0:
lines = child_lines
main_str = self._shallow_repr() + ": ("
if lines is not None:
main_str += "\n " + "\n ".join(lines) + "\n"
main_str += ")"
return main_str
def _shallow_repr(self):
shallow_repr = (
"("
+ self._type
+ ":"
+ self._name_prefix
+ self._name
+ ":"
+ self._origin._shallow_repr()
+ ")"
)
return shallow_repr
def _print(self, s_level=2, v_level=0, msg: str = ""):
r"""Do print according to info level.
"""
assert isinstance(s_level, int)
assert isinstance(v_level, int)
assert isinstance(msg, str)
if s_level >= self._debug_min_s_level:
if (s_level > 0) or (s_level == 0 and v_level <= self._debug_max_v_level):
print(msg)
class LazyBuilder(object):
def __init__(self, name: str = None, method=None):
self.name = name
self.method = method
self.result = None
self.finished = False
def try_build(self, block=None):
if not self.finished:
assert self.name is not None
assert self.method is not None
assert self.result is None
with block.scope_context():
self.result = self.method()
self.finished = True
class TensorBlock(Block):
def __init__(
self, prefix: str = "", name: str = "", origin: Union[Parameter, Tensor] = None,
):
assert not isinstance(origin, Block)
super().__init__(prefix, name)
if isinstance(origin, Parameter):
self._type = BlockType.PARAMETER
elif isinstance(origin, Tensor):
self._type = BlockType.BUFFER
else:
raise NotImplementedError()
self._lazy_origin_builder = LazyBuilder()
self.build_finished = False
self.set_origin(origin)
@property
def origin(self):
return self._origin
def set_origin(self, origin):
self._origin = origin
@property
def lazy_origin(self):
assert (
self._type == BlockType.PARAMETER or self._type == BlockType.BUFFER
), "Only Parameter or Buffer Block has lazy_origin"
return self._lazy_origin_builder.result
def lazy_origin_builder(self):
assert (
self._type == BlockType.PARAMETER or self._type == BlockType.BUFFER
), "Only Parameter or Buffer Block has lazy_origin_builder"
return self._lazy_origin_builder
def set_lazy_origin_builder(self, builder=None):
assert (
self._type == BlockType.PARAMETER or self._type == BlockType.BUFFER
), "Only Parameter or Buffer Block has lazy_origin_builder"
self._lazy_origin_builder = builder
def try_build(self):
if not self.build_finished:
self._lazy_origin_builder.try_build(self)
self.build_finished = True
def __repr__(self):
lines = None
main_str = self._shallow_repr() + ": ("
if lines is not None:
main_str += "\n " + "\n ".join(lines) + "\n"
main_str += ")"
return main_str
def _shallow_repr(self):
shallow_repr = (
"("
+ self._type
+ ":"
+ self._name_prefix
+ self._name
+ ":"
+ self._origin._meta_repr()
+ ")"
)
return shallow_repr
class SequentialBlock(get_seq(ModuleBlock)):
def __init__(
self, prefix: str = "", name: str = "", origin: Sequential = None,
):
super().__init__()
self._name_prefix = prefix
self._name = name
self.set_origin(origin)
class ModuleListBlock(get_list(ModuleBlock)):
def __init__(
self, prefix: str = "", name: str = "", origin: ModuleList = None,
):
super().__init__()
self._name_prefix = prefix
self._name = name
self.set_origin(origin)
# MoudleList is a container without forward() method,
# so it will not be executed or has an execution config.
self.config = None
class ModuleDictBlock(get_dict(ModuleBlock)):
def __init__(
self, prefix: str = "", name: str = "", origin: ModuleDict = None,
):
super().__init__()
self._name_prefix = prefix
self._name = name
self.set_origin(origin)
class ParameterListBlock(get_para_list(ModuleBlock)):
def __init__(
self, prefix: str = "", name: str = "", origin: ParameterList = None,
):
super().__init__()
self._name_prefix = prefix
self._name = name
self.set_origin(origin)
self._is_executing_forward = True
def __getitem__(self, idx):
assert isinstance(idx, int)
idx = self._get_abs_string_index(idx)
key = str(idx)
p_state = self._get_from_states(key, "_parameters")
if p_state is not None:
return p_state
else:
raise AttributeError("ParameterList dosen't contain ", key)
class ParameterDictBlock(get_para_dict(ModuleBlock)):
def __init__(
self, prefix: str = "", name: str = "", origin: ParameterDict = None,
):
super().__init__()
self._name_prefix = prefix
self._name = name
self.set_origin(origin)
self._is_executing_forward = True
def __getitem__(self, key: str):
p_state = self._get_from_states(key, "_parameters")
if p_state is not None:
return p_state
else:
raise AttributeError("ParameterDict dosen't contain key ", key)
| [
"oneflow.framework.graph_build_util.make_new_block_scope",
"oneflow.nn.graph.util.add_indent",
"oneflow.env.get_rank",
"oneflow.nn.graph.util.seq_to_func_return",
"oneflow.framework.graph_build_util.lazy_mode.is_enabled",
"oneflow.nn.graph.block_config.BlockConfig",
"oneflow.framework.graph_build_util.BlockScopeContext"
] | [((2167, 2180), 'oneflow.nn.graph.block_config.BlockConfig', 'BlockConfig', ([], {}), '()\n', (2178, 2180), False, 'from oneflow.nn.graph.block_config import BlockConfig\n'), ((2790, 2853), 'oneflow.framework.graph_build_util.BlockScopeContext', 'graph_build_util.BlockScopeContext', (['self.prev_scope', 'self.scope'], {}), '(self.prev_scope, self.scope)\n', (2824, 2853), True, 'import oneflow.framework.graph_build_util as graph_build_util\n'), ((3267, 3280), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3278, 3280), False, 'from collections import OrderedDict\n'), ((3308, 3321), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3319, 3321), False, 'from collections import OrderedDict\n'), ((3346, 3359), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3357, 3359), False, 'from collections import OrderedDict\n'), ((4738, 4748), 'oneflow.env.get_rank', 'get_rank', ([], {}), '()\n', (4746, 4748), False, 'from oneflow.env import get_rank\n'), ((7510, 7536), 'oneflow.nn.graph.util.seq_to_func_return', 'seq_to_func_return', (['result'], {}), '(result)\n', (7528, 7536), False, 'from oneflow.nn.graph.util import add_indent, seq_to_func_return\n'), ((16757, 16796), 'oneflow.framework.graph_build_util.lazy_mode.is_enabled', 'graph_build_util.lazy_mode.is_enabled', ([], {}), '()\n', (16794, 16796), True, 'import oneflow.framework.graph_build_util as graph_build_util\n'), ((2657, 2717), 'oneflow.framework.graph_build_util.make_new_block_scope', 'graph_build_util.make_new_block_scope', (['self.prev_scope', 'self'], {}), '(self.prev_scope, self)\n', (2694, 2717), True, 'import oneflow.framework.graph_build_util as graph_build_util\n'), ((17461, 17482), 'oneflow.nn.graph.util.add_indent', 'add_indent', (['in_str', '(2)'], {}), '(in_str, 2)\n', (17471, 17482), False, 'from oneflow.nn.graph.util import add_indent, seq_to_func_return\n'), ((17653, 17673), 'oneflow.nn.graph.util.add_indent', 'add_indent', (['n_str', '(2)'], {}), '(n_str, 2)\n', (17663, 17673), False, 'from oneflow.nn.graph.util import add_indent, seq_to_func_return\n'), ((17942, 17964), 'oneflow.nn.graph.util.add_indent', 'add_indent', (['out_str', '(2)'], {}), '(out_str, 2)\n', (17952, 17964), False, 'from oneflow.nn.graph.util import add_indent, seq_to_func_return\n'), ((16902, 16941), 'oneflow.framework.graph_build_util.lazy_mode.is_enabled', 'graph_build_util.lazy_mode.is_enabled', ([], {}), '()\n', (16939, 16941), True, 'import oneflow.framework.graph_build_util as graph_build_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.
"""
# Version: 0.0.1
# Author: puchazhong(<EMAIL>)
# Data: 11/03/2020
import os
import argparse
import numpy as np
import oneflow as flow
from reid_model import resreid_train, HS_reid_train
from data_loader import Market1501, RandomIdentitySampler, ImageDataset
import oneflow.typing as tp
from of_utils.avgmeter import AverageMeter
from of_loss import _TripletLoss, _CrossEntropyLoss
from eval import evaluate
import time
parser = argparse.ArgumentParser(description="flags for person re-identification")
parser.add_argument('--gpu_devices', type=str, default='3')
parser.add_argument("--model", type=str, default='resreid', required=False, help="resreid or HS-reid")
parser.add_argument("--batch_size", type=int, default=64, required=False)
parser.add_argument("--data_dir", type=str, default='./dataset', required=False, help="dataset directory")
parser.add_argument("-image_height", "--image_height", type=int, default=256, required=False)
parser.add_argument("-image_width", "--image_width", type=int, default=128, required=False)
parser.add_argument("--model_load_dir", type=str, default="./pretrained/model_pcb", required=False,
help="model load directory")
parser.add_argument("--num_classes", type=int, default=751, required=False)
parser.add_argument("--lr", type=float, default=3.5e-4, required=False)
parser.add_argument("--max_epoch", type=int, default=120, required=False)
parser.add_argument("--step_size", type=list, default=[7360, 12880], required=False)
parser.add_argument("--weight_t", type=float, default=0.5, required=False)
parser.add_argument("--margin", type=float, default=0.3, required=False)
parser.add_argument("--weight_decay", type=float, default=5e-4, required=False)
parser.add_argument("--adam_beta1", type=float, default=0.9, required=False)
parser.add_argument("--adam_beta2", type=float, default=0.999, required=False)
parser.add_argument("--warmup", action='store_true', default=True, help="warm up lr scheduler")
parser.add_argument("--warmup_factor", type=float, default=0.1, required=False)
parser.add_argument("--warmup_iters", type=int, default=1840, required=False)
parser.add_argument("--epsilon", type=float, default=0.1, required=False)
parser.add_argument("--eval_freq", type=int, default=20, required=False)
parser.add_argument("--dist_metric", type=str, default='euclidean', help="euclidean or cosine")
parser.add_argument("--num_instances", type=int, default=4)
parser.add_argument("--eval_batch", type=int, default=600, required=False)
parser.add_argument('opts', default=None, nargs=argparse.REMAINDER, help='Modify config options using the command-line')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_devices
# configs
func_config = flow.FunctionConfig()
func_config.default_data_type(flow.float)
# model opts
model = {'resreid': resreid_train, 'HS-reid': HS_reid_train}
# params
max_epoch = args.max_epoch
batch_size = args.batch_size
num_class = args.num_classes
eval_batch = args.eval_batch
# input_size
eval_image = tp.Numpy.Placeholder((args.eval_batch, 3, args.image_height, args.image_width))
input_image = tp.Numpy.Placeholder((args.batch_size, 3, args.image_height, args.image_width))
input_pid = tp.Numpy.Placeholder((args.batch_size,))
# loss
criterion_t = _TripletLoss(margin=args.margin)
criterion_x = _CrossEntropyLoss(num_classes=num_class, epsilon=args.epsilon)
weight_t = args.weight_t
weight_x = 1.0 - args.weight_t
@flow.global_function("train", func_config)
def reid_train_job(image: input_image, pids: input_pid):
# optimizer init
warmup_scheduler = flow.optimizer.warmup.linear(args.warmup_iters, args.warmup_factor)
lr_scheduler = flow.optimizer.PiecewiseScalingScheduler(base_lr=args.lr,
boundaries=args.step_size,
scale=[0.1, 0.01],
warmup=warmup_scheduler)
opt = flow.optimizer.AdamW(lr_scheduler,
beta1=args.adam_beta1,
beta2=args.adam_beta2,
weight_decay=args.weight_decay)
features, cls = model[args.model](image, num_class, trainable=True)
loss_x = criterion_x.forward(cls, pids)
loss_t = criterion_t.forward(features, pids)
loss = flow.math.add(flow.math.multiply(weight_t, loss_t), flow.math.multiply(weight_x, loss_x))
opt.minimize(loss)
return loss, loss_t, loss_x
@flow.global_function("predict", func_config)
def reid_eval_job(image: eval_image):
features = model[args.model](image, num_class, trainable=False)
return features
def inference(dataset):
# get input image features
features = []
ind = list(range(len(dataset)))
for i in range((len(dataset) // eval_batch) + 1):
try:
array, _, _ = dataset.__getbatch__(ind[i * eval_batch:(i + 1) * eval_batch])
feature = reid_eval_job(array).get()
features.extend(feature.numpy_list()[0])
except:
array, _, _ = dataset.__getbatch__(ind[-eval_batch:])
feature = reid_eval_job(array).get()
features.extend(feature.numpy_list()[0][i * eval_batch - len(dataset):])
return features
def eval(dataset):
query_img, query_id, query_cam_id = map(list, zip(*dataset.query))
gallery_img, gallery_id, gallery_cam_id = map(list, zip(*dataset.gallery))
query_dataset = ImageDataset(dataset.query, flag='test', process_size=(args.image_height, args.image_width))
gallery_dataset = ImageDataset(dataset.gallery, flag='test', process_size=(args.image_height, args.image_width))
print("extract query feature")
time1 = time.time()
query_features = inference(query_dataset)
print("extract gallery feature")
gallery_features = inference(gallery_dataset)
print("done in {}".format(time.time() - time1))
return evaluate(query_features, np.array(query_id), np.array(query_cam_id), gallery_features, np.array(gallery_id),
np.array(gallery_cam_id))
def train(dataset, batch_size, max_epoch):
train_img, train_id, train_cam_id = map(list, zip(*dataset.train))
train_dataset = ImageDataset(dataset.train, flag='train', process_size=(args.image_height, args.image_width))
for eps in range(max_epoch):
losses_t = AverageMeter()
losses_x = AverageMeter()
losses = AverageMeter()
indicies = [x for x in RandomIdentitySampler(train_id, batch_size, args.num_instances)]
for i in range(len(indicies) // batch_size):
try:
# train_batch[0,1,2] are [imgs, pid, cam_id]
train_batch = train_dataset.__getbatch__(indicies[i * batch_size:(i + 1) * batch_size])
except:
train_batch = train_dataset.__getbatch__(indicies[-batch_size:])
loss, loss_t, loss_x = reid_train_job(train_batch[0], train_batch[1].astype(np.float32)).get()
losses_t.update(loss_t.numpy_list()[0][0], batch_size)
losses_x.update(loss_x.numpy_list()[0][0], batch_size)
losses.update(loss.numpy_list()[0][0], batch_size)
print('epoch: [{0}/{1}]\t'
'Loss_t {loss_t.val:.4f} ({loss_t.avg:.4f})\t'
'Loss_x {loss_x.val:.4f} ({loss_x.avg:.4f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
.format(
eps + 1, args.max_epoch,
loss_t=losses_t,
loss_x=losses_x,
loss=losses))
if (eps + 1) % args.eval_freq == 0 and (eps + 1) != args.max_epoch:
cmc, mAP = eval(dataset)
print("=".ljust(30, "=") + " Result " + "=".ljust(30, "="))
print('mAP: {:.1%}'.format(mAP))
print('CMC curve')
for r in [1, 5, 10]:
print('Rank-{:<3}: {:.1%}'.format(r, cmc[r - 1]))
print("=".ljust(66, "="))
# print("rank1:{}, mAP:{}".format(cmc[0], mAP))
print('=> End training')
print('=> Final test')
cmc, mAP = eval(dataset)
print("=".ljust(30, "=") + " Result " + "=".ljust(30, "="))
print('mAP: {:.1%}'.format(mAP))
print('CMC curve')
for r in [1, 5, 10]:
print('Rank-{:<3}: {:.1%}'.format(r, cmc[r - 1]))
print("=".ljust(66, "="))
def main():
print("=".ljust(66, "="))
for arg in vars(args):
print("{} = {}".format(arg, getattr(args, arg)))
print("-".ljust(66, "-"))
check_point = flow.train.CheckPoint()
if args.model_load_dir:
# load model from model path
assert os.path.isdir(args.model_load_dir)
print("Restoring model from {}.".format(args.model_load_dir))
check_point.load(args.model_load_dir)
else:
# model init
print("Init model on demand.")
check_point.init()
# load data for training
dataset = Market1501(root=args.data_dir)
train(dataset, batch_size, max_epoch)
if __name__ == "__main__":
main()
| [
"oneflow.FunctionConfig",
"oneflow.optimizer.AdamW",
"oneflow.math.multiply",
"oneflow.optimizer.warmup.linear",
"oneflow.train.CheckPoint",
"oneflow.global_function",
"oneflow.typing.Numpy.Placeholder",
"oneflow.optimizer.PiecewiseScalingScheduler"
] | [((1017, 1090), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""flags for person re-identification"""'}), "(description='flags for person re-identification')\n", (1040, 1090), False, 'import argparse\n'), ((3321, 3342), 'oneflow.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (3340, 3342), True, 'import oneflow as flow\n'), ((3611, 3690), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(args.eval_batch, 3, args.image_height, args.image_width)'], {}), '((args.eval_batch, 3, args.image_height, args.image_width))\n', (3631, 3690), True, 'import oneflow.typing as tp\n'), ((3705, 3784), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(args.batch_size, 3, args.image_height, args.image_width)'], {}), '((args.batch_size, 3, args.image_height, args.image_width))\n', (3725, 3784), True, 'import oneflow.typing as tp\n'), ((3797, 3837), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(args.batch_size,)'], {}), '((args.batch_size,))\n', (3817, 3837), True, 'import oneflow.typing as tp\n'), ((3860, 3892), 'of_loss._TripletLoss', '_TripletLoss', ([], {'margin': 'args.margin'}), '(margin=args.margin)\n', (3872, 3892), False, 'from of_loss import _TripletLoss, _CrossEntropyLoss\n'), ((3907, 3969), 'of_loss._CrossEntropyLoss', '_CrossEntropyLoss', ([], {'num_classes': 'num_class', 'epsilon': 'args.epsilon'}), '(num_classes=num_class, epsilon=args.epsilon)\n', (3924, 3969), False, 'from of_loss import _TripletLoss, _CrossEntropyLoss\n'), ((4029, 4071), 'oneflow.global_function', 'flow.global_function', (['"""train"""', 'func_config'], {}), "('train', func_config)\n", (4049, 4071), True, 'import oneflow as flow\n'), ((5110, 5154), 'oneflow.global_function', 'flow.global_function', (['"""predict"""', 'func_config'], {}), "('predict', func_config)\n", (5130, 5154), True, 'import oneflow as flow\n'), ((4173, 4240), 'oneflow.optimizer.warmup.linear', 'flow.optimizer.warmup.linear', (['args.warmup_iters', 'args.warmup_factor'], {}), '(args.warmup_iters, args.warmup_factor)\n', (4201, 4240), True, 'import oneflow as flow\n'), ((4260, 4393), 'oneflow.optimizer.PiecewiseScalingScheduler', 'flow.optimizer.PiecewiseScalingScheduler', ([], {'base_lr': 'args.lr', 'boundaries': 'args.step_size', 'scale': '[0.1, 0.01]', 'warmup': 'warmup_scheduler'}), '(base_lr=args.lr, boundaries=args.\n step_size, scale=[0.1, 0.01], warmup=warmup_scheduler)\n', (4300, 4393), True, 'import oneflow as flow\n'), ((4579, 4696), 'oneflow.optimizer.AdamW', 'flow.optimizer.AdamW', (['lr_scheduler'], {'beta1': 'args.adam_beta1', 'beta2': 'args.adam_beta2', 'weight_decay': 'args.weight_decay'}), '(lr_scheduler, beta1=args.adam_beta1, beta2=args.\n adam_beta2, weight_decay=args.weight_decay)\n', (4599, 4696), True, 'import oneflow as flow\n'), ((6078, 6174), 'data_loader.ImageDataset', 'ImageDataset', (['dataset.query'], {'flag': '"""test"""', 'process_size': '(args.image_height, args.image_width)'}), "(dataset.query, flag='test', process_size=(args.image_height,\n args.image_width))\n", (6090, 6174), False, 'from data_loader import Market1501, RandomIdentitySampler, ImageDataset\n'), ((6193, 6291), 'data_loader.ImageDataset', 'ImageDataset', (['dataset.gallery'], {'flag': '"""test"""', 'process_size': '(args.image_height, args.image_width)'}), "(dataset.gallery, flag='test', process_size=(args.image_height,\n args.image_width))\n", (6205, 6291), False, 'from data_loader import Market1501, RandomIdentitySampler, ImageDataset\n'), ((6335, 6346), 'time.time', 'time.time', ([], {}), '()\n', (6344, 6346), False, 'import time\n'), ((6834, 6931), 'data_loader.ImageDataset', 'ImageDataset', (['dataset.train'], {'flag': '"""train"""', 'process_size': '(args.image_height, args.image_width)'}), "(dataset.train, flag='train', process_size=(args.image_height,\n args.image_width))\n", (6846, 6931), False, 'from data_loader import Market1501, RandomIdentitySampler, ImageDataset\n'), ((9110, 9133), 'oneflow.train.CheckPoint', 'flow.train.CheckPoint', ([], {}), '()\n', (9131, 9133), True, 'import oneflow as flow\n'), ((9506, 9536), 'data_loader.Market1501', 'Market1501', ([], {'root': 'args.data_dir'}), '(root=args.data_dir)\n', (9516, 9536), False, 'from data_loader import Market1501, RandomIdentitySampler, ImageDataset\n'), ((4976, 5012), 'oneflow.math.multiply', 'flow.math.multiply', (['weight_t', 'loss_t'], {}), '(weight_t, loss_t)\n', (4994, 5012), True, 'import oneflow as flow\n'), ((5014, 5050), 'oneflow.math.multiply', 'flow.math.multiply', (['weight_x', 'loss_x'], {}), '(weight_x, loss_x)\n', (5032, 5050), True, 'import oneflow as flow\n'), ((6568, 6586), 'numpy.array', 'np.array', (['query_id'], {}), '(query_id)\n', (6576, 6586), True, 'import numpy as np\n'), ((6588, 6610), 'numpy.array', 'np.array', (['query_cam_id'], {}), '(query_cam_id)\n', (6596, 6610), True, 'import numpy as np\n'), ((6630, 6650), 'numpy.array', 'np.array', (['gallery_id'], {}), '(gallery_id)\n', (6638, 6650), True, 'import numpy as np\n'), ((6672, 6696), 'numpy.array', 'np.array', (['gallery_cam_id'], {}), '(gallery_cam_id)\n', (6680, 6696), True, 'import numpy as np\n'), ((6980, 6994), 'of_utils.avgmeter.AverageMeter', 'AverageMeter', ([], {}), '()\n', (6992, 6994), False, 'from of_utils.avgmeter import AverageMeter\n'), ((7014, 7028), 'of_utils.avgmeter.AverageMeter', 'AverageMeter', ([], {}), '()\n', (7026, 7028), False, 'from of_utils.avgmeter import AverageMeter\n'), ((7046, 7060), 'of_utils.avgmeter.AverageMeter', 'AverageMeter', ([], {}), '()\n', (7058, 7060), False, 'from of_utils.avgmeter import AverageMeter\n'), ((9214, 9248), 'os.path.isdir', 'os.path.isdir', (['args.model_load_dir'], {}), '(args.model_load_dir)\n', (9227, 9248), False, 'import os\n'), ((6510, 6521), 'time.time', 'time.time', ([], {}), '()\n', (6519, 6521), False, 'import time\n'), ((7092, 7155), 'data_loader.RandomIdentitySampler', 'RandomIdentitySampler', (['train_id', 'batch_size', 'args.num_instances'], {}), '(train_id, batch_size, args.num_instances)\n', (7113, 7155), False, 'from data_loader import Market1501, RandomIdentitySampler, ImageDataset\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 warnings
import numbers
from enum import Enum
from typing import List, Any, Tuple, Optional
import numpy as np
from PIL import Image
import math
try:
import accimage
except ImportError:
accimage = None
import oneflow as flow
from oneflow.framework.tensor import Tensor
from . import functional_pil as F_pil
from . import functional_tensor as F_t
class InterpolationMode(Enum):
r"""Interpolation modes
"""
NEAREST = "nearest"
BILINEAR = "bilinear"
BICUBIC = "bicubic"
# For PIL compatibility
BOX = "box"
HAMMING = "hamming"
LANCZOS = "lanczos"
def _interpolation_modes_from_int(i: int) -> InterpolationMode:
inverse_modes_mapping = {
0: InterpolationMode.NEAREST,
2: InterpolationMode.BILINEAR,
3: InterpolationMode.BICUBIC,
4: InterpolationMode.BOX,
5: InterpolationMode.HAMMING,
1: InterpolationMode.LANCZOS,
}
return inverse_modes_mapping[i]
pil_modes_mapping = {
InterpolationMode.NEAREST: 0,
InterpolationMode.BILINEAR: 2,
InterpolationMode.BICUBIC: 3,
InterpolationMode.BOX: 4,
InterpolationMode.HAMMING: 5,
InterpolationMode.LANCZOS: 1,
}
def _get_image_size(img: Tensor) -> List[int]:
"""Returns image size as [w, h]
"""
if isinstance(img, flow.Tensor):
return F_t._get_image_size(img)
return F_pil._get_image_size(img)
def _get_image_num_channels(img: Tensor) -> int:
"""Returns number of image channels
"""
if isinstance(img, flow.Tensor):
return F_t._get_image_num_channels(img)
return F_pil._get_image_num_channels(img)
def _is_pil_image(img: Any) -> bool:
if accimage is not None:
return isinstance(img, (Image.Image, accimage.Image))
else:
return isinstance(img, Image.Image)
def _is_numpy(img: Any) -> bool:
return isinstance(img, np.ndarray)
def _is_numpy_image(img: Any) -> bool:
return img.ndim in {2, 3}
def to_tensor(pic):
"""Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
See :class:`~transforms.ToTensor` for more details.
Args:
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
Returns:
Tensor: Converted image.
"""
if not (_is_pil_image(pic) or _is_numpy(pic)):
raise TypeError("pic should be PIL Image or ndarray. Got {}".format(type(pic)))
if _is_numpy(pic) and not _is_numpy_image(pic):
raise ValueError(
"pic should be 2/3 dimensional. Got {} dimensions.".format(pic.ndim)
)
# default_float_dtype = flow.get_default_dtype()
default_float_dtype = flow.float32
if isinstance(pic, np.ndarray):
# handle numpy array
if pic.ndim == 2:
pic = pic[:, :, None]
img = flow.Tensor(pic.transpose((2, 0, 1)))
# backward compatibility
if img.dtype == flow.int:
return img.to(dtype=default_float_dtype).div(255)
else:
return img
if accimage is not None and isinstance(pic, accimage.Image):
nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32)
pic.copyto(nppic)
return flow.Tensor(nppic).to(dtype=default_float_dtype)
# handle PIL Image
mode_to_nptype = {"I": np.int32, "I;16": np.int16, "F": np.float32}
if mode_to_nptype.get(pic.mode, np.uint8) == np.uint8:
dtype = flow.int32
else:
dtype = flow.float32
img = flow.Tensor(
np.array(pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True), dtype=dtype,
)
if pic.mode == "1":
img = 255 * img
img = flow.reshape(img, shape=(pic.size[1], pic.size[0], len(pic.getbands())))
# put it from HWC to CHW format
res = img.permute(2, 0, 1)
if img.dtype == flow.int:
res = res.to(dtype=default_float_dtype).div(255)
return res
def pil_to_tensor(pic):
"""Convert a ``PIL Image`` to a tensor of the same type.
See :class:`~vision.transforms.PILToTensor` for more details.
Args:
pic (PIL Image): Image to be converted to tensor.
Returns:
Tensor: Converted image.
"""
if not F_pil._is_pil_image(pic):
raise TypeError("pic should be PIL Image. Got {}".format(type(pic)))
if accimage is not None and isinstance(pic, accimage.Image):
# accimage format is always uint8 internally, so always return uint8 here
nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.uint8)
pic.copyto(nppic)
return flow.tensor(nppic)
# handle PIL Image
img = flow.tensor(np.asarray(pic))
img = img.view(pic.size[1], pic.size[0], len(pic.getbands()))
# put it from HWC to CHW format
img = img.permute((2, 0, 1))
return img
def convert_image_dtype(
image: flow.Tensor, dtype: flow.dtype = flow.float
) -> flow.Tensor:
"""Convert a tensor image to the given ``dtype`` and scale the values accordingly
This function does not support PIL Image.
Args:
image (flow.Tensor): Image to be converted
dtype (flow.dtype): Desired data type of the output
Returns:
Tensor: Converted image
.. note::
When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly.
If converted back and forth, this mismatch has no effect.
Raises:
RuntimeError: When trying to cast :class:`flow.float32` to :class:`flow.int32` or :class:`flow.int64` as
well as for trying to cast :class:`flow.float64` to :class:`flow.int64`. These conversions might lead to
overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range
of the integer ``dtype``.
"""
if not isinstance(image, flow.Tensor):
raise TypeError("Input img should be Tensor Image")
return F_t.convert_image_dtype(image, dtype)
def normalize(
tensor: Tensor, mean: List[float], std: List[float], inplace: bool = False
) -> Tensor:
"""Normalize a float tensor image with mean and standard deviation.
This transform does not support PIL Image.
.. note::
This transform acts out of place by default, i.e., it does not mutates the input tensor.
See :class:`~transforms.Normalize` for more details.
Args:
tensor (Tensor): Float tensor image of size (C, H, W) or (B, C, H, W) to be normalized.
mean (sequence): Sequence of means for each channel.
std (sequence): Sequence of standard deviations for each channel.
inplace(bool,optional): Bool to make this operation inplace.
Returns:
Tensor: Normalized Tensor image.
"""
if not isinstance(tensor, flow.Tensor):
raise TypeError(
"Input tensor should be a oneflow tensor. Got {}.".format(type(tensor))
)
if not tensor.dtype == flow.float:
raise TypeError(
"Input tensor should be a float tensor. Got {}.".format(tensor.dtype)
)
if tensor.ndim < 3:
raise ValueError(
"Expected tensor to be a tensor image of size (..., C, H, W). Got tensor.size() = "
"{}.".format(tensor.size())
)
if not inplace:
tensor = tensor.clone()
dtype = tensor.dtype
mean = flow.tensor(mean, dtype=dtype, device=tensor.device)
std = flow.tensor(std, dtype=dtype, device=tensor.device)
# TODO: use tensor.any()
# if (std == 0).any():
if std.eq(0).sum().numpy() > 0:
raise ValueError(
"std evaluated to zero after conversion to {}, leading to division by zero.".format(
dtype
)
)
if mean.ndim == 1:
mean = mean.reshape(-1, 1, 1)
if std.ndim == 1:
std = std.reshape(-1, 1, 1)
tensor = tensor.sub(mean).div(std)
# tensor.sub_(mean).div_(std)
return tensor
def resize(
img: Tensor,
size: List[int],
interpolation: InterpolationMode = InterpolationMode.BILINEAR,
) -> Tensor:
r"""Resize the input image to the given size.
If the image is oneflow Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
Args:
img (PIL Image or Tensor): Image to be resized.
size (sequence or int): Desired output size. If size is a sequence like
(h, w), the output size will be matched to this. If size is an int,
the smaller edge of the image will be matched to this number maintaining
the aspect ratio. i.e, if height > width, then image will be rescaled to
:math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`.
interpolation (InterpolationMode): Desired interpolation enum defined by
:class:`flow.utils.vision.transforms.InterpolationMode`.
Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``,
``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable.
Returns:
PIL Image or Tensor: Resized image.
"""
# Backward compatibility with integer value
if isinstance(interpolation, int):
warnings.warn(
"Argument interpolation should be of type InterpolationMode instead of int. "
"Please, use InterpolationMode enum."
)
interpolation = _interpolation_modes_from_int(interpolation)
if not isinstance(interpolation, InterpolationMode):
raise TypeError("Argument interpolation should be a InterpolationMode")
if not isinstance(img, (flow.Tensor, flow._oneflow_internal.Tensor)):
pil_interpolation = pil_modes_mapping[interpolation]
return F_pil.resize(img, size=size, interpolation=pil_interpolation)
return F_t.resize(img, size=size, interpolation=interpolation.value)
def scale(*args, **kwargs):
warnings.warn(
"The use of the transforms.Scale transform is deprecated, "
+ "please use transforms.Resize instead."
)
return resize(*args, **kwargs)
def pad(
img: Tensor, padding: List[int], fill: int = 0, padding_mode: str = "constant"
) -> Tensor:
r"""Pad the given image on all sides with the given "pad" value.
If the image is oneflow Tensor, it is expected
to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric,
at most 3 leading dimensions for mode edge,
and an arbitrary number of leading dimensions for mode constant
Args:
img (PIL Image or Tensor): Image to be padded.
padding (int or sequence): Padding on each border. If a single int is provided this
is used to pad all borders. If sequence of length 2 is provided this is the padding
on left/right and top/bottom respectively. If a sequence of length 4 is provided
this is the padding for the left, top, right and bottom borders respectively.
fill (number or str or tuple): Pixel fill value for constant fill. Default is 0.
If a tuple of length 3, it is used to fill R, G, B channels respectively.
This value is only used when the padding_mode is constant.
Only number is supported for oneflow Tensor.
Only int or str or tuple value is supported for PIL Image.
padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
Default is constant.
- constant: pads with a constant value, this value is specified with fill
- edge: pads with the last value at the edge of the image.
If input a 5D oneflow Tensor, the last 3 dimensions will be padded instead of the last 2
- reflect: pads with reflection of image without repeating the last value on the edge.
For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
will result in [3, 2, 1, 2, 3, 4, 3, 2]
- symmetric: pads with reflection of image repeating the last value on the edge.
For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
will result in [2, 1, 1, 2, 3, 4, 4, 3]
Returns:
PIL Image or Tensor: Padded image.
"""
if not isinstance(img, flow.Tensor):
return F_pil.pad(img, padding=padding, fill=fill, padding_mode=padding_mode)
return F_t.pad(img, padding=padding, fill=fill, padding_mode=padding_mode)
def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor:
"""Crop the given image at specified location and output size.
If the image is oneflow Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
If image size is smaller than output size along any edge, image is padded with 0 and then cropped.
Args:
img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image.
top (int): Vertical component of the top left corner of the crop box.
left (int): Horizontal component of the top left corner of the crop box.
height (int): Height of the crop box.
width (int): Width of the crop box.
Returns:
PIL Image or Tensor: Cropped image.
"""
if not isinstance(img, flow.Tensor):
return F_pil.crop(img, top, left, height, width)
return F_t.crop(img, top, left, height, width)
def center_crop(img: Tensor, output_size: List[int]) -> Tensor:
"""Crops the given image at the center.
If the image is oneflow Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
If image size is smaller than output size along any edge, image is padded with 0 and then center cropped.
Args:
img (PIL Image or Tensor): Image to be cropped.
output_size (sequence or int): (height, width) of the crop box. If int or sequence with single int,
it is used for both directions.
Returns:
PIL Image or Tensor: Cropped image.
"""
if isinstance(output_size, numbers.Number):
output_size = (int(output_size), int(output_size))
elif isinstance(output_size, (tuple, list)) and len(output_size) == 1:
output_size = (output_size[0], output_size[0])
image_width, image_height = _get_image_size(img)
crop_height, crop_width = output_size
if crop_width > image_width or crop_height > image_height:
padding_ltrb = [
(crop_width - image_width) // 2 if crop_width > image_width else 0,
(crop_height - image_height) // 2 if crop_height > image_height else 0,
(crop_width - image_width + 1) // 2 if crop_width > image_width else 0,
(crop_height - image_height + 1) // 2 if crop_height > image_height else 0,
]
img = pad(img, padding_ltrb, fill=0) # PIL uses fill value 0
image_width, image_height = _get_image_size(img)
if crop_width == image_width and crop_height == image_height:
return img
crop_top = int(round((image_height - crop_height) / 2.0))
crop_left = int(round((image_width - crop_width) / 2.0))
return crop(img, crop_top, crop_left, crop_height, crop_width)
def resized_crop(
img: Tensor,
top: int,
left: int,
height: int,
width: int,
size: List[int],
interpolation: InterpolationMode = InterpolationMode.BILINEAR,
) -> Tensor:
"""Crop the given image and resize it to desired size.
If the image is oneflow Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
Notably used in :class:`~vision.transforms.RandomResizedCrop`.
Args:
img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image.
top (int): Vertical component of the top left corner of the crop box.
left (int): Horizontal component of the top left corner of the crop box.
height (int): Height of the crop box.
width (int): Width of the crop box.
size (sequence or int): Desired output size. Same semantics as ``resize``.
interpolation (InterpolationMode): Desired interpolation enum defined by
:class:`vision.transforms.InterpolationMode`.
Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``,
``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable.
Returns:
PIL Image or Tensor: Cropped image.
"""
img = crop(img, top, left, height, width)
img = resize(img, size, interpolation)
return img
def hflip(img: Tensor) -> Tensor:
"""Horizontally flip the given image.
Args:
img (PIL Image or Tensor): Image to be flipped. If img
is a Tensor, it is expected to be in [..., H, W] format,
where ... means it can have an arbitrary number of leading
dimensions.
Returns:
PIL Image or Tensor: Horizontally flipped image.
"""
if not isinstance(img, flow.Tensor):
return F_pil.hflip(img)
return F_t.hflip(img)
def vflip(img: Tensor) -> Tensor:
"""Vertically flip the given image.
Args:
img (PIL Image or Tensor): Image to be flipped. If img
is a Tensor, it is expected to be in [..., H, W] format,
where ... means it can have an arbitrary number of leading
dimensions.
Returns:
PIL Image or Tensor: Vertically flipped image.
"""
if not isinstance(img, flow.Tensor):
return F_pil.vflip(img)
return F_t.vflip(img)
def five_crop(
img: Tensor, size: List[int]
) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
"""Crop the given image into four corners and the central crop.
If the image is oneflow Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
.. Note::
This transform returns a tuple of images and there may be a
mismatch in the number of inputs and targets your ``Dataset`` returns.
Args:
img (PIL Image or Tensor): Image to be cropped.
size (sequence or int): Desired output size of the crop. If size is an
int instead of sequence like (h, w), a square crop (size, size) is
made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
Returns:
tuple: tuple (tl, tr, bl, br, center)
Corresponding top left, top right, bottom left, bottom right and center crop.
"""
if isinstance(size, numbers.Number):
size = (int(size), int(size))
elif isinstance(size, (tuple, list)) and len(size) == 1:
size = (size[0], size[0])
if len(size) != 2:
raise ValueError("Please provide only two dimensions (h, w) for size.")
image_width, image_height = _get_image_size(img)
crop_height, crop_width = size
if crop_width > image_width or crop_height > image_height:
msg = "Requested crop size {} is bigger than input size {}"
raise ValueError(msg.format(size, (image_height, image_width)))
tl = crop(img, 0, 0, crop_height, crop_width)
tr = crop(img, 0, image_width - crop_width, crop_height, crop_width)
bl = crop(img, image_height - crop_height, 0, crop_height, crop_width)
br = crop(
img,
image_height - crop_height,
image_width - crop_width,
crop_height,
crop_width,
)
center = center_crop(img, [crop_height, crop_width])
return tl, tr, bl, br, center
def ten_crop(img: Tensor, size: List[int], vertical_flip: bool = False) -> List[Tensor]:
"""Generate ten cropped images from the given image.
Crop the given image into four corners and the central crop plus the
flipped version of these (horizontal flipping is used by default).
If the image is oneflow Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
.. Note::
This transform returns a tuple of images and there may be a
mismatch in the number of inputs and targets your ``Dataset`` returns.
Args:
img (PIL Image or Tensor): Image to be cropped.
size (sequence or int): Desired output size of the crop. If size is an
int instead of sequence like (h, w), a square crop (size, size) is
made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
vertical_flip (bool): Use vertical flipping instead of horizontal
Returns:
tuple: tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip, br_flip, center_flip)
Corresponding top left, top right, bottom left, bottom right and
center crop and same for the flipped image.
"""
if isinstance(size, numbers.Number):
size = (int(size), int(size))
elif isinstance(size, (tuple, list)) and len(size) == 1:
size = (size[0], size[0])
if len(size) != 2:
raise ValueError("Please provide only two dimensions (h, w) for size.")
first_five = five_crop(img, size)
if vertical_flip:
img = vflip(img)
else:
img = hflip(img)
second_five = five_crop(img, size)
return first_five + second_five
def _get_inverse_affine_matrix(
center: List[float],
angle: float,
translate: List[float],
scale: float,
shear: List[float],
) -> List[float]:
# Helper method to compute inverse matrix for affine transformation
# As it is explained in PIL.Image.rotate
# We need compute INVERSE of affine transformation matrix: M = T * C * RSS * C^-1
# where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1]
# C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1]
# RSS is rotation with scale and shear matrix
# RSS(a, s, (sx, sy)) =
# = R(a) * S(s) * SHy(sy) * SHx(sx)
# = [ s*cos(a - sy)/cos(sy), s*(-cos(a - sy)*tan(x)/cos(y) - sin(a)), 0 ]
# [ s*sin(a + sy)/cos(sy), s*(-sin(a - sy)*tan(x)/cos(y) + cos(a)), 0 ]
# [ 0 , 0 , 1 ]
#
# where R is a rotation matrix, S is a scaling matrix, and SHx and SHy are the shears:
# SHx(s) = [1, -tan(s)] and SHy(s) = [1 , 0]
# [0, 1 ] [-tan(s), 1]
#
# Thus, the inverse is M^-1 = C * RSS^-1 * C^-1 * T^-1
rot = math.radians(angle)
sx, sy = [math.radians(s) for s in shear]
cx, cy = center
tx, ty = translate
# RSS without scaling
a = math.cos(rot - sy) / math.cos(sy)
b = -math.cos(rot - sy) * math.tan(sx) / math.cos(sy) - math.sin(rot)
c = math.sin(rot - sy) / math.cos(sy)
d = -math.sin(rot - sy) * math.tan(sx) / math.cos(sy) + math.cos(rot)
# Inverted rotation matrix with scale and shear
# det([[a, b], [c, d]]) == 1, since det(rotation) = 1 and det(shear) = 1
matrix = [d, -b, 0.0, -c, a, 0.0]
matrix = [x / scale for x in matrix]
# Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1
matrix[2] += matrix[0] * (-cx - tx) + matrix[1] * (-cy - ty)
matrix[5] += matrix[3] * (-cx - tx) + matrix[4] * (-cy - ty)
# Apply center translation: C * RSS^-1 * C^-1 * T^-1
matrix[2] += cx
matrix[5] += cy
return matrix
def rotate(
img: Tensor,
angle: float,
interpolation: InterpolationMode = InterpolationMode.NEAREST,
expand: bool = False,
center: Optional[List[int]] = None,
fill: Optional[List[float]] = None,
resample: Optional[int] = None,
) -> Tensor:
"""Rotate the image by angle.
If the image is oneflow Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
Args:
img (PIL Image or Tensor): image to be rotated.
angle (number): rotation angle value in degrees, counter-clockwise.
interpolation (InterpolationMode): Desired interpolation enum defined by
:class:`flow.utils.vision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable.
expand (bool, optional): Optional expansion flag.
If true, expands the output image to make it large enough to hold the entire rotated image.
If false or omitted, make the output image the same size as the input image.
Note that the expand flag assumes rotation around the center and no translation.
center (sequence, optional): Optional center of rotation. Origin is the upper left corner.
Default is the center of the image.
fill (sequence or number, optional): Pixel fill value for the area outside the transformed
image. If given a number, the value is used for all bands respectively.
Returns:
PIL Image or Tensor: Rotated image.
.. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
"""
if resample is not None:
warnings.warn(
"Argument resample is deprecated and will be removed since v0.10.0. Please, use interpolation instead"
)
interpolation = _interpolation_modes_from_int(resample)
# Backward compatibility with integer value
if isinstance(interpolation, int):
warnings.warn(
"Argument interpolation should be of type InterpolationMode instead of int. "
"Please, use InterpolationMode enum."
)
interpolation = _interpolation_modes_from_int(interpolation)
if not isinstance(angle, (int, float)):
raise TypeError("Argument angle should be int or float")
if center is not None and not isinstance(center, (list, tuple)):
raise TypeError("Argument center should be a sequence")
if not isinstance(interpolation, InterpolationMode):
raise TypeError("Argument interpolation should be a InterpolationMode")
if not isinstance(img, flow.Tensor):
pil_interpolation = pil_modes_mapping[interpolation]
return F_pil.rotate(
img,
angle=angle,
interpolation=pil_interpolation,
expand=expand,
center=center,
fill=fill,
)
center_f = [0.0, 0.0]
if center is not None:
img_size = _get_image_size(img)
# Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center.
center_f = [1.0 * (c - s * 0.5) for c, s in zip(center, img_size)]
# due to current incoherence of rotation angle direction between affine and rotate implementations
# we need to set -angle.
matrix = _get_inverse_affine_matrix(center_f, -angle, [0.0, 0.0], 1.0, [0.0, 0.0])
raise NotImplementedError("Tensor rotate is not implemented yet!")
return F_t.rotate(
img, matrix=matrix, interpolation=interpolation.value, expand=expand, fill=fill
)
| [
"oneflow.Tensor",
"oneflow.tensor"
] | [((7879, 7931), 'oneflow.tensor', 'flow.tensor', (['mean'], {'dtype': 'dtype', 'device': 'tensor.device'}), '(mean, dtype=dtype, device=tensor.device)\n', (7890, 7931), True, 'import oneflow as flow\n'), ((7942, 7993), 'oneflow.tensor', 'flow.tensor', (['std'], {'dtype': 'dtype', 'device': 'tensor.device'}), '(std, dtype=dtype, device=tensor.device)\n', (7953, 7993), True, 'import oneflow as flow\n'), ((10597, 10717), 'warnings.warn', 'warnings.warn', (["('The use of the transforms.Scale transform is deprecated, ' +\n 'please use transforms.Resize instead.')"], {}), "('The use of the transforms.Scale transform is deprecated, ' +\n 'please use transforms.Resize instead.')\n", (10610, 10717), False, 'import warnings\n'), ((23361, 23380), 'math.radians', 'math.radians', (['angle'], {}), '(angle)\n', (23373, 23380), False, 'import math\n'), ((3657, 3722), 'numpy.zeros', 'np.zeros', (['[pic.channels, pic.height, pic.width]'], {'dtype': 'np.float32'}), '([pic.channels, pic.height, pic.width], dtype=np.float32)\n', (3665, 3722), True, 'import numpy as np\n'), ((5009, 5072), 'numpy.zeros', 'np.zeros', (['[pic.channels, pic.height, pic.width]'], {'dtype': 'np.uint8'}), '([pic.channels, pic.height, pic.width], dtype=np.uint8)\n', (5017, 5072), True, 'import numpy as np\n'), ((5114, 5132), 'oneflow.tensor', 'flow.tensor', (['nppic'], {}), '(nppic)\n', (5125, 5132), True, 'import oneflow as flow\n'), ((5179, 5194), 'numpy.asarray', 'np.asarray', (['pic'], {}), '(pic)\n', (5189, 5194), True, 'import numpy as np\n'), ((9904, 10041), 'warnings.warn', 'warnings.warn', (['"""Argument interpolation should be of type InterpolationMode instead of int. Please, use InterpolationMode enum."""'], {}), "(\n 'Argument interpolation should be of type InterpolationMode instead of int. Please, use InterpolationMode enum.'\n )\n", (9917, 10041), False, 'import warnings\n'), ((23395, 23410), 'math.radians', 'math.radians', (['s'], {}), '(s)\n', (23407, 23410), False, 'import math\n'), ((23506, 23524), 'math.cos', 'math.cos', (['(rot - sy)'], {}), '(rot - sy)\n', (23514, 23524), False, 'import math\n'), ((23527, 23539), 'math.cos', 'math.cos', (['sy'], {}), '(sy)\n', (23535, 23539), False, 'import math\n'), ((23600, 23613), 'math.sin', 'math.sin', (['rot'], {}), '(rot)\n', (23608, 23613), False, 'import math\n'), ((23622, 23640), 'math.sin', 'math.sin', (['(rot - sy)'], {}), '(rot - sy)\n', (23630, 23640), False, 'import math\n'), ((23643, 23655), 'math.cos', 'math.cos', (['sy'], {}), '(sy)\n', (23651, 23655), False, 'import math\n'), ((23716, 23729), 'math.cos', 'math.cos', (['rot'], {}), '(rot)\n', (23724, 23729), False, 'import math\n'), ((26137, 26264), 'warnings.warn', 'warnings.warn', (['"""Argument resample is deprecated and will be removed since v0.10.0. Please, use interpolation instead"""'], {}), "(\n 'Argument resample is deprecated and will be removed since v0.10.0. Please, use interpolation instead'\n )\n", (26150, 26264), False, 'import warnings\n'), ((26437, 26574), 'warnings.warn', 'warnings.warn', (['"""Argument interpolation should be of type InterpolationMode instead of int. Please, use InterpolationMode enum."""'], {}), "(\n 'Argument interpolation should be of type InterpolationMode instead of int. Please, use InterpolationMode enum.'\n )\n", (26450, 26574), False, 'import warnings\n'), ((23585, 23597), 'math.cos', 'math.cos', (['sy'], {}), '(sy)\n', (23593, 23597), False, 'import math\n'), ((23701, 23713), 'math.cos', 'math.cos', (['sy'], {}), '(sy)\n', (23709, 23713), False, 'import math\n'), ((3764, 3782), 'oneflow.Tensor', 'flow.Tensor', (['nppic'], {}), '(nppic)\n', (3775, 3782), True, 'import oneflow as flow\n'), ((23570, 23582), 'math.tan', 'math.tan', (['sx'], {}), '(sx)\n', (23578, 23582), False, 'import math\n'), ((23686, 23698), 'math.tan', 'math.tan', (['sx'], {}), '(sx)\n', (23694, 23698), False, 'import math\n'), ((23549, 23567), 'math.cos', 'math.cos', (['(rot - sy)'], {}), '(rot - sy)\n', (23557, 23567), False, 'import math\n'), ((23665, 23683), 'math.sin', 'math.sin', (['(rot - sy)'], {}), '(rot - sy)\n', (23673, 23683), False, 'import math\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 as flow
import os
import oneflow.unittest
from oneflow.test_utils.test_util import GenArgList
@flow.unittest.skip_unless_1n2d()
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
class TestConsistentCastModule_1n2d(flow.unittest.TestCase):
def test_check_meta_consistency(test_case):
if os.getenv("RANK") == "0":
x = flow.ones((16, 16), device=flow.device("cuda"), dtype=flow.int32)
else:
x = flow.zeros((1,), device=flow.device("cuda"), dtype=flow.float)
placement = flow.placement("cuda", ranks=[0])
sbp = (flow.sbp.broadcast,)
y = x.to_global(placement=placement, sbp=sbp)
y.check_meta_consistency()
y = y.to_global(sbp=flow.sbp.split(0))
y.check_meta_consistency()
if __name__ == "__main__":
unittest.main()
| [
"oneflow.sbp.split",
"oneflow.device",
"oneflow.unittest.skip_unless_1n2d",
"oneflow.placement"
] | [((776, 808), 'oneflow.unittest.skip_unless_1n2d', 'flow.unittest.skip_unless_1n2d', ([], {}), '()\n', (806, 808), True, 'import oneflow as flow\n'), ((826, 860), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (835, 860), False, 'import os\n'), ((1500, 1515), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1513, 1515), False, 'import unittest\n'), ((1226, 1259), 'oneflow.placement', 'flow.placement', (['"""cuda"""'], {'ranks': '[0]'}), "('cuda', ranks=[0])\n", (1240, 1259), True, 'import oneflow as flow\n'), ((1005, 1022), 'os.getenv', 'os.getenv', (['"""RANK"""'], {}), "('RANK')\n", (1014, 1022), False, 'import os\n'), ((1413, 1430), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (1427, 1430), True, 'import oneflow as flow\n'), ((1074, 1093), 'oneflow.device', 'flow.device', (['"""cuda"""'], {}), "('cuda')\n", (1085, 1093), True, 'import oneflow as flow\n'), ((1167, 1186), 'oneflow.device', 'flow.device', (['"""cuda"""'], {}), "('cuda')\n", (1178, 1186), True, 'import oneflow as flow\n')] |
import oneflow as flow
from flowvision.layers.attention import SEModule
def test_se():
x = flow.randn(1, 48, 16, 16)
se = SEModule(48)
assert se(x).shape == x.shape
if __name__ == "__main__":
test_se()
| [
"oneflow.randn"
] | [((97, 122), 'oneflow.randn', 'flow.randn', (['(1)', '(48)', '(16)', '(16)'], {}), '(1, 48, 16, 16)\n', (107, 122), True, 'import oneflow as flow\n'), ((132, 144), 'flowvision.layers.attention.SEModule', 'SEModule', (['(48)'], {}), '(48)\n', (140, 144), False, 'from flowvision.layers.attention import SEModule\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 numpy as np
import argparse
import cv2
import oneflow as flow
import oneflow.typing as tp
import style_model
def float_list(x):
return list(map(float, x.split(",")))
def load_image(image_path):
im = cv2.imread(image_path)
im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
im = np.transpose(im, (2, 0, 1))
im = np.expand_dims(im, axis=0)
im = np.transpose(im, (0, 2, 3, 1))
return np.ascontiguousarray(im, "float32")
def recover_image(im):
im = np.squeeze(im)
print(im.shape)
# im = np.transpose(im, (1, 2, 0))
im = cv2.cvtColor(np.float32(im), cv2.COLOR_RGB2BGR)
return im.astype(np.uint8)
flow.config.enable_legacy_model_io(True)
def main(args):
input_image = load_image(args.input_image_path)
height = input_image.shape[1]
width = input_image.shape[2]
flow.env.init()
config = flow.function_config()
config.default_placement_scope(flow.scope.placement(args.backend, "0:0"))
@flow.global_function("predict", function_config=config)
def PredictNet(
image: tp.Numpy.Placeholder((1, height, width, 3), dtype=flow.float32)
) -> tp.Numpy:
style_out = style_model.styleNet(image, trainable=True, backend=args.backend)
return style_out
print("===============================>load begin")
# flow.load_variables(flow.checkpoint.get(args.model_load_dir))
flow.train.CheckPoint().load(args.model_load_dir)
print("===============================>load end")
import datetime
a = datetime.datetime.now()
print("predict begin")
style_out = PredictNet(input_image)
style_out = np.clip(style_out, 0, 255)
print("predict end")
b = datetime.datetime.now()
c = b - a
print("time: %s ms, height: %d, width: %d" % (c.microseconds / 1000, height, width))
cv2.imwrite(args.output_image_path, recover_image(style_out))
# flow.checkpoint.save("./stylenet")
def get_parser(parser=None):
parser = argparse.ArgumentParser("flags for neural style")
parser.add_argument(
"--backend",
type=str,
default="gpu",
help="gpu or cambricon"
)
parser.add_argument(
"--input_image_path", type=str, default="test_img/tiger.jpg", help="image path"
)
parser.add_argument(
"--output_image_path", type=str, default="test_img/tiger.jpg", help="image path"
)
parser.add_argument(
"--model_load_dir", type=str, default="", help="model save directory"
)
return parser
if __name__ == "__main__":
parser = get_parser()
args = parser.parse_args()
main(args)
| [
"oneflow.env.init",
"oneflow.scope.placement",
"oneflow.config.enable_legacy_model_io",
"oneflow.function_config",
"oneflow.typing.Numpy.Placeholder",
"oneflow.global_function",
"oneflow.train.CheckPoint"
] | [((1235, 1275), 'oneflow.config.enable_legacy_model_io', 'flow.config.enable_legacy_model_io', (['(True)'], {}), '(True)\n', (1269, 1275), True, 'import oneflow as flow\n'), ((809, 831), 'cv2.imread', 'cv2.imread', (['image_path'], {}), '(image_path)\n', (819, 831), False, 'import cv2\n'), ((841, 876), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2RGB'], {}), '(im, cv2.COLOR_BGR2RGB)\n', (853, 876), False, 'import cv2\n'), ((886, 913), 'numpy.transpose', 'np.transpose', (['im', '(2, 0, 1)'], {}), '(im, (2, 0, 1))\n', (898, 913), True, 'import numpy as np\n'), ((923, 949), 'numpy.expand_dims', 'np.expand_dims', (['im'], {'axis': '(0)'}), '(im, axis=0)\n', (937, 949), True, 'import numpy as np\n'), ((959, 989), 'numpy.transpose', 'np.transpose', (['im', '(0, 2, 3, 1)'], {}), '(im, (0, 2, 3, 1))\n', (971, 989), True, 'import numpy as np\n'), ((1001, 1036), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['im', '"""float32"""'], {}), "(im, 'float32')\n", (1021, 1036), True, 'import numpy as np\n'), ((1071, 1085), 'numpy.squeeze', 'np.squeeze', (['im'], {}), '(im)\n', (1081, 1085), True, 'import numpy as np\n'), ((1417, 1432), 'oneflow.env.init', 'flow.env.init', ([], {}), '()\n', (1430, 1432), True, 'import oneflow as flow\n'), ((1446, 1468), 'oneflow.function_config', 'flow.function_config', ([], {}), '()\n', (1466, 1468), True, 'import oneflow as flow\n'), ((1553, 1608), 'oneflow.global_function', 'flow.global_function', (['"""predict"""'], {'function_config': 'config'}), "('predict', function_config=config)\n", (1573, 1608), True, 'import oneflow as flow\n'), ((2101, 2124), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2122, 2124), False, 'import datetime\n'), ((2209, 2235), 'numpy.clip', 'np.clip', (['style_out', '(0)', '(255)'], {}), '(style_out, 0, 255)\n', (2216, 2235), True, 'import numpy as np\n'), ((2270, 2293), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2291, 2293), False, 'import datetime\n'), ((2550, 2599), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""flags for neural style"""'], {}), "('flags for neural style')\n", (2573, 2599), False, 'import argparse\n'), ((1167, 1181), 'numpy.float32', 'np.float32', (['im'], {}), '(im)\n', (1177, 1181), True, 'import numpy as np\n'), ((1504, 1545), 'oneflow.scope.placement', 'flow.scope.placement', (['args.backend', '"""0:0"""'], {}), "(args.backend, '0:0')\n", (1524, 1545), True, 'import oneflow as flow\n'), ((1747, 1812), 'style_model.styleNet', 'style_model.styleNet', (['image'], {'trainable': '(True)', 'backend': 'args.backend'}), '(image, trainable=True, backend=args.backend)\n', (1767, 1812), False, 'import style_model\n'), ((1644, 1707), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', (['(1, height, width, 3)'], {'dtype': 'flow.float32'}), '((1, height, width, 3), dtype=flow.float32)\n', (1664, 1707), True, 'import oneflow.typing as tp\n'), ((1967, 1990), 'oneflow.train.CheckPoint', 'flow.train.CheckPoint', ([], {}), '()\n', (1988, 1990), 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 unittest
import numpy as np
import oneflow as flow
import oneflow.unittest
from oneflow.test_utils.automated_test_util import *
from test_nms import create_tensors_with_iou
from test_nms import nms_np
def _test_nms(test_case, placement, sbp):
iou = 0.5
boxes, scores = create_tensors_with_iou(800, iou)
global_boxes = flow.tensor(boxes, dtype=flow.float32).to_global(
placement=flow.env.all_device_placement("cpu"), sbp=flow.sbp.broadcast
)
np_boxes = global_boxes.numpy()
global_boxes = global_boxes.to_global(placement=placement, sbp=sbp)
global_scores = flow.tensor(scores, dtype=flow.float32).to_global(
placement=flow.env.all_device_placement("cpu"), sbp=flow.sbp.broadcast
)
np_scores = global_scores.numpy()
global_scores = global_scores.to_global(placement=placement, sbp=sbp)
keep_np = nms_np(np_boxes, np_scores, iou)
keep = flow.nms(global_boxes, global_scores, iou)
test_case.assertTrue(np.allclose(keep.numpy(), keep_np))
class TestNMS(flow.unittest.TestCase):
@globaltest
def test_nms(test_case):
for placement in all_placement():
# TODO: nms only has cuda kernel at now.
if placement.type == "cpu":
continue
for sbp in all_sbp(placement, max_dim=1):
_test_nms(test_case, placement, sbp)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.nms",
"oneflow.tensor",
"oneflow.env.all_device_placement"
] | [((877, 910), 'test_nms.create_tensors_with_iou', 'create_tensors_with_iou', (['(800)', 'iou'], {}), '(800, iou)\n', (900, 910), False, 'from test_nms import create_tensors_with_iou\n'), ((1458, 1490), 'test_nms.nms_np', 'nms_np', (['np_boxes', 'np_scores', 'iou'], {}), '(np_boxes, np_scores, iou)\n', (1464, 1490), False, 'from test_nms import nms_np\n'), ((1503, 1545), 'oneflow.nms', 'flow.nms', (['global_boxes', 'global_scores', 'iou'], {}), '(global_boxes, global_scores, iou)\n', (1511, 1545), True, 'import oneflow as flow\n'), ((1993, 2008), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2006, 2008), False, 'import unittest\n'), ((931, 969), 'oneflow.tensor', 'flow.tensor', (['boxes'], {'dtype': 'flow.float32'}), '(boxes, dtype=flow.float32)\n', (942, 969), True, 'import oneflow as flow\n'), ((999, 1035), 'oneflow.env.all_device_placement', 'flow.env.all_device_placement', (['"""cpu"""'], {}), "('cpu')\n", (1028, 1035), True, 'import oneflow as flow\n'), ((1195, 1234), 'oneflow.tensor', 'flow.tensor', (['scores'], {'dtype': 'flow.float32'}), '(scores, dtype=flow.float32)\n', (1206, 1234), True, 'import oneflow as flow\n'), ((1264, 1300), 'oneflow.env.all_device_placement', 'flow.env.all_device_placement', (['"""cpu"""'], {}), "('cpu')\n", (1293, 1300), 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 unittest
import numpy as np
from oneflow.compatible import single_client as flow
from oneflow.compatible.single_client import typing as oft
from typing import Tuple
func_config = flow.FunctionConfig()
func_config.default_data_type(flow.float)
def GenerateTest(test_case, shape, num_inputs):
@flow.global_function(function_config=func_config)
def AddJob(xs: Tuple[(oft.Numpy.Placeholder(shape),) * num_inputs]):
return flow.math.add_n(xs)
inputs = tuple(np.random.rand(*shape).astype(np.float32) for i in range(num_inputs))
r = AddJob(inputs).get().numpy()
test_case.assertTrue(np.allclose(r, sum(inputs)))
@flow.unittest.skip_unless_1n1d()
class TestAddN(flow.unittest.TestCase):
def test_naive(test_case):
@flow.global_function(function_config=func_config)
def AddJob(xs: Tuple[(oft.Numpy.Placeholder((5, 2)),) * 3]):
return flow.math.add_n(xs)
inputs = tuple(np.random.rand(5, 2).astype(np.float32) for i in range(3))
r = AddJob(inputs).get().numpy()
test_case.assertTrue(np.allclose(r, sum(inputs)))
def test_2_inputs(test_case):
GenerateTest(test_case, (64, 64), 2)
def test_3_inputs(test_case):
GenerateTest(test_case, (64, 64), 3)
def test_4_inputs(test_case):
GenerateTest(test_case, (64, 64), 4)
def test_5_inputs(test_case):
GenerateTest(test_case, (64, 64), 5)
def test_6_inputs(test_case):
GenerateTest(test_case, (64, 64), 6)
def test_7_inputs(test_case):
GenerateTest(test_case, (64, 64), 7)
def test_8_inputs(test_case):
GenerateTest(test_case, (64, 64), 8)
def test_9_inputs(test_case):
GenerateTest(test_case, (64, 64), 9)
def test_10_inputs(test_case):
GenerateTest(test_case, (64, 64), 10)
def test_11_inputs(test_case):
GenerateTest(test_case, (64, 64), 11)
def test_12_inputs(test_case):
GenerateTest(test_case, (64, 64), 12)
def test_13_inputs(test_case):
GenerateTest(test_case, (64, 64), 13)
def test_14_inputs(test_case):
GenerateTest(test_case, (64, 64), 14)
def test_15_inputs(test_case):
GenerateTest(test_case, (64, 64), 15)
def test_16_inputs(test_case):
GenerateTest(test_case, (64, 64), 16)
def test_100_inputs(test_case):
GenerateTest(test_case, (64, 64), 100)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.compatible.single_client.unittest.skip_unless_1n1d",
"oneflow.compatible.single_client.FunctionConfig",
"oneflow.compatible.single_client.math.add_n",
"oneflow.compatible.single_client.typing.Numpy.Placeholder",
"oneflow.compatible.single_client.global_function"
] | [((777, 798), 'oneflow.compatible.single_client.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (796, 798), True, 'from oneflow.compatible import single_client as flow\n'), ((1238, 1270), 'oneflow.compatible.single_client.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (1268, 1270), True, 'from oneflow.compatible import single_client as flow\n'), ((896, 945), 'oneflow.compatible.single_client.global_function', 'flow.global_function', ([], {'function_config': 'func_config'}), '(function_config=func_config)\n', (916, 945), True, 'from oneflow.compatible import single_client as flow\n'), ((3022, 3037), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3035, 3037), False, 'import unittest\n'), ((1034, 1053), 'oneflow.compatible.single_client.math.add_n', 'flow.math.add_n', (['xs'], {}), '(xs)\n', (1049, 1053), True, 'from oneflow.compatible import single_client as flow\n'), ((1351, 1400), 'oneflow.compatible.single_client.global_function', 'flow.global_function', ([], {'function_config': 'func_config'}), '(function_config=func_config)\n', (1371, 1400), True, 'from oneflow.compatible import single_client as flow\n'), ((1489, 1508), 'oneflow.compatible.single_client.math.add_n', 'flow.math.add_n', (['xs'], {}), '(xs)\n', (1504, 1508), True, 'from oneflow.compatible import single_client as flow\n'), ((1074, 1096), 'numpy.random.rand', 'np.random.rand', (['*shape'], {}), '(*shape)\n', (1088, 1096), True, 'import numpy as np\n'), ((972, 1000), 'oneflow.compatible.single_client.typing.Numpy.Placeholder', 'oft.Numpy.Placeholder', (['shape'], {}), '(shape)\n', (993, 1000), True, 'from oneflow.compatible.single_client import typing as oft\n'), ((1533, 1553), 'numpy.random.rand', 'np.random.rand', (['(5)', '(2)'], {}), '(5, 2)\n', (1547, 1553), True, 'import numpy as np\n'), ((1431, 1460), 'oneflow.compatible.single_client.typing.Numpy.Placeholder', 'oft.Numpy.Placeholder', (['(5, 2)'], {}), '((5, 2))\n', (1452, 1460), True, 'from oneflow.compatible.single_client import typing as oft\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 typing import Optional, Sequence
import oneflow as flow
from oneflow.python.nn.module import Module
from oneflow.python.oneflow_export import oneflow_export, experimental_api
def _calc_broadcast_axes(x, like_tensor):
num_prepend = len(like_tensor.shape) - len(x.shape)
prepend_shape = [1] * num_prepend + list(x.shape)
broadcast_axes = [x for x in range(num_prepend)]
for i in range(num_prepend, len(prepend_shape)):
if prepend_shape[i] != like_tensor.shape[i]:
if prepend_shape[i] != 1:
raise RuntimeError(
f"output with shape {x.shape} doesn't match the broadcast shape {like_tensor.shape}"
)
else:
broadcast_axes.append(i)
return tuple(broadcast_axes)
class BroadCastLike(Module):
def __init__(self, broadcast_axes: Optional[Sequence] = None) -> None:
super().__init__()
self.broadcast_axes = broadcast_axes
def forward(self, x, like_tensor):
if self.broadcast_axes is None:
broadcast_axes = _calc_broadcast_axes(x, like_tensor)
else:
broadcast_axes = self.broadcast_axes
return flow.F.broadcast_like(x, like_tensor, broadcast_axes=broadcast_axes)
@oneflow_export("broadcast_like")
@experimental_api
def broadcast_like_op(x, like_tensor, broadcast_axes: Optional[Sequence] = None):
return BroadCastLike(broadcast_axes=broadcast_axes)(x, like_tensor)
| [
"oneflow.F.broadcast_like",
"oneflow.python.oneflow_export.oneflow_export"
] | [((1848, 1880), 'oneflow.python.oneflow_export.oneflow_export', 'oneflow_export', (['"""broadcast_like"""'], {}), "('broadcast_like')\n", (1862, 1880), False, 'from oneflow.python.oneflow_export import oneflow_export, experimental_api\n'), ((1776, 1844), 'oneflow.F.broadcast_like', 'flow.F.broadcast_like', (['x', 'like_tensor'], {'broadcast_axes': 'broadcast_axes'}), '(x, like_tensor, broadcast_axes=broadcast_axes)\n', (1797, 1844), 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 as flow
import oneflow.typing as tp
from collections import OrderedDict
import numpy as np
import os
from test_util import GenArgList
import unittest
def getInstanceNorm1DOutAndGrad(input, gout, eps):
assert len(input.shape) == len(gout.shape)
assert len(input.shape) >= 3
# reshape to (N, C, L)
input_reshape_to_1d = np.reshape(input, (input.shape[0], input.shape[1], -1))
gout_reshape_to_1d = np.reshape(gout, (gout.shape[0], gout.shape[1], -1))
# compute instance normalization in numpy
gamma = np.ones((1, input_reshape_to_1d.shape[1], 1), dtype=np.float32)
mean_np = np.mean(input_reshape_to_1d, axis=(2), keepdims=True)
in_sub_mean = input_reshape_to_1d - mean_np
var_np = np.mean(np.square(in_sub_mean), axis=(2), keepdims=True)
invar_np = 1.0 / np.sqrt(var_np + eps)
out_np = in_sub_mean * invar_np * gamma
# compute the gradient of variance
gvar = (
gout_reshape_to_1d * gamma * in_sub_mean * -0.5 * np.power(var_np + eps, -1.5)
)
gvar = np.sum(gvar, axis=(2), keepdims=True)
# compute the gradient of mean
gmean = np.sum(gout_reshape_to_1d * gamma, axis=(2), keepdims=True)
gmean *= -invar_np
scale = 1.0 / (input_reshape_to_1d.shape[2])
tmp = scale * np.sum(-2.0 * in_sub_mean, axis=(2), keepdims=True) * gvar
gmean += tmp
# compute the gradient of input
gin_np = (
gout_reshape_to_1d * gamma * invar_np
+ gvar * scale * 2.0 * in_sub_mean
+ gmean * scale
)
# reshape back to original
return np.reshape(out_np, list(input.shape)), np.reshape(gin_np, list(input.shape))
def _compare_instance_norm_nd_with_np(
input_shape, device_type, machine_ids, device_counts, eps, affine
):
assert device_type in ["cpu", "gpu"]
assert len(input_shape) >= 3 and len(input_shape) <= 5
flow.clear_default_session()
if device_type == "cpu":
flow.config.cpu_device_num(device_counts)
else:
flow.config.gpu_device_num(device_counts)
func_config = flow.FunctionConfig()
func_config.default_placement_scope(flow.scope.placement(device_type, machine_ids))
input = np.random.random(size=input_shape).astype(np.float32)
gout = np.random.random(size=input_shape).astype(np.float32)
out_np, gin_np = getInstanceNorm1DOutAndGrad(input, gout, eps)
def assert_prediction_grad(gin_of: tp.Numpy):
assert np.allclose(gin_of, gin_np, atol=1e-5)
@flow.global_function(type="train", function_config=func_config)
def instanceNormJob(
of_input: tp.Numpy.Placeholder(shape=input.shape),
multipler: tp.Numpy.Placeholder(shape=input.shape),
) -> tp.Numpy:
with flow.scope.placement(device_type, "0:0"):
v = flow.get_variable(
shape=of_input.shape,
dtype=flow.float32,
initializer=flow.constant_initializer(0),
name="v",
)
x_var = of_input + v
# watch the gradient
flow.watch_diff(x_var, assert_prediction_grad)
if len(of_input.shape) == 3:
out = flow.nn.InstanceNorm1d(x_var, eps=eps, affine=affine)
elif len(of_input.shape) == 4:
out = flow.nn.InstanceNorm2d(x_var, eps=eps, affine=affine)
else: # len(of_input.shape) == 5
out = flow.nn.InstanceNorm3d(x_var, eps=eps, affine=affine)
with flow.scope.placement(device_type, "0:0"):
flow.optimizer.SGD(
flow.optimizer.PiecewiseConstantScheduler([], [1e-3]), momentum=0
).minimize(out * multipler)
return out
of_out = instanceNormJob(input, gout)
assert np.allclose(of_out, out_np, atol=1e-5)
@flow.unittest.skip_unless_1n1d()
class TestInstanceNormND1n1d(flow.unittest.TestCase):
def test_instance_norm(test_case):
arg_dict = OrderedDict()
arg_dict["input_shape"] = [(4, 2, 32), (4, 2, 32, 32, 32)]
arg_dict["device_type"] = ["cpu", "gpu"]
arg_dict["machine_ids"] = ["0:0"]
arg_dict["device_counts"] = [1]
arg_dict["eps"] = [1e-3]
arg_dict["affine"] = [True, False]
for arg in GenArgList(arg_dict):
_compare_instance_norm_nd_with_np(*arg)
@flow.unittest.skip_unless_1n2d()
class TestInstanceNormND1n2d(flow.unittest.TestCase):
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
def test_instance_norm(test_case):
arg_dict = OrderedDict()
arg_dict["input_shape"] = [(4, 2, 32), (4, 2, 32, 32)]
arg_dict["device_type"] = ["gpu"]
arg_dict["machine_ids"] = ["0:0-1"]
arg_dict["device_counts"] = [2]
arg_dict["eps"] = [1e-3]
arg_dict["affine"] = [True, False]
for arg in GenArgList(arg_dict):
_compare_instance_norm_nd_with_np(*arg)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.FunctionConfig",
"oneflow.optimizer.PiecewiseConstantScheduler",
"oneflow.global_function",
"oneflow.typing.Numpy.Placeholder",
"oneflow.nn.InstanceNorm2d",
"oneflow.unittest.skip_unless_1n2d",
"oneflow.constant_initializer",
"oneflow.nn.InstanceNorm1d",
"oneflow.scope.placement",
"oneflow.unittest.skip_unless_1n1d",
"oneflow.config.gpu_device_num",
"oneflow.watch_diff",
"oneflow.nn.InstanceNorm3d",
"oneflow.config.cpu_device_num",
"oneflow.clear_default_session"
] | [((4337, 4369), 'oneflow.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (4367, 4369), True, 'import oneflow as flow\n'), ((4866, 4898), 'oneflow.unittest.skip_unless_1n2d', 'flow.unittest.skip_unless_1n2d', ([], {}), '()\n', (4896, 4898), True, 'import oneflow as flow\n'), ((944, 999), 'numpy.reshape', 'np.reshape', (['input', '(input.shape[0], input.shape[1], -1)'], {}), '(input, (input.shape[0], input.shape[1], -1))\n', (954, 999), True, 'import numpy as np\n'), ((1025, 1077), 'numpy.reshape', 'np.reshape', (['gout', '(gout.shape[0], gout.shape[1], -1)'], {}), '(gout, (gout.shape[0], gout.shape[1], -1))\n', (1035, 1077), True, 'import numpy as np\n'), ((1137, 1200), 'numpy.ones', 'np.ones', (['(1, input_reshape_to_1d.shape[1], 1)'], {'dtype': 'np.float32'}), '((1, input_reshape_to_1d.shape[1], 1), dtype=np.float32)\n', (1144, 1200), True, 'import numpy as np\n'), ((1215, 1266), 'numpy.mean', 'np.mean', (['input_reshape_to_1d'], {'axis': '(2)', 'keepdims': '(True)'}), '(input_reshape_to_1d, axis=2, keepdims=True)\n', (1222, 1266), True, 'import numpy as np\n'), ((1631, 1666), 'numpy.sum', 'np.sum', (['gvar'], {'axis': '(2)', 'keepdims': '(True)'}), '(gvar, axis=2, keepdims=True)\n', (1637, 1666), True, 'import numpy as np\n'), ((1716, 1773), 'numpy.sum', 'np.sum', (['(gout_reshape_to_1d * gamma)'], {'axis': '(2)', 'keepdims': '(True)'}), '(gout_reshape_to_1d * gamma, axis=2, keepdims=True)\n', (1722, 1773), True, 'import numpy as np\n'), ((2451, 2479), 'oneflow.clear_default_session', 'flow.clear_default_session', ([], {}), '()\n', (2477, 2479), True, 'import oneflow as flow\n'), ((2639, 2660), 'oneflow.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (2658, 2660), True, 'import oneflow as flow\n'), ((3060, 3123), 'oneflow.global_function', 'flow.global_function', ([], {'type': '"""train"""', 'function_config': 'func_config'}), "(type='train', function_config=func_config)\n", (3080, 3123), True, 'import oneflow as flow\n'), ((4295, 4334), 'numpy.allclose', 'np.allclose', (['of_out', 'out_np'], {'atol': '(1e-05)'}), '(of_out, out_np, atol=1e-05)\n', (4306, 4334), True, 'import numpy as np\n'), ((5496, 5511), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5509, 5511), False, 'import unittest\n'), ((1338, 1360), 'numpy.square', 'np.square', (['in_sub_mean'], {}), '(in_sub_mean)\n', (1347, 1360), True, 'import numpy as np\n'), ((1408, 1429), 'numpy.sqrt', 'np.sqrt', (['(var_np + eps)'], {}), '(var_np + eps)\n', (1415, 1429), True, 'import numpy as np\n'), ((1585, 1613), 'numpy.power', 'np.power', (['(var_np + eps)', '(-1.5)'], {}), '(var_np + eps, -1.5)\n', (1593, 1613), True, 'import numpy as np\n'), ((2518, 2559), 'oneflow.config.cpu_device_num', 'flow.config.cpu_device_num', (['device_counts'], {}), '(device_counts)\n', (2544, 2559), True, 'import oneflow as flow\n'), ((2578, 2619), 'oneflow.config.gpu_device_num', 'flow.config.gpu_device_num', (['device_counts'], {}), '(device_counts)\n', (2604, 2619), True, 'import oneflow as flow\n'), ((2701, 2747), 'oneflow.scope.placement', 'flow.scope.placement', (['device_type', 'machine_ids'], {}), '(device_type, machine_ids)\n', (2721, 2747), True, 'import oneflow as flow\n'), ((3015, 3054), 'numpy.allclose', 'np.allclose', (['gin_of', 'gin_np'], {'atol': '(1e-05)'}), '(gin_of, gin_np, atol=1e-05)\n', (3026, 3054), True, 'import numpy as np\n'), ((4482, 4495), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4493, 4495), False, 'from collections import OrderedDict\n'), ((4789, 4809), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (4799, 4809), False, 'from test_util import GenArgList\n'), ((5091, 5104), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (5102, 5104), False, 'from collections import OrderedDict\n'), ((5389, 5409), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (5399, 5409), False, 'from test_util import GenArgList\n'), ((4974, 5008), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (4983, 5008), False, 'import os\n'), ((1866, 1915), 'numpy.sum', 'np.sum', (['(-2.0 * in_sub_mean)'], {'axis': '(2)', 'keepdims': '(True)'}), '(-2.0 * in_sub_mean, axis=2, keepdims=True)\n', (1872, 1915), True, 'import numpy as np\n'), ((2762, 2796), 'numpy.random.random', 'np.random.random', ([], {'size': 'input_shape'}), '(size=input_shape)\n', (2778, 2796), True, 'import numpy as np\n'), ((2827, 2861), 'numpy.random.random', 'np.random.random', ([], {'size': 'input_shape'}), '(size=input_shape)\n', (2843, 2861), True, 'import numpy as np\n'), ((3167, 3206), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', ([], {'shape': 'input.shape'}), '(shape=input.shape)\n', (3187, 3206), True, 'import oneflow.typing as tp\n'), ((3227, 3266), 'oneflow.typing.Numpy.Placeholder', 'tp.Numpy.Placeholder', ([], {'shape': 'input.shape'}), '(shape=input.shape)\n', (3247, 3266), True, 'import oneflow.typing as tp\n'), ((3300, 3340), 'oneflow.scope.placement', 'flow.scope.placement', (['device_type', '"""0:0"""'], {}), "(device_type, '0:0')\n", (3320, 3340), True, 'import oneflow as flow\n'), ((3628, 3674), 'oneflow.watch_diff', 'flow.watch_diff', (['x_var', 'assert_prediction_grad'], {}), '(x_var, assert_prediction_grad)\n', (3643, 3674), True, 'import oneflow as flow\n'), ((3731, 3784), 'oneflow.nn.InstanceNorm1d', 'flow.nn.InstanceNorm1d', (['x_var'], {'eps': 'eps', 'affine': 'affine'}), '(x_var, eps=eps, affine=affine)\n', (3753, 3784), True, 'import oneflow as flow\n'), ((4024, 4064), 'oneflow.scope.placement', 'flow.scope.placement', (['device_type', '"""0:0"""'], {}), "(device_type, '0:0')\n", (4044, 4064), True, 'import oneflow as flow\n'), ((3842, 3895), 'oneflow.nn.InstanceNorm2d', 'flow.nn.InstanceNorm2d', (['x_var'], {'eps': 'eps', 'affine': 'affine'}), '(x_var, eps=eps, affine=affine)\n', (3864, 3895), True, 'import oneflow as flow\n'), ((3956, 4009), 'oneflow.nn.InstanceNorm3d', 'flow.nn.InstanceNorm3d', (['x_var'], {'eps': 'eps', 'affine': 'affine'}), '(x_var, eps=eps, affine=affine)\n', (3978, 4009), True, 'import oneflow as flow\n'), ((3479, 3507), 'oneflow.constant_initializer', 'flow.constant_initializer', (['(0)'], {}), '(0)\n', (3504, 3507), True, 'import oneflow as flow\n'), ((4114, 4168), 'oneflow.optimizer.PiecewiseConstantScheduler', 'flow.optimizer.PiecewiseConstantScheduler', (['[]', '[0.001]'], {}), '([], [0.001])\n', (4155, 4168), True, 'import oneflow as flow\n')] |
import oneflow as flow
import oneflow as flow_exp
from oneflow import Tensor
def nms(boxes: Tensor, scores: Tensor, iou_threshold: float) -> Tensor:
scores_inds = flow_exp.argsort(scores, dim=0, descending=True)
boxes = flow._C.gather(boxes, scores_inds, axis=0)
_nms_op = (
flow_exp.builtin_op("nms")
.Input("in")
.Output("out")
.Attr("iou_threshold", iou_threshold)
.Attr("keep_n", -1)
.Build()
)
keep = _nms_op(boxes)[0]
index = flow_exp.squeeze(flow_exp.argwhere(keep), dim=[1])
return flow._C.gather(scores_inds, index, axis=0)
| [
"oneflow.builtin_op",
"oneflow.argwhere",
"oneflow.argsort",
"oneflow._C.gather"
] | [((169, 217), 'oneflow.argsort', 'flow_exp.argsort', (['scores'], {'dim': '(0)', 'descending': '(True)'}), '(scores, dim=0, descending=True)\n', (185, 217), True, 'import oneflow as flow_exp\n'), ((230, 272), 'oneflow._C.gather', 'flow._C.gather', (['boxes', 'scores_inds'], {'axis': '(0)'}), '(boxes, scores_inds, axis=0)\n', (244, 272), True, 'import oneflow as flow\n'), ((568, 610), 'oneflow._C.gather', 'flow._C.gather', (['scores_inds', 'index'], {'axis': '(0)'}), '(scores_inds, index, axis=0)\n', (582, 610), True, 'import oneflow as flow\n'), ((523, 546), 'oneflow.argwhere', 'flow_exp.argwhere', (['keep'], {}), '(keep)\n', (540, 546), True, 'import oneflow as flow_exp\n'), ((297, 323), 'oneflow.builtin_op', 'flow_exp.builtin_op', (['"""nms"""'], {}), "('nms')\n", (316, 323), True, 'import oneflow as flow_exp\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, type_name_to_flow_type, type_name_to_np_type
from automated_test_util import *
def _test_variance_keepdim(test_case, shape, device):
np_arr = np.random.randn(*shape)
of_out = flow.Tensor(np_arr, device=flow.device(device)).var(0, True)
np_out = np.var(np_arr, 0, keepdims=True)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
def _test_variance(test_case, shape, device):
np_arr = np.random.randn(*shape)
of_out = flow.var(flow.Tensor(np_arr, device=flow.device(device)), 1, False)
np_out = np.var(np_arr, 1, keepdims=False)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
def _test_variance_backward(test_case, shape, device):
np_arr = np.array(
[
[
[-0.43621400, -1.11672411, 0.78394664, 2.06217120],
[0.77167030, -1.35367316, -0.40694879, -1.72392356],
[-1.08482436, -0.20731248, 1.39633697, 0.32614333],
],
[
[-1.42467297, -1.78418015, 0.17861511, 0.12065858],
[2.03621124, -0.93674042, 0.19439630, 1.98559192],
[-0.00436223, 0.37788105, 0.47820872, 0.15467583],
],
]
)
x = flow.Tensor(np_arr, requires_grad=True, device=flow.device(device))
y = flow.var(x, False)
z = y.sum()
z.backward()
np_grad = 2 * (np_arr - np_arr.mean()) / (np_arr.size)
test_case.assertTrue(np.allclose(x.grad.numpy(), np_grad, 1e-5, 1e-5))
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestVariance(flow.unittest.TestCase):
def test_variance(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [
_test_variance,
_test_variance_keepdim,
# _test_variance_backward # TODO:(zhaoluyang):output grad not equal to numpy grad
]
arg_dict["shape"] = [(2, 3), (2, 3, 4), (2, 3, 4, 5)]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
def _test_sin(test_case, shape, device):
input = flow.Tensor(np.random.randn(*shape), device=flow.device(device))
of_out = flow.sin(input)
np_out = np.sin(input.numpy())
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
def _test_sin_backward(test_case, shape, device):
x = flow.Tensor(
np.random.randn(*shape), requires_grad=True, device=flow.device(device)
)
y = flow.sin(x)
z = y.sum()
z.backward()
test_case.assertTrue(np.allclose(x.grad.numpy(), np.cos(x.numpy()), 1e-5, 1e-5))
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestSin(flow.unittest.TestCase):
def test_sin(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [
_test_sin,
_test_sin_backward,
]
arg_dict["shape"] = [(2, 3), (2, 3, 4), (2, 3, 4, 5)]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
def _test_cos(test_case, shape, device):
input = flow.Tensor(
np.random.randn(*shape), dtype=flow.float32, device=flow.device(device)
)
of_out = flow.cos(input)
np_out = np.cos(input.numpy())
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
def _test_cos_backward(test_case, shape, device):
x = flow.Tensor(
np.random.randn(*shape),
dtype=flow.float32,
device=flow.device(device),
requires_grad=True,
)
y = flow.cos(x)
z = y.sum()
z.backward()
np_grad = -np.sin(x.numpy())
test_case.assertTrue(np.allclose(x.grad.numpy(), np_grad, 1e-5, 1e-5))
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestCos(flow.unittest.TestCase):
def test_cos(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [
_test_cos,
_test_cos_backward,
]
arg_dict["shape"] = [(2, 3), (2, 3, 4), (2, 3, 4, 5)]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
def _test_log(test_case, shape, device):
np_arr = np.abs(np.random.randn(*shape))
input = flow.Tensor(np_arr, dtype=flow.float32, device=flow.device(device))
of_out = flow.log(input)
np_out = np.log(np_arr)
test_case.assertTrue(
np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5, equal_nan=True)
)
def _test_log_nan_value(test_case, shape, device):
arr = np.array([-0.7168, -0.5471, -0.8933, -1.4428, -0.1190])
input = flow.Tensor(arr, dtype=flow.float32, device=flow.device(device))
np_out = np.full((5,), np.nan)
of_out = flow.log(input)
test_case.assertTrue(
np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5, equal_nan=True)
)
def _test_log_backward(test_case, shape, device):
x = flow.Tensor(
np.random.randn(*shape),
dtype=flow.float32,
device=flow.device(device),
requires_grad=True,
)
y = flow.log(x)
z = y.sum()
z.backward()
np_grad = 1 / x.numpy()
test_case.assertTrue(
np.allclose(x.grad.numpy(), np_grad, 1e-5, 1e-5, equal_nan=True)
)
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestLog(flow.unittest.TestCase):
def test_log(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [_test_log, _test_log_nan_value, _test_log_backward]
arg_dict["shape"] = [(2, 3), (2, 3, 4), (2, 3, 4, 5)]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
def _test_std(test_case, shape, device):
np_arr = np.random.randn(*shape)
input = flow.Tensor(np_arr, device=flow.device(device))
of_out = flow.std(input, dim=2)
np_out = np.std(np_arr, axis=2)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-4, 1e-4))
def _test_std_dim1(test_case, shape, device):
np_arr = np.random.randn(*shape)
input = flow.Tensor(np_arr, device=flow.device(device))
of_out = flow.std(input, dim=1)
np_out = np.std(np_arr, axis=1)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-4, 1e-4))
def _test_std_negative_dim(test_case, shape, device):
np_arr = np.random.randn(4, 2, 3, 5)
input = flow.Tensor(np_arr, device=flow.device(device))
of_out = input.std(dim=(-2, -1, -3), keepdim=False)
np_out = np.std(np_arr, axis=(-2, -1, -3))
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-4, 1e-4))
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestStd(flow.unittest.TestCase):
def test_std(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [
_test_std,
_test_std_dim1,
_test_std_negative_dim,
# TODO:(zhaoluyang):add backward test
]
arg_dict["shape"] = [(2, 3, 4), (2, 3, 4, 5)]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
def _test_sqrt(test_case, shape, device):
np_arr = np.random.randn(*shape)
np_arr = np.abs(np_arr)
np_out = np.sqrt(np_arr)
x = flow.Tensor(np_arr, device=flow.device(device))
of_out = flow.sqrt(input=x)
test_case.assertTrue(
np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5, equal_nan=True)
)
def _test_sqrt_backward(test_case, shape, device):
np_arr = np.random.randn(*shape)
np_arr = np.abs(np_arr)
x = flow.Tensor(np_arr, device=flow.device(device), requires_grad=True)
y = flow.sqrt(input=x)
z = y.sum()
z.backward()
np_grad = 0.5 * 1 / np.sqrt(x.numpy())
test_case.assertTrue(
np.allclose(x.grad.numpy(), np_grad, 1e-5, 1e-5, equal_nan=True)
)
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestSqrt(flow.unittest.TestCase):
def test_sqrt(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [_test_sqrt, _test_sqrt_backward]
arg_dict["shape"] = [(2, 3), (2, 3, 4), (2, 3, 4, 5)]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
def _test_rsqrt(test_case, shape, device):
np_arr = np.random.randn(*shape)
np_arr = np.abs(np_arr)
np_out = 1 / np.sqrt(np_arr)
input = flow.Tensor(np_arr, device=flow.device(device))
of_out = input.rsqrt()
test_case.assertTrue(
np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5, equal_nan=True)
)
def _test_rsqrt_backward(test_case, shape, device):
np_arr = np.random.randn(*shape)
np_arr = np.abs(np_arr)
x = flow.Tensor(np_arr, device=flow.device(device), requires_grad=True)
y = flow.rsqrt(input=x)
z = y.sum()
z.backward()
np_grad = -1 / 2 * 1 / (x.numpy() * np.sqrt(x.numpy()))
test_case.assertTrue(
np.allclose(x.grad.numpy(), np_grad, 1e-5, 1e-5, equal_nan=True)
)
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestRsqrt(flow.unittest.TestCase):
def test_rsqrt(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [_test_rsqrt, _test_rsqrt_backward]
arg_dict["shape"] = [(2, 3), (2, 3, 4), (2, 3, 4, 5)]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
def _test_square(test_case, shape, device):
np_arr = np.random.randn(*shape)
np_out = np.square(np_arr)
x = flow.Tensor(np_arr, device=flow.device(device))
of_out = flow.square(x)
test_case.assertTrue(
np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5, equal_nan=True)
)
def _test_square_backward(test_case, shape, device):
np_arr = np.random.randn(*shape)
np_out = np.square(np_arr)
x = flow.Tensor(np_arr, device=flow.device(device), requires_grad=True)
y = flow.square(x)
z = y.sum()
z.backward()
np_grad = 2 * np_arr
test_case.assertTrue(
np.allclose(x.grad.numpy(), np_grad, 1e-5, 1e-5, equal_nan=True)
)
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestSquare(flow.unittest.TestCase):
def test_square(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [_test_square, _test_square_backward]
arg_dict["shape"] = [(2, 3), (2, 3, 4), (2, 3, 4, 5)]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
def _test_pow(test_case, shape, device):
input = flow.Tensor(
np.random.randn(*shape), dtype=flow.float32, device=flow.device(device)
)
of_out = flow.pow(input, 2.1)
np_out = np.power(input.numpy(), 2.1)
test_case.assertTrue(
np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5, equal_nan=True)
)
def _test_pow_backward(test_case, shape, device):
x = flow.Tensor(
np.random.randn(*shape),
dtype=flow.float32,
device=flow.device(device),
requires_grad=True,
)
y = flow.pow(x, 2.34)
z = y.sum()
z.backward()
np_grad = 2.34 * x.numpy() ** (2.34 - 1)
test_case.assertTrue(
np.allclose(x.grad.numpy(), np_grad, 1e-5, 1e-5, equal_nan=True)
)
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestPow(flow.unittest.TestCase):
def test_pow(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [
_test_pow,
_test_pow_backward,
]
arg_dict["shape"] = [(2, 3), (2, 3, 4), (2, 3, 4, 5)]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
def _test_asin(test_case, shape, device):
np_input = np.random.random(shape) - 0.5
of_input = flow.Tensor(
np_input, dtype=flow.float32, device=flow.device(device), requires_grad=True
)
of_out = flow.asin(of_input)
np_out = np.arcsin(np_input)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
of_out = of_out.sum()
of_out.backward()
np_out_grad = 1 / np.sqrt(1 - np_input ** 2)
test_case.assertTrue(np.allclose(of_input.grad.numpy(), np_out_grad, 1e-4, 1e-4))
def _test_arcsin(test_case, shape, device):
np_input = np.random.random(shape) - 0.5
of_input = flow.Tensor(
np_input, dtype=flow.float32, device=flow.device(device), requires_grad=True
)
of_out = flow.arcsin(of_input)
np_out = np.arcsin(np_input)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
of_out = of_out.sum()
of_out.backward()
np_out_grad = 1 / np.sqrt(1 - np_input ** 2)
test_case.assertTrue(np.allclose(of_input.grad.numpy(), np_out_grad, 1e-4, 1e-4))
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestAsin(flow.unittest.TestCase):
def test_asin(test_case):
arg_dict = OrderedDict()
arg_dict["shape"] = [(2,), (2, 3), (2, 4, 5, 6)]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_asin(test_case, *arg)
_test_arcsin(test_case, *arg)
def test_flow_asin_with_random_data(test_case):
for device in ["cpu", "cuda"]:
test_flow_against_pytorch(
test_case, "asin", device=device,
)
def test_flow_arcsin_with_random_data(test_case):
for device in ["cpu", "cuda"]:
test_flow_against_pytorch(
test_case, "arcsin", device=device,
)
def test_flow_tensor_asin_with_random_data(test_case):
for device in ["cpu", "cuda"]:
test_tensor_against_pytorch(
test_case, "asin", device=device,
)
def test_flow_tensor_arcsin_with_random_data(test_case):
for device in ["cpu", "cuda"]:
test_tensor_against_pytorch(
test_case, "arcsin", device=device,
)
def _test_asinh(test_case, shape, device):
np_input = np.random.randn(*shape)
of_input = flow.Tensor(
np_input, dtype=flow.float32, device=flow.device(device), requires_grad=True
)
of_out = flow.asinh(of_input)
np_out = np.arcsinh(np_input)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
of_out = of_out.sum()
of_out.backward()
np_out_grad = 1 / np.sqrt(1 + np_input ** 2)
test_case.assertTrue(np.allclose(of_input.grad.numpy(), np_out_grad, 1e-4, 1e-4))
def _test_arcsinh(test_case, shape, device):
np_input = np.random.randn(*shape)
of_input = flow.Tensor(
np_input, dtype=flow.float32, device=flow.device(device), requires_grad=True
)
of_out = flow.arcsinh(of_input)
np_out = np.arcsinh(np_input)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
of_out = of_out.sum()
of_out.backward()
np_out_grad = 1 / np.sqrt(1 + np_input ** 2)
test_case.assertTrue(np.allclose(of_input.grad.numpy(), np_out_grad, 1e-4, 1e-4))
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestAsinh(flow.unittest.TestCase):
def test_asinh(test_case):
arg_dict = OrderedDict()
arg_dict["shape"] = [(2,), (2, 3), (2, 4, 5, 6)]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_asinh(test_case, *arg)
_test_arcsinh(test_case, *arg)
def _topk_np(input, k, dim: int = None, largest: bool = True, _sorted: bool = True):
in_dims = input.shape
out_dims = list(in_dims)
num_axes = len(input.shape)
if dim < 0:
dim = dim + num_axes
n = in_dims[dim]
if k > n:
k = n
out_dims[dim] = k
out_dims = tuple(out_dims)
prev_dims = 1
next_dims = 1
for i in range(dim):
prev_dims *= in_dims[i]
for i in range(dim + 1, len(in_dims)):
next_dims *= in_dims[i]
input_flat = input.reshape((prev_dims, n, next_dims))
values_ref = np.ndarray(shape=(prev_dims, k, next_dims), dtype=input.dtype)
values_ref.fill(0)
indices_ref = np.ndarray(shape=(prev_dims, k, next_dims), dtype=np.int64)
indices_ref.fill(-1)
for i in range(prev_dims):
for j in range(next_dims):
kv = []
for x in range(n):
val = input_flat[i, x, j]
y = x * next_dims + i * in_dims[dim] * next_dims + j
kv.append((val, x, y))
cnt = 0
for val, x, y in sorted(kv, key=lambda x: (x[0], -x[1]), reverse=largest):
values_ref[i, cnt, j] = val
indices_ref[i, cnt, j] = x
cnt += 1
if cnt >= k or cnt >= n:
break
values_ref = values_ref.reshape(out_dims)
indices_ref = indices_ref.reshape(out_dims)
return (values_ref, indices_ref)
def _test_topk_dim_negative(test_case, device):
input = flow.Tensor(
np.random.randn(2, 6, 5, 7), dtype=flow.float32, device=flow.device(device),
)
dim = -1
k = 4
(of_values, of_indices) = flow.topk(input, k=k, dim=dim)
(np_values, np_indices) = _topk_np(input.numpy(), k=k, dim=dim)
test_case.assertTrue(
np.array_equal(of_values.numpy().flatten(), np_values.flatten())
)
test_case.assertTrue(
np.array_equal(of_indices.numpy().flatten(), np_indices.flatten())
)
def _test_tensor_topk(test_case, device):
input = flow.Tensor(
np.random.randn(2, 6, 5, 7), dtype=flow.float32, device=flow.device(device),
)
dim = 1
k = 4
(of_values, of_indices) = input.topk(k=k, dim=dim)
(np_values, np_indices) = _topk_np(input.numpy(), k=k, dim=dim)
test_case.assertTrue(
np.array_equal(of_values.numpy().flatten(), np_values.flatten())
)
test_case.assertTrue(
np.array_equal(of_indices.numpy().flatten(), np_indices.flatten())
)
def _test_topk_dim_positive(test_case, device):
input = flow.Tensor(
np.random.randn(2, 6, 5, 7), dtype=flow.float32, device=flow.device(device),
)
dim = 2
k = 4
(of_values, of_indices) = flow.topk(input, k=k, dim=dim)
(np_values, np_indices) = _topk_np(input.numpy(), k=k, dim=dim)
test_case.assertTrue(
np.array_equal(of_values.numpy().flatten(), np_values.flatten())
)
test_case.assertTrue(
np.array_equal(of_indices.numpy().flatten(), np_indices.flatten())
)
def _test_topk_largest(test_case, device):
input = flow.Tensor(
np.random.randn(2, 6, 5, 7), dtype=flow.float32, device=flow.device(device),
)
dim = 1
k = 4
largest = False
(of_values, of_indices) = flow.topk(input, k=k, dim=dim, largest=False)
(np_values, np_indices) = _topk_np(input.numpy(), k=k, dim=dim, largest=False)
test_case.assertTrue(
np.array_equal(of_values.numpy().flatten(), np_values.flatten())
)
test_case.assertTrue(
np.array_equal(of_indices.numpy().flatten(), np_indices.flatten())
)
def _test_topk_original(test_case, device):
arg_dict = OrderedDict()
arg_dict["shape"] = [(10, 10, 200)]
arg_dict["axis"] = [-2, 0, 2]
arg_dict["k"] = [1, 50, 200]
arg_dict["largest"] = [True, False]
arg_dict["data_type"] = ["float32", "double"]
rng = np.random.default_rng()
for (shape, axis, k, largest, data_type) in GenArgList(arg_dict):
np_type = type_name_to_np_type[data_type]
random_data = rng.standard_normal(size=shape, dtype=np_type)
while np.unique(random_data).size != random_data.size:
random_data = rng.standard_normal(size=shape, dtype=np_type)
input = flow.Tensor(
random_data,
dtype=type_name_to_flow_type[data_type],
device=flow.device(device),
)
(of_values, of_indices) = flow.topk(input, k=k, dim=axis, largest=largest)
(np_values, np_indices) = _topk_np(
input.numpy(), k=k, dim=axis, largest=largest
)
test_case.assertTrue(
np.array_equal(of_values.numpy().flatten(), np_values.flatten())
)
test_case.assertTrue(
np.array_equal(of_indices.numpy().flatten(), np_indices.flatten())
)
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestPow(flow.unittest.TestCase):
def test_pow(test_case):
input = flow.Tensor(np.array([1, 2, 3, 4, 5, 6]), dtype=flow.float32)
of_out = flow.pow(input, 2.1)
np_out = np.power(input.numpy(), 2.1)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
def test_pow_tensor_function(test_case):
input = flow.Tensor(np.array([1, 2, 3, 4, 5, 6]), dtype=flow.float32)
of_out = input.pow(2.1)
np_out = np.power(input.numpy(), 2.1)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestTopk(flow.unittest.TestCase):
def test_topk(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [
_test_topk_dim_negative,
_test_tensor_topk,
_test_topk_dim_positive,
_test_topk_largest,
_test_topk_original,
]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
if __name__ == "__main__":
unittest.main()
| [
"oneflow.experimental.std",
"oneflow.experimental.arcsinh",
"oneflow.experimental.topk",
"oneflow.experimental.unittest.env.eager_execution_enabled",
"oneflow.experimental.log",
"oneflow.experimental.sin",
"oneflow.experimental.device",
"oneflow.experimental.pow",
"oneflow.experimental.arcsin",
"oneflow.experimental.asinh",
"oneflow.experimental.cos",
"oneflow.experimental.rsqrt",
"oneflow.experimental.var",
"oneflow.experimental.asin",
"oneflow.experimental.square",
"oneflow.experimental.sqrt"
] | [((881, 904), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (896, 904), True, 'import numpy as np\n'), ((992, 1024), 'numpy.var', 'np.var', (['np_arr', '(0)'], {'keepdims': '(True)'}), '(np_arr, 0, keepdims=True)\n', (998, 1024), True, 'import numpy as np\n'), ((1160, 1183), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (1175, 1183), True, 'import numpy as np\n'), ((1278, 1311), 'numpy.var', 'np.var', (['np_arr', '(1)'], {'keepdims': '(False)'}), '(np_arr, 1, keepdims=False)\n', (1284, 1311), True, 'import numpy as np\n'), ((1456, 1796), 'numpy.array', 'np.array', (['[[[-0.436214, -1.11672411, 0.78394664, 2.0621712], [0.7716703, -1.35367316,\n -0.40694879, -1.72392356], [-1.08482436, -0.20731248, 1.39633697, \n 0.32614333]], [[-1.42467297, -1.78418015, 0.17861511, 0.12065858], [\n 2.03621124, -0.93674042, 0.1943963, 1.98559192], [-0.00436223, \n 0.37788105, 0.47820872, 0.15467583]]]'], {}), '([[[-0.436214, -1.11672411, 0.78394664, 2.0621712], [0.7716703, -\n 1.35367316, -0.40694879, -1.72392356], [-1.08482436, -0.20731248, \n 1.39633697, 0.32614333]], [[-1.42467297, -1.78418015, 0.17861511, \n 0.12065858], [2.03621124, -0.93674042, 0.1943963, 1.98559192], [-\n 0.00436223, 0.37788105, 0.47820872, 0.15467583]]])\n', (1464, 1796), True, 'import numpy as np\n'), ((2041, 2059), 'oneflow.experimental.var', 'flow.var', (['x', '(False)'], {}), '(x, False)\n', (2049, 2059), True, 'import oneflow.experimental as flow\n'), ((2977, 2992), 'oneflow.experimental.sin', 'flow.sin', (['input'], {}), '(input)\n', (2985, 2992), True, 'import oneflow.experimental as flow\n'), ((3269, 3280), 'oneflow.experimental.sin', 'flow.sin', (['x'], {}), '(x)\n', (3277, 3280), True, 'import oneflow.experimental as flow\n'), ((4070, 4085), 'oneflow.experimental.cos', 'flow.cos', (['input'], {}), '(input)\n', (4078, 4085), True, 'import oneflow.experimental as flow\n'), ((4407, 4418), 'oneflow.experimental.cos', 'flow.cos', (['x'], {}), '(x)\n', (4415, 4418), True, 'import oneflow.experimental as flow\n'), ((5245, 5260), 'oneflow.experimental.log', 'flow.log', (['input'], {}), '(input)\n', (5253, 5260), True, 'import oneflow.experimental as flow\n'), ((5274, 5288), 'numpy.log', 'np.log', (['np_arr'], {}), '(np_arr)\n', (5280, 5288), True, 'import numpy as np\n'), ((5456, 5510), 'numpy.array', 'np.array', (['[-0.7168, -0.5471, -0.8933, -1.4428, -0.119]'], {}), '([-0.7168, -0.5471, -0.8933, -1.4428, -0.119])\n', (5464, 5510), True, 'import numpy as np\n'), ((5602, 5623), 'numpy.full', 'np.full', (['(5,)', 'np.nan'], {}), '((5,), np.nan)\n', (5609, 5623), True, 'import numpy as np\n'), ((5637, 5652), 'oneflow.experimental.log', 'flow.log', (['input'], {}), '(input)\n', (5645, 5652), True, 'import oneflow.experimental as flow\n'), ((5969, 5980), 'oneflow.experimental.log', 'flow.log', (['x'], {}), '(x)\n', (5977, 5980), True, 'import oneflow.experimental as flow\n'), ((6693, 6716), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (6708, 6716), True, 'import numpy as np\n'), ((6790, 6812), 'oneflow.experimental.std', 'flow.std', (['input'], {'dim': '(2)'}), '(input, dim=2)\n', (6798, 6812), True, 'import oneflow.experimental as flow\n'), ((6826, 6848), 'numpy.std', 'np.std', (['np_arr'], {'axis': '(2)'}), '(np_arr, axis=2)\n', (6832, 6848), True, 'import numpy as np\n'), ((6984, 7007), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (6999, 7007), True, 'import numpy as np\n'), ((7081, 7103), 'oneflow.experimental.std', 'flow.std', (['input'], {'dim': '(1)'}), '(input, dim=1)\n', (7089, 7103), True, 'import oneflow.experimental as flow\n'), ((7117, 7139), 'numpy.std', 'np.std', (['np_arr'], {'axis': '(1)'}), '(np_arr, axis=1)\n', (7123, 7139), True, 'import numpy as np\n'), ((7283, 7310), 'numpy.random.randn', 'np.random.randn', (['(4)', '(2)', '(3)', '(5)'], {}), '(4, 2, 3, 5)\n', (7298, 7310), True, 'import numpy as np\n'), ((7440, 7473), 'numpy.std', 'np.std', (['np_arr'], {'axis': '(-2, -1, -3)'}), '(np_arr, axis=(-2, -1, -3))\n', (7446, 7473), True, 'import numpy as np\n'), ((8183, 8206), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (8198, 8206), True, 'import numpy as np\n'), ((8220, 8234), 'numpy.abs', 'np.abs', (['np_arr'], {}), '(np_arr)\n', (8226, 8234), True, 'import numpy as np\n'), ((8248, 8263), 'numpy.sqrt', 'np.sqrt', (['np_arr'], {}), '(np_arr)\n', (8255, 8263), True, 'import numpy as np\n'), ((8333, 8351), 'oneflow.experimental.sqrt', 'flow.sqrt', ([], {'input': 'x'}), '(input=x)\n', (8342, 8351), True, 'import oneflow.experimental as flow\n'), ((8522, 8545), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (8537, 8545), True, 'import numpy as np\n'), ((8559, 8573), 'numpy.abs', 'np.abs', (['np_arr'], {}), '(np_arr)\n', (8565, 8573), True, 'import numpy as np\n'), ((8658, 8676), 'oneflow.experimental.sqrt', 'flow.sqrt', ([], {'input': 'x'}), '(input=x)\n', (8667, 8676), True, 'import oneflow.experimental as flow\n'), ((9389, 9412), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (9404, 9412), True, 'import numpy as np\n'), ((9426, 9440), 'numpy.abs', 'np.abs', (['np_arr'], {}), '(np_arr)\n', (9432, 9440), True, 'import numpy as np\n'), ((9732, 9755), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (9747, 9755), True, 'import numpy as np\n'), ((9769, 9783), 'numpy.abs', 'np.abs', (['np_arr'], {}), '(np_arr)\n', (9775, 9783), True, 'import numpy as np\n'), ((9868, 9887), 'oneflow.experimental.rsqrt', 'flow.rsqrt', ([], {'input': 'x'}), '(input=x)\n', (9878, 9887), True, 'import oneflow.experimental as flow\n'), ((10622, 10645), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (10637, 10645), True, 'import numpy as np\n'), ((10659, 10676), 'numpy.square', 'np.square', (['np_arr'], {}), '(np_arr)\n', (10668, 10676), True, 'import numpy as np\n'), ((10746, 10760), 'oneflow.experimental.square', 'flow.square', (['x'], {}), '(x)\n', (10757, 10760), True, 'import oneflow.experimental as flow\n'), ((10933, 10956), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (10948, 10956), True, 'import numpy as np\n'), ((10970, 10987), 'numpy.square', 'np.square', (['np_arr'], {}), '(np_arr)\n', (10979, 10987), True, 'import numpy as np\n'), ((11072, 11086), 'oneflow.experimental.square', 'flow.square', (['x'], {}), '(x)\n', (11083, 11086), True, 'import oneflow.experimental as flow\n'), ((11898, 11918), 'oneflow.experimental.pow', 'flow.pow', (['input', '(2.1)'], {}), '(input, 2.1)\n', (11906, 11918), True, 'import oneflow.experimental as flow\n'), ((12277, 12294), 'oneflow.experimental.pow', 'flow.pow', (['x', '(2.34)'], {}), '(x, 2.34)\n', (12285, 12294), True, 'import oneflow.experimental as flow\n'), ((13205, 13224), 'oneflow.experimental.asin', 'flow.asin', (['of_input'], {}), '(of_input)\n', (13214, 13224), True, 'import oneflow.experimental as flow\n'), ((13238, 13257), 'numpy.arcsin', 'np.arcsin', (['np_input'], {}), '(np_input)\n', (13247, 13257), True, 'import numpy as np\n'), ((13741, 13762), 'oneflow.experimental.arcsin', 'flow.arcsin', (['of_input'], {}), '(of_input)\n', (13752, 13762), True, 'import oneflow.experimental as flow\n'), ((13776, 13795), 'numpy.arcsin', 'np.arcsin', (['np_input'], {}), '(np_input)\n', (13785, 13795), True, 'import numpy as np\n'), ((15366, 15389), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (15381, 15389), True, 'import numpy as np\n'), ((15523, 15543), 'oneflow.experimental.asinh', 'flow.asinh', (['of_input'], {}), '(of_input)\n', (15533, 15543), True, 'import oneflow.experimental as flow\n'), ((15557, 15577), 'numpy.arcsinh', 'np.arcsinh', (['np_input'], {}), '(np_input)\n', (15567, 15577), True, 'import numpy as np\n'), ((15899, 15922), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (15914, 15922), True, 'import numpy as np\n'), ((16056, 16078), 'oneflow.experimental.arcsinh', 'flow.arcsinh', (['of_input'], {}), '(of_input)\n', (16068, 16078), True, 'import oneflow.experimental as flow\n'), ((16092, 16112), 'numpy.arcsinh', 'np.arcsinh', (['np_input'], {}), '(np_input)\n', (16102, 16112), True, 'import numpy as np\n'), ((17386, 17448), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(prev_dims, k, next_dims)', 'dtype': 'input.dtype'}), '(shape=(prev_dims, k, next_dims), dtype=input.dtype)\n', (17396, 17448), True, 'import numpy as np\n'), ((17490, 17549), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(prev_dims, k, next_dims)', 'dtype': 'np.int64'}), '(shape=(prev_dims, k, next_dims), dtype=np.int64)\n', (17500, 17549), True, 'import numpy as np\n'), ((18480, 18510), 'oneflow.experimental.topk', 'flow.topk', (['input'], {'k': 'k', 'dim': 'dim'}), '(input, k=k, dim=dim)\n', (18489, 18510), True, 'import oneflow.experimental as flow\n'), ((19526, 19556), 'oneflow.experimental.topk', 'flow.topk', (['input'], {'k': 'k', 'dim': 'dim'}), '(input, k=k, dim=dim)\n', (19535, 19556), True, 'import oneflow.experimental as flow\n'), ((20070, 20115), 'oneflow.experimental.topk', 'flow.topk', (['input'], {'k': 'k', 'dim': 'dim', 'largest': '(False)'}), '(input, k=k, dim=dim, largest=False)\n', (20079, 20115), True, 'import oneflow.experimental as flow\n'), ((20472, 20485), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (20483, 20485), False, 'from collections import OrderedDict\n'), ((20693, 20716), 'numpy.random.default_rng', 'np.random.default_rng', ([], {}), '()\n', (20714, 20716), True, 'import numpy as np\n'), ((20765, 20785), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (20775, 20785), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((22927, 22942), 'unittest.main', 'unittest.main', ([], {}), '()\n', (22940, 22942), False, 'import unittest\n'), ((2441, 2454), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2452, 2454), False, 'from collections import OrderedDict\n'), ((2782, 2802), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (2792, 2802), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((2255, 2298), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (2296, 2298), True, 'import oneflow.experimental as flow\n'), ((2911, 2934), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (2926, 2934), True, 'import numpy as np\n'), ((3183, 3206), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (3198, 3206), True, 'import numpy as np\n'), ((3603, 3616), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3614, 3616), False, 'from collections import OrderedDict\n'), ((3841, 3861), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (3851, 3861), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((3427, 3470), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (3468, 3470), True, 'import oneflow.experimental as flow\n'), ((3979, 4002), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (3994, 4002), True, 'import numpy as np\n'), ((4276, 4299), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (4291, 4299), True, 'import numpy as np\n'), ((4764, 4777), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4775, 4777), False, 'from collections import OrderedDict\n'), ((5002, 5022), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (5012, 5022), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((4588, 4631), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (4629, 4631), True, 'import oneflow.experimental as flow\n'), ((5127, 5150), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (5142, 5150), True, 'import numpy as np\n'), ((5838, 5861), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (5853, 5861), True, 'import numpy as np\n'), ((6351, 6364), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (6362, 6364), False, 'from collections import OrderedDict\n'), ((6575, 6595), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (6585, 6595), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((6175, 6218), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (6216, 6218), True, 'import oneflow.experimental as flow\n'), ((7752, 7765), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (7763, 7765), False, 'from collections import OrderedDict\n'), ((8064, 8084), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (8074, 8084), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((7576, 7619), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (7617, 7619), True, 'import oneflow.experimental as flow\n'), ((9064, 9077), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (9075, 9077), False, 'from collections import OrderedDict\n'), ((9269, 9289), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (9279, 9289), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((8886, 8929), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (8927, 8929), True, 'import oneflow.experimental as flow\n'), ((9458, 9473), 'numpy.sqrt', 'np.sqrt', (['np_arr'], {}), '(np_arr)\n', (9465, 9473), True, 'import numpy as np\n'), ((10294, 10307), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (10305, 10307), False, 'from collections import OrderedDict\n'), ((10501, 10521), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (10511, 10521), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((10114, 10157), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (10155, 10157), True, 'import oneflow.experimental as flow\n'), ((11460, 11473), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (11471, 11473), False, 'from collections import OrderedDict\n'), ((11669, 11689), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (11679, 11689), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((11278, 11321), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (11319, 11321), True, 'import oneflow.experimental as flow\n'), ((11807, 11830), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (11822, 11830), True, 'import numpy as np\n'), ((12146, 12169), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (12161, 12169), True, 'import numpy as np\n'), ((12682, 12695), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (12693, 12695), False, 'from collections import OrderedDict\n'), ((12920, 12940), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (12930, 12940), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((12506, 12549), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (12547, 12549), True, 'import oneflow.experimental as flow\n'), ((13041, 13064), 'numpy.random.random', 'np.random.random', (['shape'], {}), '(shape)\n', (13057, 13064), True, 'import numpy as np\n'), ((13403, 13429), 'numpy.sqrt', 'np.sqrt', (['(1 - np_input ** 2)'], {}), '(1 - np_input ** 2)\n', (13410, 13429), True, 'import numpy as np\n'), ((13578, 13601), 'numpy.random.random', 'np.random.random', (['shape'], {}), '(shape)\n', (13594, 13601), True, 'import numpy as np\n'), ((13941, 13967), 'numpy.sqrt', 'np.sqrt', (['(1 - np_input ** 2)'], {}), '(1 - np_input ** 2)\n', (13948, 13967), True, 'import numpy as np\n'), ((14261, 14274), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (14272, 14274), False, 'from collections import OrderedDict\n'), ((14396, 14416), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (14406, 14416), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((14083, 14126), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (14124, 14126), True, 'import oneflow.experimental as flow\n'), ((15723, 15749), 'numpy.sqrt', 'np.sqrt', (['(1 + np_input ** 2)'], {}), '(1 + np_input ** 2)\n', (15730, 15749), True, 'import numpy as np\n'), ((16258, 16284), 'numpy.sqrt', 'np.sqrt', (['(1 + np_input ** 2)'], {}), '(1 + np_input ** 2)\n', (16265, 16284), True, 'import numpy as np\n'), ((16580, 16593), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (16591, 16593), False, 'from collections import OrderedDict\n'), ((16715, 16735), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (16725, 16735), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((16400, 16443), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (16441, 16443), True, 'import oneflow.experimental as flow\n'), ((18344, 18371), 'numpy.random.randn', 'np.random.randn', (['(2)', '(6)', '(5)', '(7)'], {}), '(2, 6, 5, 7)\n', (18359, 18371), True, 'import numpy as np\n'), ((18868, 18895), 'numpy.random.randn', 'np.random.randn', (['(2)', '(6)', '(5)', '(7)'], {}), '(2, 6, 5, 7)\n', (18883, 18895), True, 'import numpy as np\n'), ((19391, 19418), 'numpy.random.randn', 'np.random.randn', (['(2)', '(6)', '(5)', '(7)'], {}), '(2, 6, 5, 7)\n', (19406, 19418), True, 'import numpy as np\n'), ((19915, 19942), 'numpy.random.randn', 'np.random.randn', (['(2)', '(6)', '(5)', '(7)'], {}), '(2, 6, 5, 7)\n', (19930, 19942), True, 'import numpy as np\n'), ((21233, 21281), 'oneflow.experimental.topk', 'flow.topk', (['input'], {'k': 'k', 'dim': 'axis', 'largest': 'largest'}), '(input, k=k, dim=axis, largest=largest)\n', (21242, 21281), True, 'import oneflow.experimental as flow\n'), ((21910, 21930), 'oneflow.experimental.pow', 'flow.pow', (['input', '(2.1)'], {}), '(input, 2.1)\n', (21918, 21930), True, 'import oneflow.experimental as flow\n'), ((21658, 21701), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (21699, 21701), True, 'import oneflow.experimental as flow\n'), ((22541, 22554), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (22552, 22554), False, 'from collections import OrderedDict\n'), ((22832, 22852), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (22842, 22852), False, 'from test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n'), ((22363, 22406), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (22404, 22406), True, 'import oneflow.experimental as flow\n'), ((2012, 2031), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (2023, 2031), True, 'import oneflow.experimental as flow\n'), ((2943, 2962), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (2954, 2962), True, 'import oneflow.experimental as flow\n'), ((3235, 3254), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (3246, 3254), True, 'import oneflow.experimental as flow\n'), ((4031, 4050), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (4042, 4050), True, 'import oneflow.experimental as flow\n'), ((4344, 4363), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (4355, 4363), True, 'import oneflow.experimental as flow\n'), ((5211, 5230), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (5222, 5230), True, 'import oneflow.experimental as flow\n'), ((5568, 5587), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (5579, 5587), True, 'import oneflow.experimental as flow\n'), ((5906, 5925), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (5917, 5925), True, 'import oneflow.experimental as flow\n'), ((6756, 6775), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (6767, 6775), True, 'import oneflow.experimental as flow\n'), ((7047, 7066), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (7058, 7066), True, 'import oneflow.experimental as flow\n'), ((7350, 7369), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (7361, 7369), True, 'import oneflow.experimental as flow\n'), ((8299, 8318), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (8310, 8318), True, 'import oneflow.experimental as flow\n'), ((8609, 8628), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (8620, 8628), True, 'import oneflow.experimental as flow\n'), ((9513, 9532), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (9524, 9532), True, 'import oneflow.experimental as flow\n'), ((9819, 9838), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (9830, 9838), True, 'import oneflow.experimental as flow\n'), ((10712, 10731), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (10723, 10731), True, 'import oneflow.experimental as flow\n'), ((11023, 11042), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (11034, 11042), True, 'import oneflow.experimental as flow\n'), ((11859, 11878), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (11870, 11878), True, 'import oneflow.experimental as flow\n'), ((12214, 12233), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (12225, 12233), True, 'import oneflow.experimental as flow\n'), ((13145, 13164), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (13156, 13164), True, 'import oneflow.experimental as flow\n'), ((13681, 13700), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (13692, 13700), True, 'import oneflow.experimental as flow\n'), ((15463, 15482), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (15474, 15482), True, 'import oneflow.experimental as flow\n'), ((15996, 16015), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (16007, 16015), True, 'import oneflow.experimental as flow\n'), ((18400, 18419), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (18411, 18419), True, 'import oneflow.experimental as flow\n'), ((18924, 18943), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (18935, 18943), True, 'import oneflow.experimental as flow\n'), ((19447, 19466), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (19458, 19466), True, 'import oneflow.experimental as flow\n'), ((19971, 19990), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (19982, 19990), True, 'import oneflow.experimental as flow\n'), ((21843, 21871), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6]'], {}), '([1, 2, 3, 4, 5, 6])\n', (21851, 21871), True, 'import numpy as np\n'), ((22129, 22157), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6]'], {}), '([1, 2, 3, 4, 5, 6])\n', (22137, 22157), True, 'import numpy as np\n'), ((1233, 1252), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (1244, 1252), True, 'import oneflow.experimental as flow\n'), ((20920, 20942), 'numpy.unique', 'np.unique', (['random_data'], {}), '(random_data)\n', (20929, 20942), True, 'import numpy as np\n'), ((21168, 21187), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (21179, 21187), True, 'import oneflow.experimental as flow\n'), ((945, 964), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (956, 964), True, 'import oneflow.experimental as flow\n')] |
#-*- coding:utf-8 -*-
"""
@author: scorpio.lu
@datetime:2020-06-24 10:20
@software: PyCharm
@contact: <EMAIL>
----------
路有敬亭山
----------
"""
import oneflow as flow
import numpy as np
import cv2
import os
from .reid_model import resreid
func_config = flow.FunctionConfig()
func_config.default_data_type(flow.float)
#flow.config.gpu_device_num(args.gpu_num_per_node)
batch_size =1
# batch_size>=max(len(each_frame(bbox)))
#input_blob = flow.MirroredTensorDef((batch_size, 3, 256, 128), dtype=flow.float)
input_blob = flow.FixedTensorDef((batch_size, 3, 256, 128), dtype=flow.float)
def resize_image(img, origin_h, origin_w, image_height, image_width):
w = image_width
h = image_height
resized=np.zeros((3, image_height, image_width), dtype=np.float32)
part=np.zeros((3, origin_h, image_width), dtype = np.float32)
w_scale = (float)(origin_w - 1) / (w - 1)
h_scale = (float)(origin_h - 1) / (h - 1)
for c in range(w):
if c == w-1 or origin_w == 1:
val = img[:, :, origin_w-1]
else:
sx = c * w_scale
ix = int(sx)
dx = sx - ix
val = (1 - dx) * img[:, :, ix] + dx * img[:, :, ix+1]
part[:, :, c] = val
for r in range(h):
sy = r * h_scale
iy = int(sy)
dy = sy - iy
val = (1-dy)*part[:, iy, :]
resized[:, r, :] = val
if r==h-1 or origin_h==1:
continue
resized[:, r, :] = resized[:, r, :] + dy * part[:, iy+1, :]
return resized
def batch_image_preprocess(imgs, img_height, img_width):
result_list = []
base = np.ones([img_height, img_width])
norm_mean = [base * 0.485, base * 0.456, base * 0.406] # imagenet mean
norm_std = [0.229, 0.224, 0.225] # imagenet std
for img in imgs:
img = img.transpose(2, 0, 1).astype(np.float32) # hwc->chw
img = img / 255 # /255 # to tensor
img[[0, 1, 2], :, :] = img[[2, 1, 0], :, :] # bgr2rgb
w = img_width
h = img_height
origin_h = img.shape[1]
origin_w = img.shape[2]
resize_img = resize_image(img, origin_h, origin_w, h, w)
# normalize
resize_img[0] = (resize_img[0] - norm_mean[0])/ norm_std[0]
resize_img[1] = (resize_img[1] - norm_mean[1]) / norm_std[1]
resize_img[2] = (resize_img[2] - norm_mean[2]) / norm_std[2]
result_list.append(resize_img)
results = np.asarray(result_list).astype(np.float32)
return results
def one_batch_image_preprocess(img, img_height, img_width):
result_list = []
base = np.ones([img_height, img_width])
norm_mean = [base * 0.485, base * 0.456, base * 0.406] # imagenet mean
norm_std = [0.229, 0.224, 0.225] # imagenet std
img = img.transpose(2, 0, 1).astype(np.float32) # hwc->chw
img = img / 255 # /255 # to tensor
img[[0, 1, 2], :, :] = img[[2, 1, 0], :, :] # bgr2rgb
w = img_width
h = img_height
origin_h = img.shape[1]
origin_w = img.shape[2]
resize_img = resize_image(img, origin_h, origin_w, h, w)
# normalize
resize_img[0] = (resize_img[0] - norm_mean[0])/ norm_std[0]
resize_img[1] = (resize_img[1] - norm_mean[1]) / norm_std[1]
resize_img[2] = (resize_img[2] - norm_mean[2]) / norm_std[2]
result_list.append(resize_img)
results = np.asarray(result_list).astype(np.float32)
return results
@flow.global_function(func_config)
def reid_eval_job(image=input_blob):
features = resreid(image, trainable=False)
return features
def main():
print("Loading data from {}")
dataset = np.random.randint(0, 255, 2*64*32*3).reshape((2, 64, 32, 3))
print(dataset.shape)
model_load_dir = '../model_restrack'
assert os.path.isdir(model_load_dir)
print("Restoring model from {}.".format(model_load_dir))
check_point = flow.train.CheckPoint()
check_point.load(model_load_dir)
print('extracting features...')
dataset = batch_image_preprocess(dataset, 256, 128)
feature = reid_eval_job([dataset]).get()
print(feature.ndarray_list_[0])
return feature.ndarray_list_[0]
if __name__ == "__main__":
main() | [
"oneflow.FunctionConfig",
"oneflow.train.CheckPoint",
"oneflow.global_function",
"oneflow.FixedTensorDef"
] | [((296, 317), 'oneflow.FunctionConfig', 'flow.FunctionConfig', ([], {}), '()\n', (315, 317), True, 'import oneflow as flow\n'), ((562, 626), 'oneflow.FixedTensorDef', 'flow.FixedTensorDef', (['(batch_size, 3, 256, 128)'], {'dtype': 'flow.float'}), '((batch_size, 3, 256, 128), dtype=flow.float)\n', (581, 626), True, 'import oneflow as flow\n'), ((3426, 3459), 'oneflow.global_function', 'flow.global_function', (['func_config'], {}), '(func_config)\n', (3446, 3459), True, 'import oneflow as flow\n'), ((751, 809), 'numpy.zeros', 'np.zeros', (['(3, image_height, image_width)'], {'dtype': 'np.float32'}), '((3, image_height, image_width), dtype=np.float32)\n', (759, 809), True, 'import numpy as np\n'), ((819, 873), 'numpy.zeros', 'np.zeros', (['(3, origin_h, image_width)'], {'dtype': 'np.float32'}), '((3, origin_h, image_width), dtype=np.float32)\n', (827, 873), True, 'import numpy as np\n'), ((1646, 1678), 'numpy.ones', 'np.ones', (['[img_height, img_width]'], {}), '([img_height, img_width])\n', (1653, 1678), True, 'import numpy as np\n'), ((2617, 2649), 'numpy.ones', 'np.ones', (['[img_height, img_width]'], {}), '([img_height, img_width])\n', (2624, 2649), True, 'import numpy as np\n'), ((3764, 3793), 'os.path.isdir', 'os.path.isdir', (['model_load_dir'], {}), '(model_load_dir)\n', (3777, 3793), False, 'import os\n'), ((3873, 3896), 'oneflow.train.CheckPoint', 'flow.train.CheckPoint', ([], {}), '()\n', (3894, 3896), True, 'import oneflow as flow\n'), ((2461, 2484), 'numpy.asarray', 'np.asarray', (['result_list'], {}), '(result_list)\n', (2471, 2484), True, 'import numpy as np\n'), ((3361, 3384), 'numpy.asarray', 'np.asarray', (['result_list'], {}), '(result_list)\n', (3371, 3384), True, 'import numpy as np\n'), ((3626, 3668), 'numpy.random.randint', 'np.random.randint', (['(0)', '(255)', '(2 * 64 * 32 * 3)'], {}), '(0, 255, 2 * 64 * 32 * 3)\n', (3643, 3668), True, 'import numpy as np\n')] |
import oneflow as flow
import numpy as np
def spectral_norm(w, iteration=1):
w_shape = w.shape
w = np.reshape(w, [-1, w_shape[0]])
# u = flow.get_variable('u', shape=[1, w_shape[0]], initializer=flow.random_normal_initializer(), trainable=False)
u = np.random.random([1, w_shape[0]])
u_hat = u
v_hat = None
for i in range(iteration):
v_ = np.matmul(u_hat, np.transpose(w))
v_hat = v_/np.linalg.norm(v_)
u_ = np.matmul(v_hat, w)
u_hat = u_/np.linalg.norm(u_)
sigma = np.matmul(np.matmul(v_hat, w), np.transpose(u_hat))
w_norm = w/sigma
w_norm = np.reshape(w_norm, w_shape)
return w_norm
def sn():
weight_dict = flow.get_all_variables()
weight_copy = {}
for k in weight_dict.keys():
weight_copy[k] = np.zeros(weight_dict[k].numpy().shape)
for k in weight_dict.keys():
weight_temp = weight_dict[k].numpy()
if len(weight_temp.shape) == 4: # convolution kernel
weight_copy[k] = spectral_norm(weight_temp).astype(np.float32)
else:
weight_copy[k] = weight_temp
# print(weight_temp.shape)
# print(len(weight_temp.shape))
# weight_copy[k] = spectral_norm(weight_temp).astype(np.float32)
# print(weight_dict[k].dtype)
# print(weight_copy[k].dtype)
flow.load_variables(weight_copy) | [
"oneflow.load_variables",
"oneflow.get_all_variables"
] | [((108, 139), 'numpy.reshape', 'np.reshape', (['w', '[-1, w_shape[0]]'], {}), '(w, [-1, w_shape[0]])\n', (118, 139), True, 'import numpy as np\n'), ((268, 301), 'numpy.random.random', 'np.random.random', (['[1, w_shape[0]]'], {}), '([1, w_shape[0]])\n', (284, 301), True, 'import numpy as np\n'), ((622, 649), 'numpy.reshape', 'np.reshape', (['w_norm', 'w_shape'], {}), '(w_norm, w_shape)\n', (632, 649), True, 'import numpy as np\n'), ((697, 721), 'oneflow.get_all_variables', 'flow.get_all_variables', ([], {}), '()\n', (719, 721), True, 'import oneflow as flow\n'), ((1340, 1372), 'oneflow.load_variables', 'flow.load_variables', (['weight_copy'], {}), '(weight_copy)\n', (1359, 1372), True, 'import oneflow as flow\n'), ((464, 483), 'numpy.matmul', 'np.matmul', (['v_hat', 'w'], {}), '(v_hat, w)\n', (473, 483), True, 'import numpy as np\n'), ((545, 564), 'numpy.matmul', 'np.matmul', (['v_hat', 'w'], {}), '(v_hat, w)\n', (554, 564), True, 'import numpy as np\n'), ((566, 585), 'numpy.transpose', 'np.transpose', (['u_hat'], {}), '(u_hat)\n', (578, 585), True, 'import numpy as np\n'), ((395, 410), 'numpy.transpose', 'np.transpose', (['w'], {}), '(w)\n', (407, 410), True, 'import numpy as np\n'), ((431, 449), 'numpy.linalg.norm', 'np.linalg.norm', (['v_'], {}), '(v_)\n', (445, 449), True, 'import numpy as np\n'), ((503, 521), 'numpy.linalg.norm', 'np.linalg.norm', (['u_'], {}), '(u_)\n', (517, 521), True, 'import numpy as np\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.
"""
# RUN: python3 %s | FileCheck %s
# CHECK-NOT: oneflow.pad
import unittest
import numpy as np
import os
os.environ["ONEFLOW_MLIR_ENABLE_ROUND_TRIP"] = "1"
import oneflow as flow
import oneflow.unittest
def do_pad_conv_graph(test_case, with_cuda, with_bias, with_nchw=True):
if with_nchw:
x = flow.randn(2, 3, 4, 5)
else:
x = flow.randn(2, 4, 5, 3)
conv = flow.nn.Conv2d(3, 3, 2, 1, bias=with_bias)
if with_cuda:
x = x.cuda()
conv.to("cuda")
if with_nchw:
pad_x = flow.nn.functional.pad(x, (1, 1, 1, 1))
else:
pad_x = flow.nn.functional.pad(x, (0, 0, 1, 1, 1, 1))
eager_conv_x = conv(pad_x)
class GraphToRun(flow.nn.Graph):
def __init__(self):
super().__init__()
self.conv = conv
def build(self, x):
if with_nchw:
pad_x = flow.nn.functional.pad(x, (1, 1, 1, 1))
else:
pad_x = flow.nn.functional.pad(x, (0, 0, 1, 1, 1, 1))
return self.conv(pad_x)
graph_to_run = GraphToRun()
lazy_conv_x = graph_to_run(x)
test_case.assertTrue(np.array_equal(eager_conv_x.numpy(), lazy_conv_x.numpy()))
@flow.unittest.skip_unless_1n1d()
class TestFusePadConv(oneflow.unittest.TestCase):
def test_pad_conv_graph(test_case):
do_pad_conv_graph(test_case, True, True)
do_pad_conv_graph(test_case, False, True)
do_pad_conv_graph(test_case, True, False)
do_pad_conv_graph(test_case, False, False)
do_pad_conv_graph(test_case, True, False, True)
do_pad_conv_graph(test_case, False, False, True)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.nn.Conv2d",
"oneflow.nn.functional.pad",
"oneflow.randn",
"oneflow.unittest.skip_unless_1n1d"
] | [((1785, 1817), 'oneflow.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (1815, 1817), True, 'import oneflow as flow\n'), ((978, 1020), 'oneflow.nn.Conv2d', 'flow.nn.Conv2d', (['(3)', '(3)', '(2)', '(1)'], {'bias': 'with_bias'}), '(3, 3, 2, 1, bias=with_bias)\n', (992, 1020), True, 'import oneflow as flow\n'), ((2254, 2269), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2267, 2269), False, 'import unittest\n'), ((899, 921), 'oneflow.randn', 'flow.randn', (['(2)', '(3)', '(4)', '(5)'], {}), '(2, 3, 4, 5)\n', (909, 921), True, 'import oneflow as flow\n'), ((944, 966), 'oneflow.randn', 'flow.randn', (['(2)', '(4)', '(5)', '(3)'], {}), '(2, 4, 5, 3)\n', (954, 966), True, 'import oneflow as flow\n'), ((1119, 1158), 'oneflow.nn.functional.pad', 'flow.nn.functional.pad', (['x', '(1, 1, 1, 1)'], {}), '(x, (1, 1, 1, 1))\n', (1141, 1158), True, 'import oneflow as flow\n'), ((1185, 1230), 'oneflow.nn.functional.pad', 'flow.nn.functional.pad', (['x', '(0, 0, 1, 1, 1, 1)'], {}), '(x, (0, 0, 1, 1, 1, 1))\n', (1207, 1230), True, 'import oneflow as flow\n'), ((1467, 1506), 'oneflow.nn.functional.pad', 'flow.nn.functional.pad', (['x', '(1, 1, 1, 1)'], {}), '(x, (1, 1, 1, 1))\n', (1489, 1506), True, 'import oneflow as flow\n'), ((1549, 1594), 'oneflow.nn.functional.pad', 'flow.nn.functional.pad', (['x', '(0, 0, 1, 1, 1, 1)'], {}), '(x, (0, 0, 1, 1, 1, 1))\n', (1571, 1594), 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 os
import tempfile
import unittest
from collections import OrderedDict
import numpy as np
from optimizer_test_util import clip_grad_norm_np
from oneflow.test_utils.test_util import GenArgList
import oneflow as flow
def compare_with_numpy_lamb(
test_case,
device,
x_shape,
learning_rate,
train_iters,
betas,
weight_decay,
eps,
do_bias_correction,
adam_w_mode,
clip_grad_max_norm,
clip_grad_norm_type,
reload_state_step,
save_load_by_pickle,
):
np.random.seed(1000)
random_grad_seq = []
for _ in range(train_iters):
random_grad_seq.append(np.random.uniform(size=x_shape).astype(np.float32))
init_value = np.random.uniform(size=x_shape).astype(np.float32)
def train_by_oneflow():
x = flow.nn.Parameter(flow.Tensor(init_value, device=flow.device(device)))
optim_kwargs = {
"params": [x],
"lr": learning_rate,
"betas": betas,
"eps": eps,
"weight_decay": weight_decay,
"adam_w_mode": adam_w_mode,
"do_bias_correction": do_bias_correction,
}
if clip_grad_max_norm != -1:
optim_kwargs["clip_grad_max_norm"] = clip_grad_max_norm
optim_kwargs["clip_grad_norm_type"] = clip_grad_norm_type
lamb = flow.optim.LAMB([optim_kwargs])
def train_one_iter(grad):
grad_tensor = flow.tensor(
grad,
dtype=flow.float32,
requires_grad=False,
device=flow.device(device),
)
loss = flow.sum(x * grad_tensor)
loss.backward()
if clip_grad_max_norm != -1:
lamb.clip_grad()
lamb.step()
lamb.zero_grad()
for i in range(train_iters):
train_one_iter(random_grad_seq[i])
if i == reload_state_step:
state_dict = lamb.state_dict()
lamb = flow.optim.LAMB([optim_kwargs])
if save_load_by_pickle:
with tempfile.TemporaryDirectory() as save_dir:
flow.save(state_dict, save_dir)
state_dict = flow.load(save_dir)
lamb.load_state_dict(state_dict)
return x
def train_by_numpy():
x = init_value
mt = np.zeros_like(x)
vt = np.zeros_like(x)
beta1 = betas[0]
beta2 = betas[1]
if adam_w_mode:
l2 = 0
wd = weight_decay
else:
l2 = weight_decay
wd = 0
def np_train_one_iter(step, grad):
if clip_grad_max_norm != -1:
_, grad = clip_grad_norm_np(
grad, clip_grad_max_norm, clip_grad_norm_type
)
grad = grad + l2 * x
bias_correction1 = 1.0
bias_correction2 = 1.0
if do_bias_correction:
bias_correction1 = 1.0 - np.power(beta1, step + 1)
bias_correction2 = 1.0 - np.power(beta2, step + 1)
m = beta1 * mt + (1 - beta1) * grad
v = beta2 * vt + (1 - beta2) * grad * grad
denom = np.sqrt(v) / np.sqrt(bias_correction2) + eps
adam_diff = m / bias_correction1 / denom
w_norm = np.linalg.norm(x, ord=2)
g_norm = np.linalg.norm(adam_diff, ord=2)
if w_norm > 0 and g_norm > 0:
trust_ratio = w_norm / g_norm
else:
trust_ratio = 1.0
param = x - learning_rate * trust_ratio * (adam_diff + wd * x)
return (param, m, v)
for i in range(train_iters):
(x, mt, vt) = np_train_one_iter(i, random_grad_seq[i])
return x
of_res = train_by_oneflow().numpy()
np_res = train_by_numpy()
test_case.assertTrue(
np.allclose(of_res.flatten(), np_res.flatten(), rtol=1e-3, atol=1e-3)
)
@flow.unittest.skip_unless_1n1d()
class TestLamb(flow.unittest.TestCase):
def test_lamb(test_case):
arg_dict = OrderedDict()
arg_dict["device"] = ["cuda"]
if os.getenv("ONEFLOW_TEST_CPU_ONLY"):
arg_dict["device"] = ["cpu"]
arg_dict["x_shape"] = [(1,)]
arg_dict["learning_rate"] = [0.1, 1e-3]
arg_dict["train_iters"] = [10]
arg_dict["betas"] = [(0.99, 0.9)]
arg_dict["weight_decay"] = [0.001, 0.1]
arg_dict["eps"] = [1e-6]
arg_dict["do_bias_correction"] = [True, False]
arg_dict["adam_w_mode"] = [True, False]
# NOTE(l1aoxingyu): max_norm = -1 means no clip grad
arg_dict["clip_grad_max_norm"] = [-1, 0.0, 0.5, 1.0]
arg_dict["clip_grad_norm_type"] = ["inf", "-inf", 0.0, 1.0, 2.0, 3.5]
arg_dict["reload_state_step"] = [5]
arg_dict["save_load_by_pickle"] = [False, True]
for arg in GenArgList(arg_dict):
compare_with_numpy_lamb(test_case, *arg)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.save",
"oneflow.optim.LAMB",
"oneflow.sum",
"oneflow.device",
"oneflow.load",
"oneflow.unittest.skip_unless_1n1d",
"oneflow.test_utils.test_util.GenArgList"
] | [((4563, 4595), 'oneflow.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (4593, 4595), True, 'import oneflow as flow\n'), ((1105, 1125), 'numpy.random.seed', 'np.random.seed', (['(1000)'], {}), '(1000)\n', (1119, 1125), True, 'import numpy as np\n'), ((5603, 5618), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5616, 5618), False, 'import unittest\n'), ((1924, 1955), 'oneflow.optim.LAMB', 'flow.optim.LAMB', (['[optim_kwargs]'], {}), '([optim_kwargs])\n', (1939, 1955), True, 'import oneflow as flow\n'), ((2960, 2976), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (2973, 2976), True, 'import numpy as np\n'), ((2990, 3006), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (3003, 3006), True, 'import numpy as np\n'), ((4685, 4698), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4696, 4698), False, 'from collections import OrderedDict\n'), ((4748, 4782), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (4757, 4782), False, 'import os\n'), ((5495, 5515), 'oneflow.test_utils.test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (5505, 5515), False, 'from oneflow.test_utils.test_util import GenArgList\n'), ((1285, 1316), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'x_shape'}), '(size=x_shape)\n', (1302, 1316), True, 'import numpy as np\n'), ((2203, 2228), 'oneflow.sum', 'flow.sum', (['(x * grad_tensor)'], {}), '(x * grad_tensor)\n', (2211, 2228), True, 'import oneflow as flow\n'), ((3928, 3952), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {'ord': '(2)'}), '(x, ord=2)\n', (3942, 3952), True, 'import numpy as np\n'), ((3974, 4006), 'numpy.linalg.norm', 'np.linalg.norm', (['adam_diff'], {'ord': '(2)'}), '(adam_diff, ord=2)\n', (3988, 4006), True, 'import numpy as np\n'), ((2578, 2609), 'oneflow.optim.LAMB', 'flow.optim.LAMB', (['[optim_kwargs]'], {}), '([optim_kwargs])\n', (2593, 2609), True, 'import oneflow as flow\n'), ((3304, 3368), 'optimizer_test_util.clip_grad_norm_np', 'clip_grad_norm_np', (['grad', 'clip_grad_max_norm', 'clip_grad_norm_type'], {}), '(grad, clip_grad_max_norm, clip_grad_norm_type)\n', (3321, 3368), False, 'from optimizer_test_util import clip_grad_norm_np\n'), ((1216, 1247), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'x_shape'}), '(size=x_shape)\n', (1233, 1247), True, 'import numpy as np\n'), ((1426, 1445), 'oneflow.device', 'flow.device', (['device'], {}), '(device)\n', (1437, 1445), True, 'import oneflow as flow\n'), ((2148, 2167), 'oneflow.device', 'flow.device', (['device'], {}), '(device)\n', (2159, 2167), True, 'import oneflow as flow\n'), ((3589, 3614), 'numpy.power', 'np.power', (['beta1', '(step + 1)'], {}), '(beta1, step + 1)\n', (3597, 3614), True, 'import numpy as np\n'), ((3656, 3681), 'numpy.power', 'np.power', (['beta2', '(step + 1)'], {}), '(beta2, step + 1)\n', (3664, 3681), True, 'import numpy as np\n'), ((3807, 3817), 'numpy.sqrt', 'np.sqrt', (['v'], {}), '(v)\n', (3814, 3817), True, 'import numpy as np\n'), ((3820, 3845), 'numpy.sqrt', 'np.sqrt', (['bias_correction2'], {}), '(bias_correction2)\n', (3827, 3845), True, 'import numpy as np\n'), ((2675, 2704), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (2702, 2704), False, 'import tempfile\n'), ((2742, 2773), 'oneflow.save', 'flow.save', (['state_dict', 'save_dir'], {}), '(state_dict, save_dir)\n', (2751, 2773), True, 'import oneflow as flow\n'), ((2811, 2830), 'oneflow.load', 'flow.load', (['save_dir'], {}), '(save_dir)\n', (2820, 2830), True, 'import oneflow as flow\n')] |
from __future__ import absolute_import
from __future__ import division
import oneflow.experimental as flow
import numpy as np
class TripletLoss(flow.nn.Module):
"""Triplet loss with hard positive/negative mining.
Reference:
Hermans et al. In Defense of the Triplet Loss for Person Re-Identification. arXiv:1703.07737.
Imported from `<https://github.com/Cysu/open-reid/blob/master/reid/loss/triplet.py>`_.
Args:
margin (float, optional): margin for triplet. Default is 0.3.
"""
def __init__(self, margin=0.3):
super(TripletLoss, self).__init__()
self.margin = margin
self.ranking_loss = flow.nn.MarginRankingLoss(margin=margin)
def forward(self, inputs, targets):
"""
Args:
inputs (torch.Tensor): feature matrix with shape (batch_size, feat_dim).
targets (torch.LongTensor): ground truth labels with shape (num_classes).
"""
n = inputs.size(0)
# Compute pairwise distance, replace by the official when merged
dist = flow.pow(inputs, 2).sum(dim=1).expand(n, n)
dist = dist + flow.transpose(dist, dim0=1, dim1=0)
temp1 = -2 * flow.matmul(inputs, flow.transpose(inputs, dim0=1, dim1=0))
dist = flow.add(dist, temp1)
dist = flow.sqrt(flow.clamp(dist, min=1e-12))
# For each anchor, find the hardest positive and negative
mask = targets.expand(n, n).eq(
flow.Tensor(flow.transpose(targets.expand(n, n), dim0=1, dim1=0))
)
dist_ap, dist_an = [], []
y1 = flow.zeros((1, n), dtype=flow.float32).to("cuda")
y2 = flow.Tensor(np.exp(100 * np.ones((1, n)))).to("cuda")
for i in range(n):
temp_dist = flow.slice(dist, [(i, i + 1, 1)])
temp_mask = flow.slice(mask, [(i, i + 1, 1)])
temp_mask_rev = flow.slice(1 - mask, [(i, i + 1, 1)])
dist_ap.append(temp_mask.where(temp_dist, y1).max())
dist_an.append(temp_mask_rev.where(temp_dist, y2).min())
dist_ap = flow.cat(dist_ap)
dist_an = flow.cat(dist_an)
# Compute ranking hinge loss
y = flow.ones_like(dist_an)
return self.ranking_loss(dist_an, dist_ap, y)
class CrossEntropyLossLS(flow.nn.Module):
r"""Cross entropy loss with label smoothing regularizer.
Reference:
<NAME> al. Rethinking the Inception Architecture for Computer Vision. CVPR 2016.
With label smoothing, the label :math:`y` for a class is computed by
.. math::
\begin{equation}
(1 - \epsilon) \times y + \frac{\epsilon}{K},
\end{equation}
where :math:`K` denotes the number of classes and :math:`\epsilon` is a weight. When
:math:`\epsilon = 0`, the loss function reduces to the normal cross entropy.
Args:
num_classes (int): number of classes.
epsilon (float, optional): weight. Default is 0.1.
use_gpu (bool, optional): whether to use gpu devices. Default is True.
label_smooth (bool, optional): whether to apply label smoothing. Default is True.
"""
def __init__(self, num_classes, epsilon=0.1):
super(CrossEntropyLossLS, self).__init__()
self.num_classes = num_classes
self.epsilon = epsilon
self.logsoftmax = flow.nn.LogSoftmax(dim=1)
def forward(self, inputs, targets):
"""
Args:
inputs (torch.Tensor): prediction matrix (before softmax) with
shape (batch_size, num_classes).
targets (torch.LongTensor): ground truth labels with shape (batch_size).
Each position contains the label index.
"""
log_probs = self.logsoftmax(inputs)
targets = flow.tensor(
np.eye(self.num_classes)[targets.numpy()], dtype=flow.float32
)
targets = targets.to("cuda")
targets = (1 - self.epsilon) * targets + self.epsilon / self.num_classes
loss = (-targets * log_probs).mean(0).sum()
return loss
| [
"oneflow.experimental.add",
"oneflow.experimental.slice",
"oneflow.experimental.pow",
"oneflow.experimental.nn.LogSoftmax",
"oneflow.experimental.nn.MarginRankingLoss",
"oneflow.experimental.ones_like",
"oneflow.experimental.cat",
"oneflow.experimental.clamp",
"oneflow.experimental.zeros",
"oneflow.experimental.transpose"
] | [((658, 698), 'oneflow.experimental.nn.MarginRankingLoss', 'flow.nn.MarginRankingLoss', ([], {'margin': 'margin'}), '(margin=margin)\n', (683, 698), True, 'import oneflow.experimental as flow\n'), ((1264, 1285), 'oneflow.experimental.add', 'flow.add', (['dist', 'temp1'], {}), '(dist, temp1)\n', (1272, 1285), True, 'import oneflow.experimental as flow\n'), ((2061, 2078), 'oneflow.experimental.cat', 'flow.cat', (['dist_ap'], {}), '(dist_ap)\n', (2069, 2078), True, 'import oneflow.experimental as flow\n'), ((2097, 2114), 'oneflow.experimental.cat', 'flow.cat', (['dist_an'], {}), '(dist_an)\n', (2105, 2114), True, 'import oneflow.experimental as flow\n'), ((2165, 2188), 'oneflow.experimental.ones_like', 'flow.ones_like', (['dist_an'], {}), '(dist_an)\n', (2179, 2188), True, 'import oneflow.experimental as flow\n'), ((3306, 3331), 'oneflow.experimental.nn.LogSoftmax', 'flow.nn.LogSoftmax', ([], {'dim': '(1)'}), '(dim=1)\n', (3324, 3331), True, 'import oneflow.experimental as flow\n'), ((1131, 1167), 'oneflow.experimental.transpose', 'flow.transpose', (['dist'], {'dim0': '(1)', 'dim1': '(0)'}), '(dist, dim0=1, dim1=0)\n', (1145, 1167), True, 'import oneflow.experimental as flow\n'), ((1311, 1338), 'oneflow.experimental.clamp', 'flow.clamp', (['dist'], {'min': '(1e-12)'}), '(dist, min=1e-12)\n', (1321, 1338), True, 'import oneflow.experimental as flow\n'), ((1750, 1783), 'oneflow.experimental.slice', 'flow.slice', (['dist', '[(i, i + 1, 1)]'], {}), '(dist, [(i, i + 1, 1)])\n', (1760, 1783), True, 'import oneflow.experimental as flow\n'), ((1808, 1841), 'oneflow.experimental.slice', 'flow.slice', (['mask', '[(i, i + 1, 1)]'], {}), '(mask, [(i, i + 1, 1)])\n', (1818, 1841), True, 'import oneflow.experimental as flow\n'), ((1870, 1907), 'oneflow.experimental.slice', 'flow.slice', (['(1 - mask)', '[(i, i + 1, 1)]'], {}), '(1 - mask, [(i, i + 1, 1)])\n', (1880, 1907), True, 'import oneflow.experimental as flow\n'), ((1209, 1247), 'oneflow.experimental.transpose', 'flow.transpose', (['inputs'], {'dim0': '(1)', 'dim1': '(0)'}), '(inputs, dim0=1, dim1=0)\n', (1223, 1247), True, 'import oneflow.experimental as flow\n'), ((1581, 1619), 'oneflow.experimental.zeros', 'flow.zeros', (['(1, n)'], {'dtype': 'flow.float32'}), '((1, n), dtype=flow.float32)\n', (1591, 1619), True, 'import oneflow.experimental as flow\n'), ((3763, 3787), 'numpy.eye', 'np.eye', (['self.num_classes'], {}), '(self.num_classes)\n', (3769, 3787), True, 'import numpy as np\n'), ((1065, 1084), 'oneflow.experimental.pow', 'flow.pow', (['inputs', '(2)'], {}), '(inputs, 2)\n', (1073, 1084), True, 'import oneflow.experimental as flow\n'), ((1669, 1684), 'numpy.ones', 'np.ones', (['(1, n)'], {}), '((1, n))\n', (1676, 1684), True, 'import numpy as np\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 oneflow.python.eager.blob_cache as blob_cache_util
from contextlib import contextmanager
def GetDefaultBlobRegister():
return default_blob_register_
class RegisteredBlobAccess(object):
def __init__(self, blob_name, blob_register, blob_object=None):
self.blob_name_ = blob_name
self.blob_register_ = blob_register
if blob_object is None:
blob_object = blob_register.GetObject4BlobName(blob_name)
else:
blob_register.SetObject4BlobName(blob_name, blob_object)
self.blob_object_ = blob_object
self.reference_counter_ = 0
@property
def reference_counter(self):
return self.reference_counter_
def increase_reference_counter(self):
self.reference_counter_ = self.reference_counter_ + 1
def decrease_reference_counter(self):
self.reference_counter_ = self.reference_counter_ - 1
return self.reference_counter_
@property
def blob_object(self):
return self.blob_object_
def __del__(self):
self.blob_register_.ClearObject4BlobName(self.blob_name_)
class BlobRegister(object):
def __init__(self):
self.blob_name2object_ = {}
self.blob_name2access_ = {}
def OpenRegisteredBlobAccess(self, blob_name, blob_object=None):
if blob_name not in self.blob_name2access_:
self.blob_name2access_[blob_name] = RegisteredBlobAccess(
blob_name, self, blob_object
)
access = self.blob_name2access_[blob_name]
access.increase_reference_counter()
return access
def CloseRegisteredBlobAccess(self, blob_name):
if blob_name in self.blob_name2access_:
if self.blob_name2access_[blob_name].decrease_reference_counter() == 0:
del self.blob_name2access_[blob_name]
@property
def blob_name2object(self):
return self.blob_name2object_
def HasObject4BlobName(self, blob_name):
return blob_name in self.blob_name2object
def GetObject4BlobName(self, blob_name):
assert self.HasObject4BlobName(blob_name), "blob_name %s not found" % blob_name
return self.blob_name2object[blob_name]
def SetObject4BlobName(self, blob_name, obj):
assert not self.HasObject4BlobName(blob_name), blob_name
self.blob_name2object[blob_name] = obj
def TrySetObject4BlobName(self, blob_name, obj):
if not self.HasObject4BlobName(blob_name):
self.SetObject4BlobName(blob_name, obj)
def ClearObject4BlobName(self, blob_name):
assert self.HasObject4BlobName(blob_name), "blob_name %s not found" % blob_name
blob_cache_util.TryDisableBlobCache(self.blob_name2object[blob_name])
del self.blob_name2object[blob_name]
def TryClearObject4BlobName(self, blob_name):
if self.HasObject4BlobName(blob_name):
self.ClearObject4BlobName(blob_name)
def ForceReleaseAll(self):
for blob_name, blob_object in self.blob_name2object.items():
print("Forcely release blob %s." % blob_name)
blob_object.__del__()
@contextmanager
def BnInOp2BlobObjectScope(self, op_attribute):
bn_in_op2blob_object = {}
for ibn in op_attribute.input_bns:
lbi = op_attribute.arg_signature.bn_in_op2lbi[ibn]
bn_in_op2blob_object[ibn] = self.GetObject4BlobName(
"%s/%s" % (lbi.op_name, lbi.blob_name)
)
yield bn_in_op2blob_object
for obn in op_attribute.output_bns:
lbi = op_attribute.arg_signature.bn_in_op2lbi[obn]
self.SetObject4BlobName(
"%s/%s" % (lbi.op_name, lbi.blob_name), bn_in_op2blob_object[obn]
)
default_blob_register_ = BlobRegister()
| [
"oneflow.python.eager.blob_cache.TryDisableBlobCache"
] | [((3300, 3369), 'oneflow.python.eager.blob_cache.TryDisableBlobCache', 'blob_cache_util.TryDisableBlobCache', (['self.blob_name2object[blob_name]'], {}), '(self.blob_name2object[blob_name])\n', (3335, 3369), True, 'import oneflow.python.eager.blob_cache as blob_cache_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.
"""
import unittest
from collections import OrderedDict
import numpy as np
from test_util import GenArgList
import oneflow.experimental as flow
def _test_atan2_forward(test_case, shape, scalar, device):
np_input_x = 10 * np.random.rand(*shape)
np_input_y = 10 * np.random.randn(*shape)
of_input_x = flow.Tensor(np_input_x, dtype=flow.float32, device=flow.device(device))
of_input_y = flow.Tensor(np_input_y, dtype=flow.float32, device=flow.device(device))
of_out = flow.atan2(of_input_x, of_input_y)
np_out = np.arctan2(np_input_x, np_input_y)
test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-5, 1e-5))
def _test_atan2_backward(test_case, device):
np_input_x = np.random.rand(2, 3)
np_input_y = np.random.rand(2, 3)
np_y_grad = -1 * np_input_x / (np_input_x * np_input_x + np_input_y * np_input_y)
np_x_grad = np_input_y / (np_input_x * np_input_x + np_input_y * np_input_y)
def test_x_y_grad():
of_input_x = flow.Tensor(
np_input_x,
dtype=flow.float32,
device=flow.device(device),
requires_grad=True,
)
of_input_y = flow.Tensor(
np_input_y,
dtype=flow.float32,
device=flow.device(device),
requires_grad=True,
)
of_out = flow.atan2(of_input_x, of_input_y)
of_out_sum = of_out.sum()
of_out_sum.backward()
test_case.assertTrue(
np.allclose(of_input_x.grad.numpy(), np_x_grad, 1e-4, 1e-4)
)
test_case.assertTrue(
np.allclose(of_input_y.grad.numpy(), np_y_grad, 1e-4, 1e-4)
)
def test_x_grad():
of_input_x = flow.Tensor(
np_input_x,
dtype=flow.float32,
device=flow.device(device),
requires_grad=True,
)
of_input_y = flow.Tensor(
np_input_y, dtype=flow.float32, device=flow.device(device)
)
of_out = flow.atan2(of_input_x, of_input_y)
of_out_sum = of_out.sum()
of_out_sum.backward()
test_case.assertTrue(
np.allclose(of_input_x.grad.numpy(), np_x_grad, 1e-4, 1e-4)
)
def test_y_grad():
of_input_x = flow.Tensor(
np_input_x, dtype=flow.float32, device=flow.device(device)
)
of_input_y = flow.Tensor(
np_input_y,
dtype=flow.float32,
device=flow.device(device),
requires_grad=True,
)
of_out = flow.atan2(of_input_x, of_input_y)
of_out_sum = of_out.sum()
of_out_sum.backward()
test_case.assertTrue(
np.allclose(of_input_y.grad.numpy(), np_y_grad, 1e-4, 1e-4)
)
test_x_y_grad()
test_x_grad()
test_y_grad()
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestAtan2(flow.unittest.TestCase):
def test_atan2_forward(test_case):
arg_dict = OrderedDict()
arg_dict["shape"] = [(2,), (2, 3), (2, 3, 4), (2, 3, 4, 5)]
arg_dict["scalar"] = [2.1, 0.8]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_atan2_forward(test_case, *arg)
def test_atan2_backward(test_case):
arg_dict = OrderedDict()
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
_test_atan2_backward(test_case, *arg)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.experimental.atan2",
"oneflow.experimental.unittest.env.eager_execution_enabled",
"oneflow.experimental.device"
] | [((1104, 1138), 'oneflow.experimental.atan2', 'flow.atan2', (['of_input_x', 'of_input_y'], {}), '(of_input_x, of_input_y)\n', (1114, 1138), True, 'import oneflow.experimental as flow\n'), ((1153, 1187), 'numpy.arctan2', 'np.arctan2', (['np_input_x', 'np_input_y'], {}), '(np_input_x, np_input_y)\n', (1163, 1187), True, 'import numpy as np\n'), ((1331, 1351), 'numpy.random.rand', 'np.random.rand', (['(2)', '(3)'], {}), '(2, 3)\n', (1345, 1351), True, 'import numpy as np\n'), ((1370, 1390), 'numpy.random.rand', 'np.random.rand', (['(2)', '(3)'], {}), '(2, 3)\n', (1384, 1390), True, 'import numpy as np\n'), ((4208, 4223), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4221, 4223), False, 'import unittest\n'), ((840, 862), 'numpy.random.rand', 'np.random.rand', (['*shape'], {}), '(*shape)\n', (854, 862), True, 'import numpy as np\n'), ((886, 909), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (901, 909), True, 'import numpy as np\n'), ((1964, 1998), 'oneflow.experimental.atan2', 'flow.atan2', (['of_input_x', 'of_input_y'], {}), '(of_input_x, of_input_y)\n', (1974, 1998), True, 'import oneflow.experimental as flow\n'), ((2635, 2669), 'oneflow.experimental.atan2', 'flow.atan2', (['of_input_x', 'of_input_y'], {}), '(of_input_x, of_input_y)\n', (2645, 2669), True, 'import oneflow.experimental as flow\n'), ((3191, 3225), 'oneflow.experimental.atan2', 'flow.atan2', (['of_input_x', 'of_input_y'], {}), '(of_input_x, of_input_y)\n', (3201, 3225), True, 'import oneflow.experimental as flow\n'), ((3693, 3706), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3704, 3706), False, 'from collections import OrderedDict\n'), ((3883, 3903), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (3893, 3903), False, 'from test_util import GenArgList\n'), ((4018, 4031), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4029, 4031), False, 'from collections import OrderedDict\n'), ((4098, 4118), 'test_util.GenArgList', 'GenArgList', (['arg_dict'], {}), '(arg_dict)\n', (4108, 4118), False, 'from test_util import GenArgList\n'), ((3500, 3543), 'oneflow.experimental.unittest.env.eager_execution_enabled', 'flow.unittest.env.eager_execution_enabled', ([], {}), '()\n', (3541, 3543), True, 'import oneflow.experimental as flow\n'), ((979, 998), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (990, 998), True, 'import oneflow.experimental as flow\n'), ((1069, 1088), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (1080, 1088), True, 'import oneflow.experimental as flow\n'), ((1703, 1722), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (1714, 1722), True, 'import oneflow.experimental as flow\n'), ((1881, 1900), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (1892, 1900), True, 'import oneflow.experimental as flow\n'), ((2434, 2453), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (2445, 2453), True, 'import oneflow.experimental as flow\n'), ((2586, 2605), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (2597, 2605), True, 'import oneflow.experimental as flow\n'), ((2964, 2983), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (2975, 2983), True, 'import oneflow.experimental as flow\n'), ((3108, 3127), 'oneflow.experimental.device', 'flow.device', (['device'], {}), '(device)\n', (3119, 3127), True, 'import oneflow.experimental as flow\n')] |
import oneflow as flow
import oneflow.nn as nn
import math
# Reference: https://github.com/piEsposito/pytorch-lstm-by-hand
class LSTM(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, batch_size=1, num_layers=1):
super(LSTM, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.batch_size = batch_size
self.num_layers = num_layers
# Define the LSTM layer
self.lstm = CustomLSTM(self.input_dim, self.hidden_dim)
# Define the output layer
self.linear = nn.Linear(self.hidden_dim, output_dim)
def forward(self, input):
# Forward pass through LSTM layer
# shape of lstm_out: [input_size, batch_size, hidden_dim]
# shape of self.hidden: (a, b), where a and b both
# have shape (num_layers, batch_size, hidden_dim).
lstm_out, _ = self.lstm(input.reshape((input.shape[0], self.batch_size, -1)))
# Only take the output from the final timestep
# Can pass on the entirety of lstm_out to the next layer if it is a seq2seq prediction
# NOTE(<NAME>) Negative indexing and view not supported
output = lstm_out[lstm_out.shape[0] - 1].reshape((self.batch_size, -1))
y_pred = self.linear(output)
return y_pred
class CustomLSTM(nn.Module):
def __init__(self, input_sz, hidden_sz):
super().__init__()
self.input_sz = input_sz
self.hidden_size = hidden_sz
self.W = nn.Parameter(flow.Tensor(input_sz, hidden_sz * 4))
self.U = nn.Parameter(flow.Tensor(hidden_sz, hidden_sz * 4))
self.bias = nn.Parameter(flow.Tensor(hidden_sz * 4))
self.init_weights()
def init_weights(self):
stdv = 1.0 / math.sqrt(self.hidden_size)
for weight in self.parameters():
weight.data.uniform_(-stdv, stdv)
def forward(self, x, init_states=None):
"""Assumes x is of shape (batch, sequence, feature)"""
seq_sz, bs, _ = x.size()
hidden_seq = []
if init_states is None:
h_t, c_t = (
flow.zeros((bs, self.hidden_size)).to("cuda"),
flow.zeros((bs, self.hidden_size)).to("cuda"),
)
else:
h_t, c_t = init_states
HS = self.hidden_size
for t in range(seq_sz):
x_t = x[t, :, :].reshape((x.shape[1], x.shape[2]))
# batch the computations into a single matrix multiplication
# NOTE(<NAME>): flow does not support view now, use reshape instead
gates = flow.matmul(x_t, self.W) + flow.matmul(h_t, self.U) + self.bias
i_t, f_t, g_t, o_t = (
flow.sigmoid(gates[:, :HS]),
flow.sigmoid(gates[:, HS : HS * 2]),
flow.tanh(gates[:, HS * 2 : HS * 3]),
flow.sigmoid(gates[:, HS * 3 :]),
)
c_t = f_t * c_t + i_t * g_t
h_t = o_t * flow.tanh(c_t)
hidden_seq.append(h_t.unsqueeze(0))
hidden_seq = flow.cat(hidden_seq, dim=0)
return hidden_seq, (h_t, c_t)
| [
"oneflow.matmul",
"oneflow.nn.Linear",
"oneflow.tanh",
"oneflow.sigmoid",
"oneflow.zeros",
"oneflow.Tensor",
"oneflow.cat"
] | [((571, 609), 'oneflow.nn.Linear', 'nn.Linear', (['self.hidden_dim', 'output_dim'], {}), '(self.hidden_dim, output_dim)\n', (580, 609), True, 'import oneflow.nn as nn\n'), ((3044, 3071), 'oneflow.cat', 'flow.cat', (['hidden_seq'], {'dim': '(0)'}), '(hidden_seq, dim=0)\n', (3052, 3071), True, 'import oneflow as flow\n'), ((1510, 1546), 'oneflow.Tensor', 'flow.Tensor', (['input_sz', '(hidden_sz * 4)'], {}), '(input_sz, hidden_sz * 4)\n', (1521, 1546), True, 'import oneflow as flow\n'), ((1578, 1615), 'oneflow.Tensor', 'flow.Tensor', (['hidden_sz', '(hidden_sz * 4)'], {}), '(hidden_sz, hidden_sz * 4)\n', (1589, 1615), True, 'import oneflow as flow\n'), ((1650, 1676), 'oneflow.Tensor', 'flow.Tensor', (['(hidden_sz * 4)'], {}), '(hidden_sz * 4)\n', (1661, 1676), True, 'import oneflow as flow\n'), ((1756, 1783), 'math.sqrt', 'math.sqrt', (['self.hidden_size'], {}), '(self.hidden_size)\n', (1765, 1783), False, 'import math\n'), ((2696, 2723), 'oneflow.sigmoid', 'flow.sigmoid', (['gates[:, :HS]'], {}), '(gates[:, :HS])\n', (2708, 2723), True, 'import oneflow as flow\n'), ((2741, 2774), 'oneflow.sigmoid', 'flow.sigmoid', (['gates[:, HS:HS * 2]'], {}), '(gates[:, HS:HS * 2])\n', (2753, 2774), True, 'import oneflow as flow\n'), ((2794, 2828), 'oneflow.tanh', 'flow.tanh', (['gates[:, HS * 2:HS * 3]'], {}), '(gates[:, HS * 2:HS * 3])\n', (2803, 2828), True, 'import oneflow as flow\n'), ((2848, 2879), 'oneflow.sigmoid', 'flow.sigmoid', (['gates[:, HS * 3:]'], {}), '(gates[:, HS * 3:])\n', (2860, 2879), True, 'import oneflow as flow\n'), ((2960, 2974), 'oneflow.tanh', 'flow.tanh', (['c_t'], {}), '(c_t)\n', (2969, 2974), True, 'import oneflow as flow\n'), ((2581, 2605), 'oneflow.matmul', 'flow.matmul', (['x_t', 'self.W'], {}), '(x_t, self.W)\n', (2592, 2605), True, 'import oneflow as flow\n'), ((2608, 2632), 'oneflow.matmul', 'flow.matmul', (['h_t', 'self.U'], {}), '(h_t, self.U)\n', (2619, 2632), True, 'import oneflow as flow\n'), ((2109, 2143), 'oneflow.zeros', 'flow.zeros', (['(bs, self.hidden_size)'], {}), '((bs, self.hidden_size))\n', (2119, 2143), True, 'import oneflow as flow\n'), ((2172, 2206), 'oneflow.zeros', 'flow.zeros', (['(bs, self.hidden_size)'], {}), '((bs, self.hidden_size))\n', (2182, 2206), True, 'import oneflow as flow\n')] |
import oneflow as flow
def make_optimizer(args, model):
param_group = {"params": [p for p in model.parameters() if p is not None]}
if args.grad_clipping > 0.0:
assert args.grad_clipping == 1.0, "ONLY support grad_clipping == 1.0"
param_group["clip_grad_max_norm"] = (1.0,)
param_group["clip_grad_norm_type"] = (2.0,)
optimizer = flow.optim.SGD(
[param_group],
lr=args.learning_rate,
momentum=args.momentum,
weight_decay=args.weight_decay,
)
return optimizer
def make_grad_scaler():
return flow.amp.GradScaler(
init_scale=2 ** 30, growth_factor=2.0, backoff_factor=0.5, growth_interval=2000,
)
def make_static_grad_scaler():
return flow.amp.StaticGradScaler(flow.env.get_world_size())
def make_lr_scheduler(args, optimizer):
assert args.lr_decay_type in ("none", "cosine")
if args.lr_decay_type == "none":
return None
warmup_batches = args.batches_per_epoch * args.warmup_epochs
total_batches = args.batches_per_epoch * args.num_epochs
# TODO(zwx): These's no need that decay_batches minus warmup_batches
# decay_batches = total_batches - warmup_batches
decay_batches = total_batches
lr_scheduler = flow.optim.lr_scheduler.CosineDecayLR(
optimizer, decay_steps=decay_batches
)
if args.warmup_epochs > 0:
lr_scheduler = flow.optim.lr_scheduler.WarmUpLR(
lr_scheduler,
warmup_factor=0,
warmup_iters=warmup_batches,
warmup_method="linear",
)
return lr_scheduler
def make_cross_entropy(args):
if args.label_smoothing > 0:
cross_entropy = LabelSmoothLoss(
num_classes=args.num_classes, smooth_rate=args.label_smoothing
)
else:
cross_entropy = flow.nn.CrossEntropyLoss(reduction="mean")
return cross_entropy
class LabelSmoothLoss(flow.nn.Module):
def __init__(self, num_classes=-1, smooth_rate=0.0):
super().__init__()
self.num_classes = num_classes
self.smooth_rate = smooth_rate
# TODO(zwx): check this hyper param correction
self.on_value = 1 - self.smooth_rate + self.smooth_rate / self.num_classes
self.off_value = self.smooth_rate / self.num_classes
def forward(self, input, label):
onehot_label = flow._C.one_hot(
label, self.num_classes, self.on_value, self.off_value
)
# NOTE(zwx): manual way has bug
# log_prob = input.softmax(dim=-1).log()
# onehot_label = flow.F.cast(onehot_label, log_prob.dtype)
# loss = flow.mul(log_prob * -1, onehot_label).sum(dim=-1).mean()
loss = flow._C.softmax_cross_entropy(input, onehot_label.to(dtype=input.dtype))
return loss.mean()
| [
"oneflow.amp.GradScaler",
"oneflow.optim.lr_scheduler.WarmUpLR",
"oneflow.nn.CrossEntropyLoss",
"oneflow.optim.SGD",
"oneflow.optim.lr_scheduler.CosineDecayLR",
"oneflow.env.get_world_size",
"oneflow._C.one_hot"
] | [((369, 481), 'oneflow.optim.SGD', 'flow.optim.SGD', (['[param_group]'], {'lr': 'args.learning_rate', 'momentum': 'args.momentum', 'weight_decay': 'args.weight_decay'}), '([param_group], lr=args.learning_rate, momentum=args.momentum,\n weight_decay=args.weight_decay)\n', (383, 481), True, 'import oneflow as flow\n'), ((575, 680), 'oneflow.amp.GradScaler', 'flow.amp.GradScaler', ([], {'init_scale': '(2 ** 30)', 'growth_factor': '(2.0)', 'backoff_factor': '(0.5)', 'growth_interval': '(2000)'}), '(init_scale=2 ** 30, growth_factor=2.0, backoff_factor=\n 0.5, growth_interval=2000)\n', (594, 680), True, 'import oneflow as flow\n'), ((1247, 1322), 'oneflow.optim.lr_scheduler.CosineDecayLR', 'flow.optim.lr_scheduler.CosineDecayLR', (['optimizer'], {'decay_steps': 'decay_batches'}), '(optimizer, decay_steps=decay_batches)\n', (1284, 1322), True, 'import oneflow as flow\n'), ((761, 786), 'oneflow.env.get_world_size', 'flow.env.get_world_size', ([], {}), '()\n', (784, 786), True, 'import oneflow as flow\n'), ((1392, 1512), 'oneflow.optim.lr_scheduler.WarmUpLR', 'flow.optim.lr_scheduler.WarmUpLR', (['lr_scheduler'], {'warmup_factor': '(0)', 'warmup_iters': 'warmup_batches', 'warmup_method': '"""linear"""'}), "(lr_scheduler, warmup_factor=0,\n warmup_iters=warmup_batches, warmup_method='linear')\n", (1424, 1512), True, 'import oneflow as flow\n'), ((1818, 1860), 'oneflow.nn.CrossEntropyLoss', 'flow.nn.CrossEntropyLoss', ([], {'reduction': '"""mean"""'}), "(reduction='mean')\n", (1842, 1860), True, 'import oneflow as flow\n'), ((2350, 2421), 'oneflow._C.one_hot', 'flow._C.one_hot', (['label', 'self.num_classes', 'self.on_value', 'self.off_value'], {}), '(label, self.num_classes, self.on_value, self.off_value)\n', (2365, 2421), 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 unittest
import oneflow as flow
from oneflow import nn
import os
import numpy as np
import oneflow.unittest
class TestModuleDiffHierarchy(nn.Module):
def forward(self, x):
sbp_1ds = [
flow.sbp.broadcast,
flow.sbp.partial_sum,
flow.sbp.split(0),
flow.sbp.split(1),
]
for sbp1 in sbp_1ds:
for sbp2 in sbp_1ds:
for sbp3 in sbp_1ds:
for sbp4 in sbp_1ds:
# (3, 2) -> (2, 3)
x = x.to_global(
placement=flow.placement(
type="cuda", ranks=np.array(range(6)).reshape(2, 3)
),
sbp=[sbp1, sbp2],
)
# (2, 3) -> (3, 2)
x = x.to_global(
placement=flow.placement(
type="cuda", ranks=np.array(range(6)).reshape(3, 2)
),
sbp=[sbp3, sbp4],
)
return x
class TestModuleDiffPlacement(nn.Module):
def forward(self, x):
sbp_1ds = [
flow.sbp.broadcast,
flow.sbp.partial_sum,
flow.sbp.split(0),
flow.sbp.split(1),
]
for sbp1 in sbp_1ds:
for sbp2 in sbp_1ds:
for sbp3 in sbp_1ds:
for sbp4 in sbp_1ds:
# (3, 2) -> (2, 2)
x = x.to_global(
placement=flow.placement(
type="cuda", ranks=np.array(range(4)).reshape(2, 2)
),
sbp=[sbp1, sbp2],
)
# (2, 2) -> (3, 2)
x = x.to_global(
placement=flow.placement(
type="cuda", ranks=np.array(range(6)).reshape(3, 2)
),
sbp=[sbp3, sbp4],
)
return x
class TestGraph(nn.Graph):
def __init__(self, model):
super().__init__()
self.model = model
def build(self, x):
x = self.model(x)
return x
@flow.unittest.skip_unless_2n4d()
@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
class TestLazyAllSbpCombinationTesting(flow.unittest.TestCase):
def test_lazy_boxing_2d_all_combination(test_case):
x = flow.ones(
12,
12,
sbp=[flow.sbp.broadcast, flow.sbp.broadcast],
placement=flow.placement(
type="cuda", ranks=np.array(range(6)).reshape(3, 2)
),
)
model_diff_hierarchy = TestModuleDiffHierarchy()
graph_diff_hierarchy = TestGraph(model_diff_hierarchy)
y = graph_diff_hierarchy(x)
model_diff_placement = TestModuleDiffPlacement()
graph_diff_placement = TestGraph(model_diff_placement)
z = graph_diff_placement(x)
if __name__ == "__main__":
unittest.main()
| [
"oneflow.sbp.split",
"oneflow.unittest.skip_unless_2n4d"
] | [((2969, 3001), 'oneflow.unittest.skip_unless_2n4d', 'flow.unittest.skip_unless_2n4d', ([], {}), '()\n', (2999, 3001), True, 'import oneflow as flow\n'), ((3019, 3053), 'os.getenv', 'os.getenv', (['"""ONEFLOW_TEST_CPU_ONLY"""'], {}), "('ONEFLOW_TEST_CPU_ONLY')\n", (3028, 3053), False, 'import os\n'), ((3790, 3805), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3803, 3805), False, 'import unittest\n'), ((876, 893), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (890, 893), True, 'import oneflow as flow\n'), ((907, 924), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (921, 924), True, 'import oneflow as flow\n'), ((1914, 1931), 'oneflow.sbp.split', 'flow.sbp.split', (['(0)'], {}), '(0)\n', (1928, 1931), True, 'import oneflow as flow\n'), ((1945, 1962), 'oneflow.sbp.split', 'flow.sbp.split', (['(1)'], {}), '(1)\n', (1959, 1962), True, 'import oneflow as flow\n')] |
import random
import numpy as np
from functools import partial
import oneflow
import oneflow as flow
import oneflow.nn as nn
import oneflow.F as F
from utils.drop import DropPath
from layers.mlp import Mlp
from layers.layer_norm import LayerNorm
from layers.helpers import to_2tuple
from layers.patch_embed import PatchEmbed
# TODO: 在测试单个的mlp-block时,出现了nan
# test-code
# test_data = flow.ones((10, 16, 768), dtype=flow.float32)
# block = MixerBlock(768, 16, drop_path=0.5)
# print(block(test_data)) # 有一部分数据输出nan
class MixerBlock(nn.Module):
def __init__(self, dim, seq_len, mlp_ratio=(0.5, 4.0), mlp_layer=Mlp,
norm_layer=partial(LayerNorm, eps=1e-6), act_layer=nn.GELU, drop=0., drop_path=0.):
super().__init__()
tokens_dim, channels_dim = [int(x * dim) for x in to_2tuple(mlp_ratio)]
self.norm1 = norm_layer(dim)
self.mlp_tokens = mlp_layer(seq_len, tokens_dim, act_layer=act_layer, drop=drop)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
self.mlp_channels = mlp_layer(dim, channels_dim, act_layer=act_layer, drop=drop)
def forward(self, x):
x = x + self.drop_path(self.mlp_tokens(self.norm1(x).transpose(1, 2)).transpose(1, 2))
x = x + self.drop_path(self.mlp_channels(self.norm2(x)))
return x
class MlpMixer(nn.Module):
def __init__(
self,
num_classes=1000,
img_size=224,
in_chans=3,
patch_size=16,
num_blocks=8, # depth
embed_dim=512, # hidden dim
mlp_ratio=(0.5, 4.0),
block_layer=MixerBlock,
mlp_layer=Mlp,
norm_layer=partial(LayerNorm, eps=1e-6),
act_layer=nn.GELU,
drop_rate=0.,
drop_path_rate=0.,
nlhb=False, # not used
stem_norm=False,
):
super().__init__()
self.num_classes = num_classes
self.num_features = self.embed_dim = embed_dim
self.stem = PatchEmbed(
img_size=img_size, patch_size=patch_size, in_chans=in_chans,
embed_dim=embed_dim, norm_layer=norm_layer if stem_norm else None
)
self.blocks = nn.Sequential(*[
block_layer(
embed_dim, self.stem.num_patches, mlp_ratio, mlp_layer=mlp_layer, norm_layer=norm_layer,
act_layer=act_layer, drop=drop_rate, drop_path=drop_path_rate)
for _ in range(num_blocks)])
self.norm = norm_layer(embed_dim)
self.head = nn.Linear(embed_dim, self.num_classes) if num_classes > 0 else nn.Identity()
def forward_features(self, x):
x = self.stem(x)
x = self.blocks(x)
x = self.norm(x)
x = x.mean(dim=1)
return x
def forward(self, x):
x = self.forward_features(x)
x = self.head(x)
return x
# def _resnet(
# arch: str,
# block: Type[Union[BasicBlock, Bottleneck]],
# layers: List[int],
# pretrained: bool,
# progress: bool,
# **kwargs: Any
# ) -> ResNet:
# model = ResNet(block, layers, **kwargs)
# if pretrained:
# state_dict = load_state_dict_from_url(model_urls[arch],
# progress=progress)
# model.load_state_dict(state_dict)
# return model
# def _mixer(pretrained=False, **kwargs):
# model = MlpMixer(**kwargs)
# # if pretrained:
# # state_dict = load_state_dict_from_url(model_urls[arch],
# # progress=progress)
# def mixer_s32_224(pretrained=False, **kwargs):
import torch
model_path = "/data/rentianhe/code/vision-mlp-oneflow/weights/torch/mixer_b16_224.pth"
if __name__ == "__main__":
test_data = flow.ones((1, 3, 224, 224), dtype=flow.float32)
model = MlpMixer(patch_size=16, num_blocks=12, embed_dim=768)
# preds = model(test_data)
# print(preds)
# parameters = torch.load(model_path)
# new_parameters = dict()
# for key,value in parameters.items():
# if "num_batches_tracked" not in key:
# val = value.detach().cpu().numpy()
# new_parameters[key] = val
# model.load_state_dict(new_parameters)
# flow.save(model.state_dict(), "/data/rentianhe/code/vision-mlp-oneflow/weights/flow/mixer_b16_224.of")
state_dict = flow.load("/data/rentianhe/code/vision-mlp-oneflow/weights/flow/mixer_b16_224.of")
model.load_state_dict(state_dict) | [
"oneflow.nn.Linear",
"oneflow.nn.Identity",
"oneflow.load",
"oneflow.ones"
] | [((3832, 3879), 'oneflow.ones', 'flow.ones', (['(1, 3, 224, 224)'], {'dtype': 'flow.float32'}), '((1, 3, 224, 224), dtype=flow.float32)\n', (3841, 3879), True, 'import oneflow as flow\n'), ((4414, 4501), 'oneflow.load', 'flow.load', (['"""/data/rentianhe/code/vision-mlp-oneflow/weights/flow/mixer_b16_224.of"""'], {}), "(\n '/data/rentianhe/code/vision-mlp-oneflow/weights/flow/mixer_b16_224.of')\n", (4423, 4501), True, 'import oneflow as flow\n'), ((648, 677), 'functools.partial', 'partial', (['LayerNorm'], {'eps': '(1e-06)'}), '(LayerNorm, eps=1e-06)\n', (655, 677), False, 'from functools import partial\n'), ((1734, 1763), 'functools.partial', 'partial', (['LayerNorm'], {'eps': '(1e-06)'}), '(LayerNorm, eps=1e-06)\n', (1741, 1763), False, 'from functools import partial\n'), ((2078, 2220), 'layers.patch_embed.PatchEmbed', 'PatchEmbed', ([], {'img_size': 'img_size', 'patch_size': 'patch_size', 'in_chans': 'in_chans', 'embed_dim': 'embed_dim', 'norm_layer': '(norm_layer if stem_norm else None)'}), '(img_size=img_size, patch_size=patch_size, in_chans=in_chans,\n embed_dim=embed_dim, norm_layer=norm_layer if stem_norm else None)\n', (2088, 2220), False, 'from layers.patch_embed import PatchEmbed\n'), ((979, 998), 'utils.drop.DropPath', 'DropPath', (['drop_path'], {}), '(drop_path)\n', (987, 998), False, 'from utils.drop import DropPath\n'), ((1022, 1035), 'oneflow.nn.Identity', 'nn.Identity', ([], {}), '()\n', (1033, 1035), True, 'import oneflow.nn as nn\n'), ((2602, 2640), 'oneflow.nn.Linear', 'nn.Linear', (['embed_dim', 'self.num_classes'], {}), '(embed_dim, self.num_classes)\n', (2611, 2640), True, 'import oneflow.nn as nn\n'), ((2665, 2678), 'oneflow.nn.Identity', 'nn.Identity', ([], {}), '()\n', (2676, 2678), True, 'import oneflow.nn as nn\n'), ((806, 826), 'layers.helpers.to_2tuple', 'to_2tuple', (['mlp_ratio'], {}), '(mlp_ratio)\n', (815, 826), False, 'from layers.helpers import to_2tuple\n')] |
import oneflow as flow
from quantization_ops.q_module import QModule, QParam
__all__ = ["QConv2d"]
class QConv2d(QModule):
def __init__(self, conv_module, qi=True, qo=True, quantization_bit=8, quantization_scheme='symmetric', quantization_formula='google', per_layer_quantization=True):
super(QConv2d, self).__init__(qi=qi, qo=qo, quantization_bit=quantization_bit, quantization_scheme=quantization_scheme,
quantization_formula=quantization_formula, per_layer_quantization=per_layer_quantization)
self.quantization_bit = quantization_bit
self.quantization_scheme = quantization_scheme
self.quantization_formula = quantization_formula
self.per_layer_quantization = per_layer_quantization
self.conv_module = conv_module
self.fake_quantization = flow.nn.FakeQuantization(
quantization_formula=quantization_formula, quantization_bit=quantization_bit, quantization_scheme=quantization_scheme)
self.qw = QParam(quantization_bit=quantization_bit, quantization_scheme=quantization_scheme,
quantization_formula=quantization_formula, per_layer_quantization=per_layer_quantization)
self.quantization = flow.nn.Quantization(
quantization_bit=32, quantization_scheme="affine", quantization_formula="google")
def forward(self, x):
if hasattr(self, 'qi'):
self.qi.update(x)
x = self.qi.fake_quantize_tensor(x)
self.qw.update(self.conv_module.weight)
x = flow.F.conv2d(x, self.qw.fake_quantize_tensor(self.conv_module.weight), self.conv_module.bias,
stride=self.conv_module.stride,
padding=self.conv_module.padding, dilation=self.conv_module.dilation,
groups=self.conv_module.groups)
if hasattr(self, 'qo'):
self.qo.update(x)
x = self.qo.fake_quantize_tensor(x)
return x
def freeze(self, qi=None, qo=None):
if hasattr(self, 'qi') and qi is not None:
raise ValueError('qi has been provided in init function.')
if not hasattr(self, 'qi') and qi is None:
raise ValueError('qi is not existed, should be provided.')
if hasattr(self, 'qo') and qo is not None:
raise ValueError('qo has been provided in init function.')
if not hasattr(self, 'qo') and qo is None:
raise ValueError('qo is not existed, should be provided.')
if qi is not None:
self.qi = qi
if qo is not None:
self.qo = qo
self.M = self.qw.scale.numpy() * self.qi.scale.numpy() / self.qo.scale.numpy()
self.conv_module.weight = flow.nn.Parameter(
self.qw.quantize_tensor(self.conv_module.weight) - self.qw.zero_point)
self.conv_module.bias = flow.nn.Parameter(self.quantization(
self.conv_module.bias, self.qi.scale * self.qw.scale, flow.Tensor([0])))
| [
"oneflow.Tensor",
"oneflow.nn.FakeQuantization",
"oneflow.nn.Quantization"
] | [((845, 992), 'oneflow.nn.FakeQuantization', 'flow.nn.FakeQuantization', ([], {'quantization_formula': 'quantization_formula', 'quantization_bit': 'quantization_bit', 'quantization_scheme': 'quantization_scheme'}), '(quantization_formula=quantization_formula,\n quantization_bit=quantization_bit, quantization_scheme=quantization_scheme)\n', (869, 992), True, 'import oneflow as flow\n'), ((1020, 1201), 'quantization_ops.q_module.QParam', 'QParam', ([], {'quantization_bit': 'quantization_bit', 'quantization_scheme': 'quantization_scheme', 'quantization_formula': 'quantization_formula', 'per_layer_quantization': 'per_layer_quantization'}), '(quantization_bit=quantization_bit, quantization_scheme=\n quantization_scheme, quantization_formula=quantization_formula,\n per_layer_quantization=per_layer_quantization)\n', (1026, 1201), False, 'from quantization_ops.q_module import QModule, QParam\n'), ((1246, 1352), 'oneflow.nn.Quantization', 'flow.nn.Quantization', ([], {'quantization_bit': '(32)', 'quantization_scheme': '"""affine"""', 'quantization_formula': '"""google"""'}), "(quantization_bit=32, quantization_scheme='affine',\n quantization_formula='google')\n", (1266, 1352), True, 'import oneflow as flow\n'), ((2992, 3008), 'oneflow.Tensor', 'flow.Tensor', (['[0]'], {}), '([0])\n', (3003, 3008), 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 as flow
from oneflow.framework.tensor import Tensor, register_tensor_op
def _input_args_is_int(args):
return all((isinstance(x, int) for x in args))
def index_select_op(input, dim, index):
assert len(index.shape) == 1, "Dimensions of index should be 1-D"
assert (
dim < len(input.shape) and dim >= 0
), "Value of dim is out of range(dim should be in the range of [0, input dimensions) )"
assert _input_args_is_int(
index.tolist()
), "input index parameter is not legal!(index should be an 1-D int tensor)"
index_rshp = list(input.shape)
for index_i in index:
assert (
index_i < index_rshp[dim]
), "index is out of range(index shuold be lower than the dim-th dimension of input)"
index_rshp[dim] = 1
index_gather = index[0].expand(*index_rshp)
if index.size()[0] > 1:
for index_i in index[1:]:
x = index_i.expand(*index_rshp)
index_gather = flow.cat((index_gather, x), dim)
return flow.gather(input, dim, index_gather)
if __name__ == "__main__":
import doctest
doctest.testmod(raise_on_error=True)
| [
"oneflow.cat",
"oneflow.gather"
] | [((1616, 1653), 'oneflow.gather', 'flow.gather', (['input', 'dim', 'index_gather'], {}), '(input, dim, index_gather)\n', (1627, 1653), True, 'import oneflow as flow\n'), ((1707, 1743), 'doctest.testmod', 'doctest.testmod', ([], {'raise_on_error': '(True)'}), '(raise_on_error=True)\n', (1722, 1743), False, 'import doctest\n'), ((1571, 1603), 'oneflow.cat', 'flow.cat', (['(index_gather, x)', 'dim'], {}), '((index_gather, x), dim)\n', (1579, 1603), True, 'import oneflow as flow\n')] |
Subsets and Splits