python_code
stringlengths 0
679k
| repo_name
stringlengths 9
41
| file_path
stringlengths 6
149
|
|---|---|---|
import torch
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
import torch.distributed as dist
from torch.nn.modules import Module
def flat_dist_call(tensors, call, extra_args=None):
flat_dist_call.warn_on_half = True
buckets = {}
for tensor in tensors:
tp = tensor.type()
if tp not in buckets:
buckets[tp] = []
buckets[tp].append(tensor)
if flat_dist_call.warn_on_half:
if torch.cuda.HalfTensor in buckets:
print("WARNING: gloo dist backend for half parameters may be extremely slow." +
" It is recommended to use the NCCL backend in this case.")
flat_dist_call.warn_on_half = False
for tp in buckets:
bucket = buckets[tp]
coalesced = _flatten_dense_tensors(bucket)
if extra_args is not None:
call(coalesced, *extra_args)
else:
call(coalesced)
coalesced /= dist.get_world_size()
for buf, synced in zip(bucket, _unflatten_dense_tensors(coalesced, bucket)):
buf.copy_(synced)
class DistributedDataParallel(Module):
def __init__(self, module):
super(DistributedDataParallel, self).__init__()
self.warn_on_half = True if dist._backend == dist.dist_backend.GLOO else False
self.module = module
param_list = [param for param in self.module.state_dict().values() if torch.is_tensor(param)]
if dist._backend == dist.dist_backend.NCCL:
for param in param_list:
assert param.is_cuda, "NCCL backend only supports model parameters to be on GPU."
#broadcast parameters
flat_dist_call(param_list, dist.broadcast, (0,) )
#all reduce gradient hook
def allreduce_params():
if(self.needs_reduction):
self.needs_reduction = False
else:
return
grads = [param.grad.data for param in self.module.parameters() if param.grad is not None]
flat_dist_call(grads, dist.all_reduce)
for param in list(self.module.parameters()):
def allreduce_hook(*unused):
param._execution_engine.queue_callback(allreduce_params)
if param.requires_grad:
param.register_hook(allreduce_hook)
def forward(self, *inputs, **kwargs):
self.needs_reduction = True
return self.module(*inputs, **kwargs)
|
DALI-main
|
docs/examples/use_cases/video_superres/common/distributed.py
|
import torch
class LossScaler:
def __init__(self, scale=1):
self.cur_scale = scale
# `params` is a list / generator of torch.Variable
def has_overflow(self, params):
return False
# `x` is a torch.Tensor
def _has_inf_or_nan(x):
return False
# `overflow` is boolean indicating whether we overflowed in gradient
def update_scale(self, overflow):
pass
@property
def loss_scale(self):
return self.cur_scale
def scale_gradient(self, module, grad_in, grad_out):
return tuple(self.loss_scale * g for g in grad_in)
def backward(self, loss):
scaled_loss = loss*self.loss_scale
scaled_loss.backward()
class DynamicLossScaler:
def __init__(self,
init_scale=2**32,
scale_factor=2.,
scale_window=1000):
self.cur_scale = init_scale
self.cur_iter = 0
self.last_overflow_iter = -1
self.scale_factor = scale_factor
self.scale_window = scale_window
# `params` is a list / generator of torch.Variable
def has_overflow(self, params):
# return False
for p in params:
if p.grad is not None and DynamicLossScaler._has_inf_or_nan(p.grad.data):
return True
return False
# `x` is a torch.Tensor
def _has_inf_or_nan(x):
inf_count = torch.sum(x.abs() == float('inf'))
if inf_count > 0:
return True
nan_count = torch.sum(x != x)
return nan_count > 0
# `overflow` is boolean indicating whether we overflowed in gradient
def update_scale(self, overflow):
if overflow:
#self.cur_scale /= self.scale_factor
self.cur_scale = max(self.cur_scale/self.scale_factor, 1)
self.last_overflow_iter = self.cur_iter
else:
if (self.cur_iter - self.last_overflow_iter) % self.scale_window == 0:
self.cur_scale *= self.scale_factor
# self.cur_scale = 1
self.cur_iter += 1
@property
def loss_scale(self):
return self.cur_scale
def scale_gradient(self, module, grad_in, grad_out):
return tuple(self.loss_scale * g for g in grad_in)
def backward(self, loss):
scaled_loss = loss*self.loss_scale
scaled_loss.backward()
|
DALI-main
|
docs/examples/use_cases/video_superres/common/loss_scaler.py
|
import sys
import copy
from glob import glob
import math
import os
import torch
from torch.utils.data import DataLoader
from dataloading.datasets import imageDataset
from nvidia.dali.pipeline import pipeline_def
from nvidia.dali.plugin import pytorch
import nvidia.dali.fn as fn
import nvidia.dali.types as types
@pipeline_def
def create_video_reader_pipeline(sequence_length, files, crop_size):
images = fn.readers.video(device="gpu", filenames=files, sequence_length=sequence_length,
normalized=False, random_shuffle=True, image_type=types.RGB,
dtype=types.UINT8, initial_fill=16, pad_last_batch=True, name="Reader")
images = fn.crop(images, crop=crop_size, dtype=types.FLOAT,
crop_pos_x=fn.random.uniform(range=(0.0, 1.0)),
crop_pos_y=fn.random.uniform(range=(0.0, 1.0)))
images = fn.transpose(images, perm=[3, 0, 1, 2])
return images
class DALILoader():
def __init__(self, batch_size, file_root, sequence_length, crop_size):
container_files = os.listdir(file_root)
container_files = [file_root + '/' + f for f in container_files]
self.pipeline = create_video_reader_pipeline(batch_size=batch_size,
sequence_length=sequence_length,
num_threads=2,
device_id=0,
files=container_files,
crop_size=crop_size)
self.pipeline.build()
self.epoch_size = self.pipeline.epoch_size("Reader")
self.dali_iterator = pytorch.DALIGenericIterator(self.pipeline,
["data"],
reader_name="Reader",
last_batch_policy=pytorch.LastBatchPolicy.PARTIAL,
auto_reset=True)
def __len__(self):
return int(self.epoch_size)
def __iter__(self):
return self.dali_iterator.__iter__()
def get_loader(args, ds_type):
if ds_type not in ('train', 'val'):
raise ValueError("ds_type has to be either 'train' or 'val'")
if args.loader == 'pytorch':
if ds_type == 'train':
dataset = imageDataset(
args.frames,
args.is_cropped,
args.crop_size,
os.path.join(args.root, 'train'),
args.batchsize,
args.world_size)
if args.world_size > 1:
sampler = torch.utils.data.distributed.DistributedSampler(
dataset)
else:
sampler = torch.utils.data.RandomSampler(dataset)
loader = DataLoader(
dataset,
batch_size=args.batchsize,
shuffle=(sampler is None),
num_workers=0,
pin_memory=True,
sampler=sampler,
drop_last=True)
effective_bsz = args.batchsize * float(args.world_size)
batches = math.ceil(len(dataset) / float(effective_bsz))
if ds_type == 'val':
dataset = imageDataset(
args.frames,
args.is_cropped,
args.crop_size,
os.path.join(args.root, 'val'),
args.batchsize,
args.world_size)
if args.world_size > 1:
sampler = torch.utils.data.distributed.DistributedSampler(
dataset)
else:
sampler = torch.utils.data.RandomSampler(dataset)
loader = DataLoader(
dataset,
batch_size=1,
shuffle=False,
num_workers=1,
pin_memory=True,
sampler=sampler,
drop_last=True)
batches = math.ceil(len(dataset) / float(args.world_size))
elif args.loader == 'DALI':
loader = DALILoader(args.batchsize,
os.path.join(args.root, ds_type),
args.frames,
args.crop_size)
batches = len(loader)
sampler = None
else:
raise ValueError('%s is not a valid option for --loader' % args.loader)
return loader, batches, sampler
|
DALI-main
|
docs/examples/use_cases/video_superres/dataloading/dataloaders.py
|
import copy
import sys, time, argparse, os, subprocess, shutil
import math, numbers, random, bisect
from random import Random
from skimage import io, transform
from os import listdir
from os.path import join
from glob import glob
import numpy as np
import torch
import torch.utils.data as data
class imageDataset():
def __init__(self, frames, is_cropped, crop_size,
root, batch_size, world_size):
self.root = root
self.frames = frames
self.is_cropped = is_cropped
self.crop_size = crop_size
self.files = glob(os.path.join(self.root, '*/*.png'))
if len(self.files) < 1:
print(("[Error] No image files in %s" % (self.root)))
raise LookupError
self.files = sorted(self.files)
self.total_frames = 0
# Find start_indices for different folders
self.start_index = [0]
prev_folder = self.files[0].split('/')[-2]
for (i, f) in enumerate(self.files):
folder = f.split('/')[-2]
if i > 0 and folder != prev_folder:
self.start_index.append(i)
prev_folder = folder
self.total_frames -= (self.frames + 1)
else:
self.total_frames += 1
self.total_frames -= (self.frames + 1)
self.start_index.append(i)
if self.is_cropped:
self.image_shape = self.crop_size
else:
self.image_shape = list(io.imread(self.files[0]).shape[:2])
# Frames are enforced to be mod64 in each dimension
# as required by FlowNetSD convolutions
self.frame_size = self.image_shape
self.frame_size[0] = int(math.floor(self.image_shape[0]/64.)*64)
self.frame_size[1] = int(math.floor(self.image_shape[1]/64.)*64)
self.frame_buffer = np.zeros((3, self.frames,
self.frame_size[0], self.frame_size[1]),
dtype = np.float32)
def __len__(self):
return self.total_frames
def __getitem__(self, index):
index = index % self.total_frames
# we want bisect_right here so that the first frame in a file gets the
# file, not the previous file
next_file_index = bisect.bisect_right(self.start_index, index)
if self.start_index[next_file_index] < index + self.frames:
index = self.start_index[next_file_index] - self.frames - 1
for (i, file_idx) in enumerate(range(index, index + self.frames)):
image = io.imread(self.files[file_idx])
#TODO(jbarker): Tidy this up and remove redundant computation
if i == 0 and self.is_cropped:
crop_x = random.randint(0, self.image_shape[1] - self.frame_size[1])
crop_y = random.randint(0, self.image_shape[0] - self.frame_size[0])
elif self.is_cropped == False:
crop_x = math.floor((self.image_shape[1] - self.frame_size[1]) / 2)
crop_y = math.floor((self.image_shape[0] - self.frame_size[0]) / 2)
self.crop_size = self.frame_size
image = image[crop_y:crop_y + self.crop_size[0],
crop_x:crop_x + self.crop_size[1],
:]
self.frame_buffer[:, i, :, :] = np.rollaxis(image, 2, 0)
return torch.from_numpy(self.frame_buffer)
|
DALI-main
|
docs/examples/use_cases/video_superres/dataloading/datasets.py
|
DALI-main
|
docs/examples/use_cases/video_superres/dataloading/__init__.py
|
|
DALI-main
|
docs/examples/use_cases/video_superres/model/__init__.py
|
|
from math import floor
# Cyclic learning rate
def cycle(iteration, stepsize):
return floor(1 + iteration / (2 * stepsize))
def abs_pos(cycle_num, iteration, stepsize):
return abs(iteration / stepsize - 2 * cycle_num + 1)
def rel_pos(iteration, stepsize):
return max(0, (1-abs_pos(cycle(iteration, stepsize), iteration, stepsize)))
def cyclic_learning_rate(min_lr, max_lr, stepsize):
return lambda iteration: min_lr + (max_lr - min_lr) * rel_pos(iteration, stepsize)
|
DALI-main
|
docs/examples/use_cases/video_superres/model/clr.py
|
import time
import scipy.misc
import numpy as np
from math import floor, log
import torch
import torch.nn as nn
from torch.nn import init
from torch.autograd import Variable
from torch.nn.functional import upsample
import sys
sys.path.append('flownet2-pytorch/networks')
try:
from submodules import *
except ModuleNotFoundError:
raise ModuleNotFoundError("flownet2-pytorch not found, did you update the git submodule?")
def lp_error(img1, img2, lp=2):
return torch.mean((img1 - img2)**lp)
# https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
def psnr(img1, img2):
mse = lp_error(img1, img2, 2)
if mse == 0:
return 100
PIXEL_MAX = 255.0
# getting the noise in dB
return 20 * torch.log10(PIXEL_MAX / torch.sqrt(mse))
def rgb2ycbcr(input_tensor):
# Conversion from RGB to YCbCr according to
# https://en.wikipedia.org/wiki/YCbCr?section=6#JPEG_conversion
# Expecting batch of RGB images with values in [0, 255]
kr = 0.299
kg = 0.587
kb = 0.114
# Expecting batch of image sequence inputs with values in [0, 255]
r = input_tensor[:, 0, :, :, :]
g = input_tensor[:, 1, :, :, :]
b = input_tensor[:, 2, :, :, :]
y = torch.unsqueeze(kr * r + kg * g + kb * b, 1)
cb = torch.unsqueeze(128 - (0.1687346 * r) - (0.331264 * g) + (0.5 * b), 1)
cr = torch.unsqueeze(128 + (0.5 * r) - (0.418688 * g) - (0.081312 * b), 1)
return y, cb, cr
def ycbcr2rgb(input_tensor):
# Conversion from YCbCr to RGB according to
# https://en.wikipedia.org/wiki/YCbCr/16?section=6#JPEG_conversion
# Expecting batch of YCbCr images with values in [0, 255]
y = input_tensor[:, 0, :, :]
cb = input_tensor[:, 1, :, :]
cr = input_tensor[:, 2, :, :]
r = y + 1.402 * (cr - 128)
g = y - 0.344136 * (cb - 128) - 0.714136 * (cr - 128)
b = y + 1.772 * (cb - 128)
r = torch.unsqueeze(r, 1)
g = torch.unsqueeze(g, 1)
b = torch.unsqueeze(b, 1)
return torch.clamp(torch.cat((r, g, b), 1), 0, 255)
def get_grid(batchsize, rows, cols, fp16):
# Input is a tensor with shape [batchsize, channels, rows, cols]
# Output is tensor with shape [batchsize, 2, rows, cols]
# where each col in [:, 1, :, :] and each row in [:, 0, :, :]
# is an evenly spaced arithmetic progression from -1.0 to 1.0
hor = torch.linspace(-1.0, 1.0, cols)
hor = hor.view(1, 1, 1, cols)
hor = hor.expand(batchsize, 1, rows, cols)
ver = torch.linspace(-1.0, 1.0, rows)
ver = ver.view(1, 1, rows, 1)
ver = ver.expand(batchsize, 1, rows, cols)
t_grid = torch.cat([hor, ver], 1)
if fp16:
return Variable(t_grid.half().cuda())
else:
return Variable(t_grid.cuda())
def tensorboard_image(name, image, iteration, writer):
# tensorboardX expects CHW images
out_im = image.data.cpu().numpy().astype('uint8')
writer.add_image(name, out_im, iteration)
class VSRNet(nn.Module):
def __init__(self, frames=3, flownet_path='', fp16=False):
super(VSRNet, self).__init__()
self.frames = frames
self.fp16 = fp16
self.mi = int(floor(self.frames / 2))
self.pooling = nn.AvgPool2d(4, ceil_mode=False)
self.upsample = nn.Upsample(scale_factor=4, mode='bilinear')
if fp16:
#from FlowNetSD16 import FlowNetSD
from FlowNetSD import FlowNetSD
else:
from FlowNetSD import FlowNetSD
FlowNetSD_network = FlowNetSD(args=[], batchNorm=False)
try:
FlowNetSD_weights = torch.load(flownet_path)['state_dict']
except:
raise IOError('FlowNet weights could not be loaded from %s' % flownet_path)
FlowNetSD_network.load_state_dict(FlowNetSD_weights)
self.FlowNetSD_network = FlowNetSD_network
self.train_grid = None
self.val_grid = None
self.batchNorm = True
self.conv1 = conv(self.batchNorm, 1, 64, kernel_size=9)
self.conv2 = conv(self.batchNorm, 64 * self.frames, 32, kernel_size=5)
self.conv3 = nn.Conv2d(32, 1, kernel_size=5, stride=1, padding=2, bias=True)
self.conv3.weight = torch.nn.init.normal(self.conv3.weight, 0, 0.1)
def forward(self, inputs, iteration, writer, im_out=False):
batchsize, channels, frames, rows, cols = inputs.size()
# inputs are normalized
y, cb, cr = rgb2ycbcr(inputs)
y /= 255
target = y[:, :, self.mi, :, :]
if writer is not None and im_out:
out_im = inputs[0, :, self.mi, :, :] # / 255.0 will we need this?
tensorboard_image('target', out_im, iteration, writer)
out_im = self.pooling(out_im)
tensorboard_image('downsampled', out_im, iteration, writer)
out_im = self.upsample(out_im.unsqueeze(0)).squeeze(0)
tensorboard_image('upsampled', out_im, iteration, writer)
# Compute per RGB channel mean across pixels for each image in input batch
rgb_mean = inputs.view((batchsize, channels) + (-1, )).float().mean(dim=-1)
rgb_mean = rgb_mean.view((batchsize, channels) + (1, 1, 1, ))
if self.fp16:
rgb_mean = rgb_mean.half()
inputs = (inputs - rgb_mean) / 255
if self.training:
if self.train_grid is None:
self.train_grid = get_grid(batchsize, rows, cols, self.fp16)
grid = self.train_grid
else:
if self.val_grid is None:
self.val_grid = get_grid(batchsize, rows, cols, self.fp16)
grid = self.val_grid
grid.requires_grad = False
downsampled_input = self.pooling(cb[:, :, self.mi, :, :])
cb[:, :, self.mi, :, :] = self.upsample(downsampled_input)
downsampled_input = self.pooling(cr[:, :, self.mi, :, :])
cr[:, :, self.mi, :, :] = self.upsample(downsampled_input)
conv1_out = []
for fr in range(self.frames):
downsampled_input = self.pooling(y[:, :, fr, :, :])
y[:, :, fr, :, :] = self.upsample(downsampled_input)
if fr == self.mi:
conv1_out.append(self.conv1(y[:, :, self.mi, :, :].clone()))
else:
im1 = inputs[:, :, fr, :, :]
im2 = inputs[:, :, self.mi, :, :]
im_pair = torch.cat((im2, im1), 1)
to_warp = y[:, :, fr, :, :]
flow = self.upsample(self.FlowNetSD_network(im_pair)[0]) / 16
flow = torch.cat([flow[:, 0:1, :, :] / ((cols - 1.0) / 2.0),
flow[:, 1:2, :, :] / ((rows - 1.0) / 2.0)], 1)
warped = torch.nn.functional.grid_sample(
input=to_warp,
grid=(grid + flow).permute(0, 2, 3, 1),
mode='bilinear',
padding_mode='border')
conv1_out.append(self.conv1(warped))
conv1_out = torch.cat(conv1_out, 1)
conv2_out = self.conv2(conv1_out)
# Loss must be computed for pixel values in [0, 255] to prevent
# divergence in fp16
prediction = torch.nn.functional.sigmoid(self.conv3(conv2_out).float())
loss = torch.nn.functional.mse_loss(prediction.float(), target.float())
if not self.training:
# Following [1], remove 12 pixels around border to prevent
# convolution edge effects affecting PSNR
psnr_metric = psnr(prediction[:, :, 12:, :-12].float() * 255,
target[:, :, 12:, :-12].float() * 255)
prediction = ycbcr2rgb(torch.cat((prediction * 255, cb[:, :, self.mi, :, :],
cr[:, :, self.mi, :, :]), 1))
if writer is not None and im_out:
out_im = prediction[0, :, :, :]
tensorboard_image('prediction', out_im, iteration, writer)
if self.training:
return loss
else:
return loss, psnr_metric
# [1] Osama Makansi, Eddy Ilg, Thomas Brox, "End-to-End Learning of Video Super-Resolution with Motion Compensation", https://arxiv.org/abs/1707.00471
|
DALI-main
|
docs/examples/use_cases/video_superres/model/model.py
|
import argparse
import os
import shutil
import time
import math
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import numpy as np
from torch.nn.parallel import DistributedDataParallel as DDP
try:
from nvidia.dali.plugin.pytorch import DALIClassificationIterator, LastBatchPolicy
from nvidia.dali.pipeline import pipeline_def
import nvidia.dali.types as types
import nvidia.dali.fn as fn
except ImportError:
raise ImportError("Please install DALI from https://www.github.com/NVIDIA/DALI to run this example.")
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
def fast_collate(batch, memory_format):
"""Based on fast_collate from the APEX example
https://github.com/NVIDIA/apex/blob/5b5d41034b506591a316c308c3d2cd14d5187e23/examples/imagenet/main_amp.py#L265
"""
imgs = [img[0] for img in batch]
targets = torch.tensor([target[1] for target in batch], dtype=torch.int64)
w = imgs[0].size[0]
h = imgs[0].size[1]
tensor = torch.zeros( (len(imgs), 3, h, w), dtype=torch.uint8).contiguous(memory_format=memory_format)
for i, img in enumerate(imgs):
nump_array = np.asarray(img, dtype=np.uint8)
if(nump_array.ndim < 3):
nump_array = np.expand_dims(nump_array, axis=-1)
nump_array = np.rollaxis(nump_array, 2)
tensor[i] += torch.from_numpy(nump_array)
return tensor, targets
def parse():
model_names = sorted(name for name in models.__dict__
if name.islower() and not name.startswith("__")
and callable(models.__dict__[name]))
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('data', metavar='DIR', nargs='*',
help='path(s) to dataset (if one path is provided, it is assumed\n' +
'to have subdirectories named "train" and "val"; alternatively,\n' +
'train and val paths can be specified directly by providing both paths as arguments)')
parser.add_argument('--arch', '-a', metavar='ARCH', default='resnet18',
choices=model_names,
help='model architecture: ' +
' | '.join(model_names) +
' (default: resnet18)')
parser.add_argument('-j', '--workers', default=4, type=int, metavar='N',
help='number of data loading workers (default: 4)')
parser.add_argument('--epochs', default=90, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=256, type=int,
metavar='N', help='mini-batch size per process (default: 256)')
parser.add_argument('--lr', '--learning-rate', default=0.1, type=float,
metavar='LR', help='Initial learning rate. Will be scaled by <global batch size>/256: args.lr = args.lr*float(args.batch_size*args.world_size)/256. A warmup schedule will also be applied over the first 5 epochs.')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
help='momentum')
parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,
metavar='W', help='weight decay (default: 1e-4)')
parser.add_argument('--print-freq', '-p', default=10, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to latest checkpoint (default: none)')
parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',
help='evaluate model on validation set')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
help='use pre-trained model')
parser.add_argument('--dali_cpu', action='store_true',
help='Runs CPU based version of DALI pipeline.')
parser.add_argument('--disable_dali', default=False, action='store_true',
help='Disable DALI data loader and use native PyTorch one instead.')
parser.add_argument('--prof', default=-1, type=int,
help='Only run 10 iterations for profiling.')
parser.add_argument('--deterministic', action='store_true')
parser.add_argument('--fp16-mode', default=False, action='store_true',
help='Enable half precision mode.')
parser.add_argument('--loss-scale', type=float, default=1)
parser.add_argument('--channels-last', type=bool, default=False)
parser.add_argument('-t', '--test', action='store_true',
help='Launch test mode with preset arguments')
args = parser.parse_args()
return args
# item() is a recent addition, so this helps with backward compatibility.
def to_python_float(t):
if hasattr(t, 'item'):
return t.item()
else:
return t[0]
@pipeline_def
def create_dali_pipeline(data_dir, crop, size, shard_id, num_shards, dali_cpu=False, is_training=True):
images, labels = fn.readers.file(file_root=data_dir,
shard_id=shard_id,
num_shards=num_shards,
random_shuffle=is_training,
pad_last_batch=True,
name="Reader")
dali_device = 'cpu' if dali_cpu else 'gpu'
decoder_device = 'cpu' if dali_cpu else 'mixed'
# ask nvJPEG to preallocate memory for the biggest sample in ImageNet for CPU and GPU to avoid reallocations in runtime
device_memory_padding = 211025920 if decoder_device == 'mixed' else 0
host_memory_padding = 140544512 if decoder_device == 'mixed' else 0
# ask HW NVJPEG to allocate memory ahead for the biggest image in the data set to avoid reallocations in runtime
preallocate_width_hint = 5980 if decoder_device == 'mixed' else 0
preallocate_height_hint = 6430 if decoder_device == 'mixed' else 0
if is_training:
images = fn.decoders.image_random_crop(images,
device=decoder_device, output_type=types.RGB,
device_memory_padding=device_memory_padding,
host_memory_padding=host_memory_padding,
preallocate_width_hint=preallocate_width_hint,
preallocate_height_hint=preallocate_height_hint,
random_aspect_ratio=[0.8, 1.25],
random_area=[0.1, 1.0],
num_attempts=100)
images = fn.resize(images,
device=dali_device,
resize_x=crop,
resize_y=crop,
interp_type=types.INTERP_TRIANGULAR)
mirror = fn.random.coin_flip(probability=0.5)
else:
images = fn.decoders.image(images,
device=decoder_device,
output_type=types.RGB)
images = fn.resize(images,
device=dali_device,
size=size,
mode="not_smaller",
interp_type=types.INTERP_TRIANGULAR)
mirror = False
images = fn.crop_mirror_normalize(images.gpu(),
dtype=types.FLOAT,
output_layout="CHW",
crop=(crop, crop),
mean=[0.485 * 255,0.456 * 255,0.406 * 255],
std=[0.229 * 255,0.224 * 255,0.225 * 255],
mirror=mirror)
labels = labels.gpu()
return images, labels
def main():
global best_prec1, args
best_prec1 = 0
args = parse()
if not len(args.data):
raise Exception("error: No data set provided")
if args.test:
print("Test mode - only 10 iterations")
args.distributed = False
if 'WORLD_SIZE' in os.environ:
args.distributed = int(os.environ['WORLD_SIZE']) > 1
if 'LOCAL_RANK' in os.environ:
args.local_rank = int(os.environ['LOCAL_RANK'])
else:
args.local_rank = 0
print("fp16_mode = {}".format(args.fp16_mode))
print("loss_scale = {}".format(args.loss_scale), type(args.loss_scale))
print("\nCUDNN VERSION: {}\n".format(torch.backends.cudnn.version()))
cudnn.benchmark = True
best_prec1 = 0
if args.deterministic:
cudnn.benchmark = False
cudnn.deterministic = True
torch.manual_seed(args.local_rank)
torch.set_printoptions(precision=10)
args.gpu = 0
args.world_size = 1
if args.distributed:
args.gpu = args.local_rank
torch.cuda.set_device(args.gpu)
torch.distributed.init_process_group(backend='nccl',
init_method='env://')
args.world_size = torch.distributed.get_world_size()
args.total_batch_size = args.world_size * args.batch_size
assert torch.backends.cudnn.enabled, "Amp requires cudnn backend to be enabled."
# create model
if args.pretrained:
print("=> using pre-trained model '{}'".format(args.arch))
model = models.__dict__[args.arch](pretrained=True)
else:
print("=> creating model '{}'".format(args.arch))
model = models.__dict__[args.arch]()
if hasattr(torch, 'channels_last') and hasattr(torch, 'contiguous_format'):
if args.channels_last:
memory_format = torch.channels_last
else:
memory_format = torch.contiguous_format
model = model.cuda().to(memory_format=memory_format)
else:
model = model.cuda()
# Scale learning rate based on global batch size
args.lr = args.lr*float(args.batch_size*args.world_size)/256.
optimizer = torch.optim.SGD(model.parameters(), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
if args.distributed:
s = torch.cuda.Stream()
s.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(s):
model = DDP(model, device_ids=[args.local_rank], output_device=args.local_rank)
torch.cuda.current_stream().wait_stream(s)
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
# Optionally resume from a checkpoint
if args.resume:
# Use a local scope to avoid dangling references
def resume():
if os.path.isfile(args.resume):
print("=> loading checkpoint '{}'".format(args.resume))
checkpoint = torch.load(args.resume, map_location = lambda storage, loc: storage.cuda(args.gpu))
args.start_epoch = checkpoint['epoch']
global best_prec1
best_prec1 = checkpoint['best_prec1']
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
print("=> loaded checkpoint '{}' (epoch {})"
.format(args.resume, checkpoint['epoch']))
else:
print("=> no checkpoint found at '{}'".format(args.resume))
resume()
# Data loading code
if len(args.data) == 1:
traindir = os.path.join(args.data[0], 'train')
valdir = os.path.join(args.data[0], 'val')
else:
traindir = args.data[0]
valdir= args.data[1]
if args.arch == "inception_v3":
raise RuntimeError("Currently, inception_v3 is not supported by this example.")
# crop_size = 299
# val_size = 320 # I chose this value arbitrarily, we can adjust.
else:
crop_size = 224
val_size = 256
train_loader = None
val_loader = None
if not args.disable_dali:
train_pipe = create_dali_pipeline(batch_size=args.batch_size,
num_threads=args.workers,
device_id=args.local_rank,
seed=12 + args.local_rank,
data_dir=traindir,
crop=crop_size,
size=val_size,
dali_cpu=args.dali_cpu,
shard_id=args.local_rank,
num_shards=args.world_size,
is_training=True)
train_pipe.build()
train_loader = DALIClassificationIterator(train_pipe, reader_name="Reader",
last_batch_policy=LastBatchPolicy.PARTIAL,
auto_reset=True)
val_pipe = create_dali_pipeline(batch_size=args.batch_size,
num_threads=args.workers,
device_id=args.local_rank,
seed=12 + args.local_rank,
data_dir=valdir,
crop=crop_size,
size=val_size,
dali_cpu=args.dali_cpu,
shard_id=args.local_rank,
num_shards=args.world_size,
is_training=False)
val_pipe.build()
val_loader = DALIClassificationIterator(val_pipe, reader_name="Reader",
last_batch_policy=LastBatchPolicy.PARTIAL,
auto_reset=True)
else:
train_dataset = datasets.ImageFolder(traindir,
transforms.Compose([transforms.RandomResizedCrop(crop_size),
transforms.RandomHorizontalFlip()]))
val_dataset = datasets.ImageFolder(valdir,
transforms.Compose([transforms.Resize(val_size),
transforms.CenterCrop(crop_size)]))
train_sampler = None
val_sampler = None
if args.distributed:
train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
val_sampler = torch.utils.data.distributed.DistributedSampler(val_dataset)
collate_fn = lambda b: fast_collate(b, memory_format)
train_loader = torch.utils.data.DataLoader(train_dataset,
batch_size=args.batch_size,
shuffle=(train_sampler is None),
num_workers=args.workers,
pin_memory=True,
sampler=train_sampler,
collate_fn=collate_fn)
val_loader = torch.utils.data.DataLoader(val_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.workers,
pin_memory=True,
sampler=val_sampler,
collate_fn=collate_fn)
if args.evaluate:
validate(val_loader, model, criterion)
return
scaler = torch.cuda.amp.GradScaler(init_scale=args.loss_scale,
growth_factor=2,
backoff_factor=0.5,
growth_interval=100,
enabled=args.fp16_mode)
total_time = AverageMeter()
for epoch in range(args.start_epoch, args.epochs):
# train for one epoch
avg_train_time = train(train_loader, model, criterion, scaler, optimizer, epoch)
total_time.update(avg_train_time)
if args.test:
break
# evaluate on validation set
[prec1, prec5] = validate(val_loader, model, criterion)
# remember best prec@1 and save checkpoint
if args.local_rank == 0:
is_best = prec1 > best_prec1
best_prec1 = max(prec1, best_prec1)
save_checkpoint({
'epoch': epoch + 1,
'arch': args.arch,
'state_dict': model.state_dict(),
'best_prec1': best_prec1,
'optimizer' : optimizer.state_dict(),
}, is_best)
if epoch == args.epochs - 1:
print('##Top-1 {0}\n'
'##Top-5 {1}\n'
'##Perf {2}'.format(
prec1,
prec5,
args.total_batch_size / total_time.avg))
class data_prefetcher():
"""Based on prefetcher from the APEX example
https://github.com/NVIDIA/apex/blob/5b5d41034b506591a316c308c3d2cd14d5187e23/examples/imagenet/main_amp.py#L265
"""
def __init__(self, loader):
self.loader = iter(loader)
self.stream = torch.cuda.Stream()
self.mean = torch.tensor([0.485 * 255, 0.456 * 255, 0.406 * 255]).cuda().view(1,3,1,1)
self.std = torch.tensor([0.229 * 255, 0.224 * 255, 0.225 * 255]).cuda().view(1,3,1,1)
self.preload()
def preload(self):
try:
self.next_input, self.next_target = next(self.loader)
except StopIteration:
self.next_input = None
self.next_target = None
return
with torch.cuda.stream(self.stream):
self.next_input = self.next_input.cuda(non_blocking=True)
self.next_target = self.next_target.cuda(non_blocking=True)
self.next_input = self.next_input.float()
self.next_input = self.next_input.sub_(self.mean).div_(self.std)
def __iter__(self):
return self
def __next__(self):
"""The iterator was added on top of the orignal example to align it with DALI iterator
"""
torch.cuda.current_stream().wait_stream(self.stream)
input = self.next_input
target = self.next_target
if input is not None:
input.record_stream(torch.cuda.current_stream())
if target is not None:
target.record_stream(torch.cuda.current_stream())
self.preload()
if input is None:
raise StopIteration
return input, target
def train(train_loader, model, criterion, scaler, optimizer, epoch):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
end = time.time()
if args.disable_dali:
data_iterator = data_prefetcher(train_loader)
data_iterator = iter(data_iterator)
else:
data_iterator = train_loader
for i, data in enumerate(data_iterator):
if args.disable_dali:
input, target = data
train_loader_len = len(train_loader)
else:
input = data[0]["data"]
target = data[0]["label"].squeeze(-1).long()
train_loader_len = int(math.ceil(data_iterator._size / args.batch_size))
if args.prof >= 0 and i == args.prof:
print("Profiling begun at iteration {}".format(i))
torch.cuda.cudart().cudaProfilerStart()
if args.prof >= 0: torch.cuda.nvtx.range_push("Body of iteration {}".format(i))
adjust_learning_rate(optimizer, epoch, i, train_loader_len)
if args.test:
if i > 10:
break
with torch.cuda.amp.autocast(enabled=args.fp16_mode):
output = model(input)
loss = criterion(output, target)
# compute output
if args.prof >= 0: torch.cuda.nvtx.range_push("forward")
if args.prof >= 0: torch.cuda.nvtx.range_pop()
# compute gradient and do SGD step
optimizer.zero_grad()
if args.prof >= 0: torch.cuda.nvtx.range_push("backward")
scaler.scale(loss).backward()
if args.prof >= 0: torch.cuda.nvtx.range_pop()
if args.prof >= 0: torch.cuda.nvtx.range_push("optimizer.step()")
scaler.step(optimizer)
if args.prof >= 0: torch.cuda.nvtx.range_pop()
scaler.update()
if i%args.print_freq == 0:
# Every print_freq iterations, check the loss, accuracy, and speed.
# For best performance, it doesn't make sense to print these metrics every
# iteration, since they incur an allreduce and some host<->device syncs.
# Measure accuracy
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
# Average loss and accuracy across processes for logging
if args.distributed:
reduced_loss = reduce_tensor(loss.data)
prec1 = reduce_tensor(prec1)
prec5 = reduce_tensor(prec5)
else:
reduced_loss = loss.data
# to_python_float incurs a host<->device sync
losses.update(to_python_float(reduced_loss), input.size(0))
top1.update(to_python_float(prec1), input.size(0))
top5.update(to_python_float(prec5), input.size(0))
torch.cuda.synchronize()
batch_time.update((time.time() - end)/args.print_freq)
end = time.time()
if args.local_rank == 0:
print('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Speed {3:.3f} ({4:.3f})\t'
'Loss {loss.val:.10f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
epoch, i, train_loader_len,
args.world_size*args.batch_size/batch_time.val,
args.world_size*args.batch_size/batch_time.avg,
batch_time=batch_time,
loss=losses, top1=top1, top5=top5))
# Pop range "Body of iteration {}".format(i)
if args.prof >= 0: torch.cuda.nvtx.range_pop()
if args.prof >= 0 and i == args.prof + 10:
print("Profiling ended at iteration {}".format(i))
torch.cuda.cudart().cudaProfilerStop()
quit()
return batch_time.avg
def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
if args.disable_dali:
data_iterator = data_prefetcher(val_loader)
data_iterator = iter(data_iterator)
else:
data_iterator = val_loader
for i, data in enumerate(data_iterator):
if args.disable_dali:
input, target = data
val_loader_len = len(val_loader)
else:
input = data[0]["data"]
target = data[0]["label"].squeeze(-1).long()
val_loader_len = int(math.ceil(data_iterator._size / args.batch_size))
# compute output
with torch.no_grad():
output = model(input)
loss = criterion(output, target)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
if args.distributed:
reduced_loss = reduce_tensor(loss.data)
prec1 = reduce_tensor(prec1)
prec5 = reduce_tensor(prec5)
else:
reduced_loss = loss.data
losses.update(to_python_float(reduced_loss), input.size(0))
top1.update(to_python_float(prec1), input.size(0))
top5.update(to_python_float(prec5), input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
# TODO: Change timings to mirror train().
if args.local_rank == 0 and i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Speed {2:.3f} ({3:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, val_loader_len,
args.world_size * args.batch_size / batch_time.val,
args.world_size * args.batch_size / batch_time.avg,
batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return [top1.avg, top5.avg]
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, step, len_epoch):
"""LR schedule that should yield 76% converged accuracy with batch size 256"""
factor = epoch // 30
if epoch >= 80:
factor = factor + 1
lr = args.lr*(0.1**factor)
"""Warmup"""
if epoch < 5:
lr = lr*float(1 + step + epoch*len_epoch)/(5.*len_epoch)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
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.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
def reduce_tensor(tensor):
rt = tensor.clone()
dist.all_reduce(rt, op=dist.ReduceOp.SUM)
rt /= args.world_size
return rt
if __name__ == '__main__':
main()
|
DALI-main
|
docs/examples/use_cases/pytorch/resnet50/main.py
|
# Copyright (c) 2019-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# 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 PIL import Image
import argparse
import numpy as np
import json
import torch
from torch.cuda.amp import autocast
import torch.backends.cudnn as cudnn
from image_classification import models
import torchvision.transforms as transforms
from image_classification.models import efficientnet_b0
def available_models():
models = {m.name: m for m in [efficientnet_b0]}
return models
def add_parser_arguments(parser):
model_names = available_models().keys()
parser.add_argument("--image-size", default="224", type=int)
parser.add_argument(
"--arch",
"-a",
metavar="ARCH",
default="efficientnet-b0",
choices=model_names,
help="model architecture: " + " | ".join(model_names) + " (default: efficientnet-b0)",
)
parser.add_argument(
"--precision", metavar="PREC", default="AMP", choices=["AMP", "FP32"]
)
parser.add_argument("--cpu", action="store_true", help="perform inference on CPU")
parser.add_argument("--image", metavar="<path>", help="path to classified image")
def load_jpeg_from_file(path, image_size, cuda=True):
img_transforms = transforms.Compose(
[
transforms.Resize(image_size + 32),
transforms.CenterCrop(image_size),
transforms.ToTensor(),
]
)
img = img_transforms(Image.open(path))
with torch.no_grad():
# mean and std are not multiplied by 255 as they are in training script
# torch dataloader reads data into bytes whereas loading directly
# through PIL creates a tensor with floats in [0,1] range
mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
if cuda:
mean = mean.cuda()
std = std.cuda()
img = img.cuda()
img = img.float()
input = img.unsqueeze(0).sub_(mean).div_(std)
return input
def check_quant_weight_correctness(checkpoint_path, model):
state_dict = torch.load(checkpoint_path, map_location=torch.device("cpu"))
state_dict = {
k[len("module.") :] if k.startswith("module.") else k: v
for k, v in state_dict.items()
}
quantizers_sd_keys = {
f"{n[0]}._amax" for n in model.named_modules() if "quantizer" in n[0]
}
sd_all_keys = quantizers_sd_keys | set(model.state_dict().keys())
assert set(state_dict.keys()) == sd_all_keys, (
f"Passed quantized architecture, but following keys are missing in "
f"checkpoint: {list(sd_all_keys - set(state_dict.keys()))}"
)
def main(args, model_args):
imgnet_classes = np.array(json.load(open("./LOC_synset_mapping.json", "r")))
try:
model = available_models()[args.arch](**model_args.__dict__)
except RuntimeError as e:
print_in_box(
"Error when creating model, did you forget to run checkpoint2model script?"
)
raise e
if args.arch in ["efficientnet-quant-b0", "efficientnet-quant-b4"]:
check_quant_weight_correctness(model_args.pretrained_from_file, model)
if not args.cpu:
model = model.cuda()
model.eval()
input = load_jpeg_from_file(args.image, args.image_size, cuda=not args.cpu)
with torch.no_grad(), autocast(enabled=args.precision == "AMP"):
output = torch.nn.functional.softmax(model(input), dim=1)
output = output.float().cpu().view(-1).numpy()
top5 = np.argsort(output)[-5:][::-1]
print(args.image)
for c, v in zip(imgnet_classes[top5], output[top5]):
print(f"{c}: {100*v:.1f}%")
def print_in_box(msg):
print("#" * (len(msg) + 10))
print(f"#### {msg} ####")
print("#" * (len(msg) + 10))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="PyTorch ImageNet Classification")
add_parser_arguments(parser)
args, rest = parser.parse_known_args()
model_args, rest = available_models()[args.arch].parser().parse_known_args(rest)
assert len(rest) == 0, f"Unknown args passed: {rest}"
cudnn.benchmark = True
main(args, model_args)
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/classify.py
|
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# 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 argparse
import torch
def add_parser_arguments(parser):
parser.add_argument(
"--checkpoint-path", metavar="<path>", help="checkpoint filename"
)
parser.add_argument(
"--weight-path", metavar="<path>", help="name of file in which to store weights"
)
parser.add_argument("--ema", action="store_true", default=False)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="PyTorch ImageNet Training")
add_parser_arguments(parser)
args = parser.parse_args()
checkpoint = torch.load(args.checkpoint_path, map_location=torch.device("cpu"))
key = "state_dict" if not args.ema else "ema_state_dict"
model_state_dict = {
k[len("module.") :] if "module." in k else k: v
for k, v in checkpoint["state_dict"].items()
}
print(f"Loaded model, acc : {checkpoint['best_prec1']}")
torch.save(model_state_dict, args.weight_path)
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/checkpoint2model.py
|
# Copyright (c) 2018-2019, NVIDIA CORPORATION
# Copyright (c) 2017- Facebook, Inc
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
os.environ[
"KMP_AFFINITY"
] = "disabled" # We need to do this before importing anything else as a workaround for this bug: https://github.com/pytorch/pytorch/issues/28389
import argparse
import random
from copy import deepcopy
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import image_classification.logger as log
from image_classification.smoothing import LabelSmoothing
from image_classification.mixup import NLLMultiLabelSmooth, MixUpWrapper
from image_classification.dataloaders import *
from image_classification.training import *
from image_classification.utils import *
from image_classification.models import efficientnet_b0
from image_classification.optimizers import (
get_optimizer,
lr_cosine_policy,
lr_linear_policy,
lr_step_policy,
)
from image_classification.gpu_affinity import set_affinity, AffinityMode
import dllogger
def available_models():
models = {m.name: m for m in [efficientnet_b0]}
return models
def add_parser_arguments(parser, skip_arch=False):
parser.add_argument("data", metavar="DIR", help="path to dataset")
parser.add_argument(
"--data-backend",
metavar="BACKEND",
default="dali",
choices=DATA_BACKEND_CHOICES,
help="data backend: "
+ " | ".join(DATA_BACKEND_CHOICES)
+ " (default: dali)",
)
parser.add_argument(
"--interpolation",
metavar="INTERPOLATION",
default="bicubic",
help="interpolation type for resizing images: bilinear, bicubic or triangular (DALI only)",
)
if not skip_arch:
model_names = available_models().keys()
parser.add_argument(
"--arch",
"-a",
metavar="ARCH",
default="efficientnet-b0",
choices=model_names,
help="model architecture: "
+ " | ".join(model_names)
+ " (default: efficientnet-b0)",
)
parser.add_argument(
"-j",
"--workers",
default=4,
type=int,
metavar="N",
help=("number of data loading workers (default: 4)."
" The number of workers for PyTorch loader is doubled."),
)
parser.add_argument(
"--prefetch",
default=4,
type=int,
metavar="N",
help="number of samples prefetched by each loader (PyTorch only)",
)
parser.add_argument(
"--dali-device",
default="gpu",
type=str,
choices=["cpu", "gpu"],
help=("The placement of DALI decode and random resized crop operations (default: gpu)"),
)
parser.add_argument(
"--epochs",
default=400,
type=int,
metavar="N",
help="number of total epochs to run",
)
parser.add_argument(
"--run-epochs",
default=-1,
type=int,
metavar="N",
help="run only N epochs, used for checkpointing runs",
)
parser.add_argument(
"--early-stopping-patience",
default=-1,
type=int,
metavar="N",
help="early stopping after N epochs without validation accuracy improving",
)
parser.add_argument(
"--image-size", default=224, type=int, help="resolution of image"
)
parser.add_argument(
"-b",
"--batch-size",
default=64,
type=int,
metavar="N",
help="mini-batch size (default: 64) per gpu",
)
parser.add_argument(
"--optimizer-batch-size",
default=4096,
type=int,
metavar="N",
help="size of a total batch size, for simulating bigger batches using gradient accumulation",
)
parser.add_argument(
"--lr",
"--learning-rate",
default=0.08,
type=float,
metavar="LR",
help="initial learning rate",
)
parser.add_argument(
"--lr-schedule",
default="cosine",
type=str,
metavar="SCHEDULE",
choices=["step", "linear", "cosine"],
help="Type of LR schedule: {}, {}, {}".format("step", "linear", "cosine"),
)
parser.add_argument("--end-lr", default=0, type=float)
parser.add_argument(
"--warmup", default=16, type=int, metavar="E", help="number of warmup epochs"
)
parser.add_argument(
"--label-smoothing",
default=0.1,
type=float,
metavar="S",
help="label smoothing",
)
parser.add_argument(
"--mixup", default=0.2, type=float, metavar="ALPHA", help="mixup alpha"
)
parser.add_argument(
"--optimizer", default="rmsprop", type=str, choices=("sgd", "rmsprop")
)
parser.add_argument(
"--momentum", default=0.9, type=float, metavar="M", help="momentum"
)
parser.add_argument(
"--weight-decay",
"--wd",
default=1e-05,
type=float,
metavar="W",
help="weight decay (default: 1e-5)",
)
parser.add_argument(
"--bn-weight-decay",
action="store_true",
help="use weight_decay on batch normalization learnable parameters, (default: false)",
)
parser.add_argument(
"--rmsprop-alpha",
default=0.9,
type=float,
help="value of alpha parameter in rmsprop optimizer (default: 0.9)",
)
parser.add_argument(
"--rmsprop-eps",
default=0.01,
type=float,
help="value of eps parameter in rmsprop optimizer (default: 0.01)",
)
parser.add_argument(
"--nesterov",
action="store_true",
help="use nesterov momentum, (default: false)",
)
parser.add_argument(
"--print-freq",
"-p",
default=100,
type=int,
metavar="N",
help="print frequency (default: 100)",
)
parser.add_argument(
"--resume",
default=None,
type=str,
metavar="PATH",
help="path to latest checkpoint (default: none)",
)
parser.add_argument(
"--static-loss-scale",
type=float,
default=1,
help="Static loss scale, positive power of 2 values can improve amp convergence.",
)
parser.add_argument(
"--prof", type=int, default=-1, metavar="N", help="Run only N iterations"
)
parser.add_argument(
"--amp",
action="store_true",
help="Run model AMP (automatic mixed precision) mode.",
)
parser.add_argument(
"--seed", default=None, type=int, help="random seed used for numpy and pytorch"
)
parser.add_argument(
"--gather-checkpoints",
default="0",
type=int,
help=(
"Gather N last checkpoints throughout the training,"
" without this flag only best and last checkpoints will be stored. "
"Use -1 for all checkpoints"
),
)
parser.add_argument(
"--raport-file",
default="experiment_raport.json",
type=str,
help="file in which to store JSON experiment raport",
)
parser.add_argument(
"--evaluate", action="store_true", help="evaluate checkpoint/model"
)
parser.add_argument("--training-only", action="store_true", help="do not evaluate")
parser.add_argument(
"--no-checkpoints",
action="store_false",
dest="save_checkpoints",
help="do not store any checkpoints, useful for benchmarking",
)
parser.add_argument(
"--jit",
type=str,
default="no",
choices=["no", "script"],
help="no -> do not use torch.jit; script -> use torch.jit.script",
)
parser.add_argument("--checkpoint-filename", default="checkpoint.pth.tar", type=str)
parser.add_argument(
"--workspace",
type=str,
default="./",
metavar="DIR",
help="path to directory where checkpoints will be stored",
)
parser.add_argument(
"--memory-format",
type=str,
default="nhwc",
choices=["nchw", "nhwc"],
help="memory layout, nchw or nhwc",
)
parser.add_argument("--use-ema", default=None, type=float, help="use EMA")
parser.add_argument(
"--automatic-augmentation",
type=str,
default="autoaugment",
choices=["disabled", "autoaugment", "trivialaugment"],
help="Automatic augmentation method, trivialaugment is supported only for DALI data backend",
)
parser.add_argument(
"--gpu-affinity",
type=str,
default="socket_unique_contiguous",
required=False,
choices=[am.name for am in AffinityMode],
)
parser.add_argument(
"--topk",
type=int,
default=5,
required=False,
)
def prepare_for_training(args, model_args, model_arch):
args.distributed = False
if "WORLD_SIZE" in os.environ:
args.distributed = int(os.environ["WORLD_SIZE"]) > 1
args.local_rank = int(os.environ["LOCAL_RANK"])
else:
args.local_rank = 0
args.gpu = 0
args.world_size = 1
if args.distributed:
args.gpu = args.local_rank % torch.cuda.device_count()
torch.cuda.set_device(args.gpu)
dist.init_process_group(backend="nccl", init_method="env://")
args.world_size = torch.distributed.get_world_size()
affinity = set_affinity(args.gpu, mode=args.gpu_affinity)
print(f"Training process {args.local_rank} affinity: {affinity}")
if args.seed is not None:
print("Using seed = {}".format(args.seed))
torch.manual_seed(args.seed + args.local_rank)
torch.cuda.manual_seed(args.seed + args.local_rank)
np.random.seed(seed=args.seed + args.local_rank)
random.seed(args.seed + args.local_rank)
def _worker_init_fn(id):
# Worker process should inherit its affinity from parent
affinity = os.sched_getaffinity(0)
print(f"Process {args.local_rank} Worker {id} set affinity to: {affinity}")
np.random.seed(seed=args.seed + args.local_rank + id)
random.seed(args.seed + args.local_rank + id)
else:
def _worker_init_fn(id):
# Worker process should inherit its affinity from parent
affinity = os.sched_getaffinity(0)
print(f"Process {args.local_rank} Worker {id} set affinity to: {affinity}")
if args.static_loss_scale != 1.0:
if not args.amp:
print("Warning: if --amp is not used, static_loss_scale will be ignored.")
if args.optimizer_batch_size < 0:
batch_size_multiplier = 1
else:
tbs = args.world_size * args.batch_size
if args.optimizer_batch_size % tbs != 0:
print(
"Warning: simulated batch size {} is not divisible by actual batch size {}".format(
args.optimizer_batch_size, tbs
)
)
batch_size_multiplier = int(args.optimizer_batch_size / tbs)
print("BSM: {}".format(batch_size_multiplier))
start_epoch = 0
best_prec1 = 0
# optionally resume from a checkpoint
if args.resume is not None:
if os.path.isfile(args.resume):
print("=> loading checkpoint '{}'".format(args.resume))
checkpoint = torch.load(
args.resume, map_location=lambda storage, loc: storage.cuda(args.gpu)
)
start_epoch = checkpoint["epoch"]
best_prec1 = checkpoint["best_prec1"]
model_state = checkpoint["state_dict"]
optimizer_state = checkpoint["optimizer"]
if "state_dict_ema" in checkpoint:
model_state_ema = checkpoint["state_dict_ema"]
print(
"=> loaded checkpoint '{}' (epoch {})".format(
args.resume, checkpoint["epoch"]
)
)
if start_epoch >= args.epochs:
print(
f"Launched training for {args.epochs}, checkpoint already run {start_epoch}"
)
exit(1)
else:
print("=> no checkpoint found at '{}'".format(args.resume))
model_state = None
model_state_ema = None
optimizer_state = None
else:
model_state = None
model_state_ema = None
optimizer_state = None
loss = nn.CrossEntropyLoss
if args.mixup > 0.0:
loss = lambda: NLLMultiLabelSmooth(args.label_smoothing)
elif args.label_smoothing > 0.0:
loss = lambda: LabelSmoothing(args.label_smoothing)
memory_format = (
torch.channels_last if args.memory_format == "nhwc" else torch.contiguous_format
)
model = model_arch(
**{
k: v
if k != "pretrained"
else v and (not args.distributed or dist.get_rank() == 0)
for k, v in model_args.__dict__.items()
}
)
image_size = (
args.image_size
if args.image_size is not None
else model.arch.default_image_size
)
scaler = torch.cuda.amp.GradScaler(
init_scale=args.static_loss_scale,
growth_factor=2,
backoff_factor=0.5,
growth_interval=100,
enabled=args.amp,
)
executor = Executor(
model,
loss(),
cuda=True,
memory_format=memory_format,
amp=args.amp,
scaler=scaler,
divide_loss=batch_size_multiplier,
ts_script=args.jit == "script",
)
# Create data loaders and optimizers as needed
if args.data_backend == "pytorch":
args.workers = args.workers * 2
get_train_loader = get_pytorch_train_loader
get_val_loader = get_pytorch_val_loader
elif args.data_backend == "dali":
get_train_loader = get_dali_train_loader(dali_device=args.dali_device)
get_val_loader = get_dali_val_loader()
elif args.data_backend == "synthetic":
get_val_loader = get_synthetic_loader
get_train_loader = get_synthetic_loader
else:
print("Bad databackend picked")
exit(1)
train_loader, train_loader_len = get_train_loader(
args.data,
image_size,
args.batch_size,
model_args.num_classes,
args.mixup > 0.0,
interpolation=args.interpolation,
augmentation=args.automatic_augmentation,
start_epoch=start_epoch,
workers=args.workers,
_worker_init_fn=_worker_init_fn,
memory_format=memory_format,
prefetch_factor=args.prefetch,
)
if args.mixup != 0.0:
train_loader = MixUpWrapper(args.mixup, train_loader)
val_loader, val_loader_len = get_val_loader(
args.data,
image_size,
args.batch_size,
model_args.num_classes,
False,
interpolation=args.interpolation,
workers=args.workers,
_worker_init_fn=_worker_init_fn,
memory_format=memory_format,
prefetch_factor=args.prefetch,
)
if not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0:
logger = log.Logger(
args.print_freq,
[
dllogger.StdOutBackend(
dllogger.Verbosity.DEFAULT, step_format=log.format_step
),
dllogger.JSONStreamBackend(
dllogger.Verbosity.VERBOSE,
os.path.join(args.workspace, args.raport_file),
),
],
start_epoch=start_epoch - 1,
)
else:
logger = log.Logger(args.print_freq, [], start_epoch=start_epoch - 1)
logger.log_parameter(args.__dict__, verbosity=dllogger.Verbosity.DEFAULT)
logger.log_parameter(
{f"model.{k}": v for k, v in model_args.__dict__.items()},
verbosity=dllogger.Verbosity.DEFAULT,
)
optimizer = get_optimizer(
list(executor.model.named_parameters()),
args.lr,
args=args,
state=optimizer_state,
)
if args.lr_schedule == "step":
lr_policy = lr_step_policy(args.lr, [30, 60, 80], 0.1, args.warmup)
elif args.lr_schedule == "cosine":
lr_policy = lr_cosine_policy(
args.lr, args.warmup, args.epochs, end_lr=args.end_lr
)
elif args.lr_schedule == "linear":
lr_policy = lr_linear_policy(args.lr, args.warmup, args.epochs)
if args.distributed:
executor.distributed(args.gpu)
if model_state is not None:
executor.model.load_state_dict(model_state)
trainer = Trainer(
executor,
optimizer,
grad_acc_steps=batch_size_multiplier,
ema=args.use_ema,
)
if (args.use_ema is not None) and (model_state_ema is not None):
trainer.ema_executor.model.load_state_dict(model_state_ema)
return (
trainer,
lr_policy,
train_loader,
train_loader_len,
val_loader,
logger,
start_epoch,
best_prec1,
)
def main(args, model_args, model_arch):
exp_start_time = time.time()
(
trainer,
lr_policy,
train_loader,
train_loader_len,
val_loader,
logger,
start_epoch,
best_prec1,
) = prepare_for_training(args, model_args, model_arch)
train_loop(
trainer,
lr_policy,
train_loader,
train_loader_len,
val_loader,
logger,
start_epoch=start_epoch,
end_epoch=min((start_epoch + args.run_epochs), args.epochs)
if args.run_epochs != -1
else args.epochs,
early_stopping_patience=args.early_stopping_patience,
best_prec1=best_prec1,
prof=args.prof,
skip_training=args.evaluate,
skip_validation=args.training_only,
save_checkpoints=args.save_checkpoints and not args.evaluate,
checkpoint_dir=args.workspace,
checkpoint_filename=args.checkpoint_filename,
keep_last_n_checkpoints=args.gather_checkpoints,
topk=args.topk,
)
exp_duration = time.time() - exp_start_time
if not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0:
logger.end()
print("Experiment ended")
if __name__ == "__main__":
epilog = [
"Based on the architecture picked by --arch flag, you may use the following options:\n"
]
for model, ep in available_models().items():
model_help = "\n".join(ep.parser().format_help().split("\n")[2:])
epilog.append(model_help)
parser = argparse.ArgumentParser(
description="PyTorch EfficientNet Training",
epilog="\n".join(epilog),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
add_parser_arguments(parser)
args, rest = parser.parse_known_args()
model_arch = available_models()[args.arch]
model_args, rest = model_arch.parser().parse_known_args(rest)
print(model_args)
assert len(rest) == 0, f"Unknown args passed: {rest}"
cudnn.benchmark = True
main(args, model_args, model_arch)
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/main.py
|
# From PyTorch:
#
# Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
# Copyright (c) 2016- Facebook, Inc (Adam Paszke)
# Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
# Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
# Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
# Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
# Copyright (c) 2011-2013 NYU (Clement Farabet)
# Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
# Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
# Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
#
# From Caffe2:
#
# Copyright (c) 2016-present, Facebook Inc. All rights reserved.
#
# All contributions by Facebook:
# Copyright (c) 2016 Facebook Inc.
#
# All contributions by Google:
# Copyright (c) 2015 Google Inc.
# All rights reserved.
#
# All contributions by Yangqing Jia:
# Copyright (c) 2015 Yangqing Jia
# All rights reserved.
#
# All contributions from Caffe:
# Copyright(c) 2013, 2014, 2015, the respective contributors
# All rights reserved.
#
# All other contributions:
# Copyright(c) 2015, 2016 the respective contributors
# All rights reserved.
#
# Caffe2 uses a copyright model similar to Caffe: each contributor holds
# copyright over their contributions to Caffe2. The project versioning records
# all such contribution and copyright details. If a contributor wants to further
# mark their specific copyright on a particular contribution, they should
# indicate their copyright solely in the commit message of the change when it is
# committed.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America
# and IDIAP Research Institute nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import sys
import subprocess
import os
import socket
import time
from argparse import ArgumentParser, REMAINDER
import torch
def parse_args():
"""
Helper function parsing the command line options
@retval ArgumentParser
"""
parser = ArgumentParser(
description="PyTorch distributed training launch "
"helper utilty that will spawn up "
"multiple distributed processes"
)
# Optional arguments for the launch helper
parser.add_argument(
"--nnodes",
type=int,
default=1,
help="The number of nodes to use for distributed " "training",
)
parser.add_argument(
"--node_rank",
type=int,
default=0,
help="The rank of the node for multi-node distributed " "training",
)
parser.add_argument(
"--nproc_per_node",
type=int,
default=1,
help="The number of processes to launch on each node, "
"for GPU training, this is recommended to be set "
"to the number of GPUs in your system so that "
"each process can be bound to a single GPU.",
)
parser.add_argument(
"--master_addr",
default="127.0.0.1",
type=str,
help="Master node (rank 0)'s address, should be either "
"the IP address or the hostname of node 0, for "
"single node multi-proc training, the "
"--master_addr can simply be 127.0.0.1",
)
parser.add_argument(
"--master_port",
default=29500,
type=int,
help="Master node (rank 0)'s free port that needs to "
"be used for communciation during distributed "
"training",
)
# positional
parser.add_argument(
"training_script",
type=str,
help="The full path to the single GPU training "
"program/script to be launched in parallel, "
"followed by all the arguments for the "
"training script",
)
# rest from the training program
parser.add_argument("training_script_args", nargs=REMAINDER)
return parser.parse_args()
def main():
args = parse_args()
# world size in terms of number of processes
dist_world_size = args.nproc_per_node * args.nnodes
# set PyTorch distributed related environmental variables
current_env = os.environ.copy()
current_env["MASTER_ADDR"] = args.master_addr
current_env["MASTER_PORT"] = str(args.master_port)
current_env["WORLD_SIZE"] = str(dist_world_size)
processes = []
for local_rank in range(0, args.nproc_per_node):
# each process's rank
dist_rank = args.nproc_per_node * args.node_rank + local_rank
current_env["RANK"] = str(dist_rank)
current_env["LOCAL_RANK"] = str(local_rank)
# spawn the processes
cmd = [sys.executable, "-u", args.training_script] + args.training_script_args
print(cmd)
stdout = (
None if local_rank == 0 else open("GPU_" + str(local_rank) + ".log", "w")
)
process = subprocess.Popen(cmd, env=current_env, stdout=stdout, stderr=stdout)
processes.append(process)
try:
up = True
error = False
while up and not error:
up = False
for p in processes:
ret = p.poll()
if ret is None:
up = True
elif ret != 0:
error = True
time.sleep(1)
if error:
for p in processes:
if p.poll() is None:
p.terminate()
exit(1)
except KeyboardInterrupt:
for p in processes:
p.terminate()
raise
except SystemExit:
for p in processes:
p.terminate()
raise
except:
for p in processes:
p.terminate()
raise
if __name__ == "__main__":
main()
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/multiproc.py
|
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# 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 torch
import torch.nn as nn
import numpy as np
def mixup(alpha, data, target):
with torch.no_grad():
bs = data.size(0)
c = np.random.beta(alpha, alpha)
perm = torch.randperm(bs).cuda()
md = c * data + (1 - c) * data[perm, :]
mt = c * target + (1 - c) * target[perm, :]
return md, mt
class MixUpWrapper(object):
def __init__(self, alpha, dataloader):
self.alpha = alpha
self.dataloader = dataloader
def mixup_loader(self, loader):
for input, target in loader:
i, t = mixup(self.alpha, input, target)
yield i, t
def __iter__(self):
return self.mixup_loader(self.dataloader)
def __len__(self):
return len(self.dataloader)
class NLLMultiLabelSmooth(nn.Module):
def __init__(self, smoothing=0.0):
super(NLLMultiLabelSmooth, self).__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
def forward(self, x, target):
if self.training:
x = x.float()
target = target.float()
logprobs = torch.nn.functional.log_softmax(x, dim=-1)
nll_loss = -logprobs * target
nll_loss = nll_loss.sum(-1)
smooth_loss = -logprobs.mean(dim=-1)
loss = self.confidence * nll_loss + self.smoothing * smooth_loss
return loss.mean()
else:
return torch.nn.functional.cross_entropy(x, target)
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/mixup.py
|
import collections
import itertools
import os
import pathlib
import re
import pynvml
from typing import Union
class Device:
# assume nvml returns list of 64 bit ints
_nvml_bit_affinity = 64
_nvml_affinity_elements = (
os.cpu_count() + _nvml_bit_affinity - 1
) // _nvml_bit_affinity
def __init__(self, device_idx):
super().__init__()
self.handle = pynvml.nvmlDeviceGetHandleByIndex(device_idx)
def get_name(self):
return pynvml.nvmlDeviceGetName(self.handle)
def get_uuid(self):
return pynvml.nvmlDeviceGetUUID(self.handle)
def get_cpu_affinity(self):
affinity_string = ""
for j in pynvml.nvmlDeviceGetCpuAffinity(
self.handle, Device._nvml_affinity_elements
):
# assume nvml returns list of 64 bit ints
affinity_string = "{:064b}".format(j) + affinity_string
affinity_list = [int(x) for x in affinity_string]
affinity_list.reverse() # so core 0 is in 0th element of list
ret = [i for i, e in enumerate(affinity_list) if e != 0]
return ret
def get_thread_siblings_list():
"""
Returns a list of 2-element integer tuples representing pairs of
hyperthreading cores.
"""
path = "/sys/devices/system/cpu/cpu*/topology/thread_siblings_list"
thread_siblings_list = []
pattern = re.compile(r"(\d+)\D(\d+)")
for fname in pathlib.Path(path[0]).glob(path[1:]):
with open(fname) as f:
content = f.read().strip()
res = pattern.findall(content)
if res:
pair = tuple(sorted(map(int, res[0])))
thread_siblings_list.append(pair)
thread_siblings_list = list(set(thread_siblings_list))
return thread_siblings_list
def build_thread_siblings_dict(siblings_list):
siblings_dict = {}
for siblings_tuple in siblings_list:
for core in siblings_tuple:
siblings_dict[core] = siblings_tuple
return siblings_dict
def group_list_by_dict(affinity, siblings_dict):
sorted_affinity = sorted(affinity, key=lambda x: siblings_dict.get(x, (x,)))
grouped = itertools.groupby(
sorted_affinity, key=lambda x: siblings_dict.get(x, (x,))
)
grouped_affinity = []
for key, group in grouped:
grouped_affinity.append(tuple(group))
return grouped_affinity
def group_affinity_by_siblings(socket_affinities):
siblings_list = get_thread_siblings_list()
siblings_dict = build_thread_siblings_dict(siblings_list)
grouped_socket_affinities = []
for socket_affinity in socket_affinities:
grouped_socket_affinities.append(
group_list_by_dict(socket_affinity, siblings_dict)
)
return grouped_socket_affinities
def ungroup_affinities(affinities, cores):
ungrouped_affinities = []
for affinity in affinities:
if cores == "all_logical":
ungrouped_affinities.append(list(itertools.chain(*affinity)))
elif cores == "single_logical":
ungrouped_affinities.append([group[0] for group in affinity])
else:
raise RuntimeError("Unknown cores mode")
return ungrouped_affinities
def check_socket_affinities(socket_affinities):
# sets of cores should be either identical or disjoint
for i, j in itertools.product(socket_affinities, socket_affinities):
if not set(i) == set(j) and not set(i).isdisjoint(set(j)):
raise RuntimeError(
f"Sets of cores should be either identical or disjoint, "
f"but got {i} and {j}."
)
def get_socket_affinities(nproc_per_node, exclude_unavailable_cores=True):
devices = [Device(i) for i in range(nproc_per_node)]
socket_affinities = [dev.get_cpu_affinity() for dev in devices]
if exclude_unavailable_cores:
available_cores = os.sched_getaffinity(0)
socket_affinities = [
list(set(affinity) & available_cores) for affinity in socket_affinities
]
check_socket_affinities(socket_affinities)
return socket_affinities
def get_grouped_socket_affinities(nproc_per_node, exclude_unavailable_cores=True):
socket_affinities = get_socket_affinities(nproc_per_node, exclude_unavailable_cores)
grouped_socket_affinities = group_affinity_by_siblings(socket_affinities)
return grouped_socket_affinities
def set_socket_affinity(gpu_id, nproc_per_node, cores):
"""
The process is assigned with all available physical CPU cores from the CPU
socket connected to the GPU with a given id.
Args:
gpu_id: index of a GPU
nproc_per_node: number of processes per node
cores: 'all_logical' or 'single_logical'
"""
grouped_socket_affinities = get_grouped_socket_affinities(nproc_per_node)
ungrouped_affinities = ungroup_affinities(grouped_socket_affinities, cores)
os.sched_setaffinity(0, ungrouped_affinities[gpu_id])
def set_socket_single_affinity(gpu_id, nproc_per_node, cores):
"""
The process is assigned with the first available physical CPU core from the
list of all CPU physical cores from the CPU socket connected to the GPU with
a given id.
Args:
gpu_id: index of a GPU
nproc_per_node: number of processes per node
cores: 'all_logical' or 'single_logical'
"""
grouped_socket_affinities = get_grouped_socket_affinities(nproc_per_node)
single_grouped_socket_affinities = [
group[:1] for group in grouped_socket_affinities
]
ungrouped_affinities = ungroup_affinities(single_grouped_socket_affinities, cores)
os.sched_setaffinity(0, ungrouped_affinities[gpu_id])
def set_socket_single_unique_affinity(gpu_id, nproc_per_node, cores):
"""
The process is assigned with a single unique available physical CPU core
from the list of all CPU cores from the CPU socket connected to the GPU with
a given id.
Args:
gpu_id: index of a GPU
nproc_per_node: number of processes per node
cores: 'all_logical' or 'single_logical'
"""
grouped_socket_affinities = get_grouped_socket_affinities(nproc_per_node)
affinities = []
assigned_groups = set()
for grouped_socket_affinity in grouped_socket_affinities:
for group in grouped_socket_affinity:
if group not in assigned_groups:
affinities.append([group])
assigned_groups.add(group)
break
ungrouped_affinities = ungroup_affinities(affinities, cores)
os.sched_setaffinity(0, ungrouped_affinities[gpu_id])
def set_socket_unique_affinity(gpu_id, nproc_per_node, cores, mode, balanced=True):
"""
The process is assigned with a unique subset of available physical CPU
cores from the CPU socket connected to a GPU with a given id.
Assignment automatically includes hyperthreading siblings (if siblings are
available).
Args:
gpu_id: index of a GPU
nproc_per_node: number of processes per node
cores: 'all_logical' or 'single_logical'
mode: 'contiguous' or 'interleaved'
balanced: assign an equal number of physical cores to each process,
"""
grouped_socket_affinities = get_grouped_socket_affinities(nproc_per_node)
grouped_socket_affinities_to_device_ids = collections.defaultdict(list)
for idx, grouped_socket_affinity in enumerate(grouped_socket_affinities):
grouped_socket_affinities_to_device_ids[tuple(grouped_socket_affinity)].append(
idx
)
# compute minimal number of physical cores per GPU across all GPUs and
# sockets, code assigns this number of cores per GPU if balanced == True
min_physical_cores_per_gpu = min(
[
len(cores) // len(gpus)
for cores, gpus in grouped_socket_affinities_to_device_ids.items()
]
)
grouped_unique_affinities = [None] * nproc_per_node
for (
grouped_socket_affinity,
device_ids,
) in grouped_socket_affinities_to_device_ids.items():
devices_per_group = len(device_ids)
if balanced:
cores_per_device = min_physical_cores_per_gpu
grouped_socket_affinity = grouped_socket_affinity[
: devices_per_group * min_physical_cores_per_gpu
]
else:
cores_per_device = len(grouped_socket_affinity) // devices_per_group
for socket_subgroup_id, device_id in enumerate(device_ids):
# In theory there should be no difference in performance between
# 'interleaved' and 'contiguous' pattern on Intel-based DGX-1,
# but 'contiguous' should be better for DGX A100 because on AMD
# Rome 4 consecutive cores are sharing L3 cache.
# TODO: code doesn't attempt to automatically detect layout of
# L3 cache, also external environment may already exclude some
# cores, this code makes no attempt to detect it and to align
# mapping to multiples of 4.
if mode == "interleaved":
unique_grouped_affinity = list(
grouped_socket_affinity[socket_subgroup_id::devices_per_group]
)
elif mode == "contiguous":
unique_grouped_affinity = list(
grouped_socket_affinity[
socket_subgroup_id
* cores_per_device : (socket_subgroup_id + 1)
* cores_per_device
]
)
else:
raise RuntimeError("Unknown set_socket_unique_affinity mode")
grouped_unique_affinities[device_id] = unique_grouped_affinity
ungrouped_affinities = ungroup_affinities(grouped_unique_affinities, cores)
os.sched_setaffinity(0, ungrouped_affinities[gpu_id])
from enum import Enum, auto
class AffinityMode(Enum):
none = auto()
socket = auto()
socket_single = auto()
socket_single_unique = auto()
socket_unique_interleaved = auto()
socket_unique_contiguous = auto()
def set_affinity(
gpu_id,
nproc_per_node=None,
*,
mode: Union[str, AffinityMode] = AffinityMode.socket_unique_contiguous,
cores="all_logical",
balanced=True,
):
"""
The process is assigned with a proper CPU affinity that matches CPU-GPU
hardware architecture on a given platform. Usually, it improves and
stabilizes the performance of deep learning training workloads.
This function assumes that the workload runs in multi-process single-device
mode (there are multiple training processes, and each process is running on
a single GPU). This is typical for multi-GPU data-parallel training
workloads (e.g., using `torch.nn.parallel.DistributedDataParallel`).
Available affinity modes:
* 'socket' - the process is assigned with all available physical CPU cores
from the CPU socket connected to the GPU with a given id.
* 'socket_single' - the process is assigned with the first available
physical CPU core from the list of all CPU cores from the CPU socket
connected to the GPU with a given id (multiple GPUs could be assigned with
the same CPU core).
* 'socket_single_unique' - the process is assigned with a single unique
available physical CPU core from the list of all CPU cores from the CPU
socket connected to the GPU with a given id.
* 'socket_unique_interleaved' - the process is assigned with a unique
subset of available physical CPU cores from the CPU socket connected to a
GPU with a given id, cores are assigned with interleaved indexing pattern
* 'socket_unique_contiguous' - (the default) the process is assigned with a
unique subset of available physical CPU cores from the CPU socket connected
to a GPU with a given id, cores are assigned with contiguous indexing
pattern
Available "cores" modes:
* 'all_logical' - assigns the process with all logical cores associated with
a given corresponding physical core (i.e., automatically includes all
available hyperthreading siblings)
* 'single_logical' - assigns the process with only one logical core
associated with a given corresponding physical core (i.e., excludes
hyperthreading siblings)
'socket_unique_contiguous' is the recommended mode for deep learning
training workloads on NVIDIA DGX machines.
Args:
gpu_id: integer index of a GPU, value from 0 to 'nproc_per_node' - 1
nproc_per_node: number of processes per node
mode: affinity mode
balanced: assign an equal number of physical cores to each process,
affects only 'socket_unique_interleaved' and
'socket_unique_contiguous' affinity modes
cores: 'all_logical' or 'single_logical'
Returns a set of logical CPU cores on which the process is eligible to run.
Example:
import argparse
import os
import gpu_affinity
import torch
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--local_rank',
type=int,
default=os.getenv('LOCAL_RANK', 0),
)
args = parser.parse_args()
nproc_per_node = torch.cuda.device_count()
affinity = gpu_affinity.set_affinity(args.local_rank, nproc_per_node)
print(f'{args.local_rank}: core affinity: {affinity}')
if __name__ == "__main__":
main()
Launch the example with:
python -m torch.distributed.launch --nproc_per_node <#GPUs> example.py
WARNING: On DGX A100, only half of the CPU cores have direct access to GPUs.
This function restricts execution only to the CPU cores directly connected
to GPUs, so on DGX A100, it will limit the code to half of the CPU cores and
half of CPU memory bandwidth (which may be fine for many DL models).
WARNING: Intel's OpenMP implementation resets affinity on the first call to
an OpenMP function after a fork. It's recommended to run with env variable:
`KMP_AFFINITY=disabled` if the affinity set by gpu_affinity should be
preserved after a fork (e.g. in PyTorch DataLoader workers).
"""
if not isinstance(mode, AffinityMode):
mode = AffinityMode[mode]
pynvml.nvmlInit()
if nproc_per_node is None:
nproc_per_node = pynvml.nvmlDeviceGetCount()
if mode == AffinityMode.none:
pass
elif mode == AffinityMode.socket:
set_socket_affinity(gpu_id, nproc_per_node, cores)
elif mode == AffinityMode.socket_single:
set_socket_single_affinity(gpu_id, nproc_per_node, cores)
elif mode == AffinityMode.socket_single_unique:
set_socket_single_unique_affinity(gpu_id, nproc_per_node, cores)
elif mode == AffinityMode.socket_unique_interleaved:
set_socket_unique_affinity(
gpu_id, nproc_per_node, cores, "interleaved", balanced
)
elif mode == AffinityMode.socket_unique_contiguous:
set_socket_unique_affinity(
gpu_id, nproc_per_node, cores, "contiguous", balanced
)
else:
raise RuntimeError("Unknown affinity mode")
affinity = os.sched_getaffinity(0)
return affinity
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/gpu_affinity.py
|
from tqdm import tqdm
import torch
import contextlib
import time
import logging
from pytorch_quantization import quant_modules
from pytorch_quantization import nn as quant_nn
from pytorch_quantization import calib
from pytorch_quantization.tensor_quant import QuantDescriptor
from . import logger as log
from .utils import calc_ips
import dllogger
initialize = quant_modules.initialize
deactivate = quant_modules.deactivate
IPS_METADATA = {"unit": "img/s", "format": ":.2f"}
TIME_METADATA = {"unit": "s", "format": ":.5f"}
def select_default_calib_method(calib_method='histogram'):
"""Set up selected calibration method in whole network"""
quant_desc_input = QuantDescriptor(calib_method=calib_method)
quant_nn.QuantConv1d.set_default_quant_desc_input(quant_desc_input)
quant_nn.QuantConv2d.set_default_quant_desc_input(quant_desc_input)
quant_nn.QuantLinear.set_default_quant_desc_input(quant_desc_input)
quant_nn.QuantAdaptiveAvgPool2d.set_default_quant_desc_input(quant_desc_input)
def quantization_setup(calib_method='histogram'):
"""Change network into quantized version "automatically" and selects histogram as default quantization method"""
select_default_calib_method(calib_method)
initialize()
def disable_calibration(model):
"""Disables calibration in whole network. Should be run always before running interference."""
for name, module in model.named_modules():
if isinstance(module, quant_nn.TensorQuantizer):
if module._calibrator is not None:
module.enable_quant()
module.disable_calib()
else:
module.enable()
def collect_stats(model, data_loader, logger, num_batches):
"""Feed data to the network and collect statistic"""
if logger is not None:
logger.register_metric(
f"calib.total_ips",
log.PERF_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=IPS_METADATA,
)
logger.register_metric(
f"calib.data_time",
log.PERF_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=TIME_METADATA,
)
logger.register_metric(
f"calib.compute_latency",
log.PERF_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=TIME_METADATA,
)
# Enable calibrators
data_iter = enumerate(data_loader)
if logger is not None:
data_iter = logger.iteration_generator_wrapper(data_iter, mode='calib')
for name, module in model.named_modules():
if isinstance(module, quant_nn.TensorQuantizer):
if module._calibrator is not None:
module.disable_quant()
module.enable_calib()
else:
module.disable()
end = time.time()
if logger is not None:
logger.start_calibration()
for i, (image, _) in data_iter:
bs = image.size(0)
data_time = time.time() - end
model(image.cuda())
it_time = time.time() - end
if logger is not None:
logger.log_metric(f"calib.total_ips", calc_ips(bs, it_time))
logger.log_metric(f"calib.data_time", data_time)
logger.log_metric(f"calib.compute_latency", it_time - data_time)
if i >= num_batches:
time.sleep(5)
break
end = time.time()
if logger is not None:
logger.end_calibration()
logging.disable(logging.WARNING)
disable_calibration(model)
def compute_amax(model, **kwargs):
"""Loads statistics of data and calculates quantization parameters in whole network"""
for name, module in model.named_modules():
if isinstance(module, quant_nn.TensorQuantizer) and module._calibrator is not None:
if isinstance(module._calibrator, calib.MaxCalibrator):
module.load_calib_amax()
else:
module.load_calib_amax(**kwargs)
model.cuda()
def calibrate(model, train_loader, logger, calib_iter=1, percentile=99.99):
"""Calibrates whole network i.e. gathers data for quantization and calculates quantization parameters"""
model.eval()
with torch.no_grad():
collect_stats(model, train_loader, logger, num_batches=calib_iter)
compute_amax(model, method="percentile", percentile=percentile)
logging.disable(logging.NOTSET)
@contextlib.contextmanager
def switch_on_quantization(do_quantization=True):
"""Context manager for quantization activation"""
if do_quantization:
initialize()
try:
yield
finally:
if do_quantization:
deactivate()
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/quantization.py
|
# Copyright (c) 2018-2019, NVIDIA CORPORATION
# Copyright (c) 2017- Facebook, Inc
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import torch
import numpy as np
from PIL import Image
from functools import partial
from image_classification.autoaugment import AutoaugmentImageNetPolicy
DATA_BACKEND_CHOICES = ["pytorch", "synthetic"]
try:
from nvidia.dali.plugin.pytorch import DALIClassificationIterator
import nvidia.dali.types as types
from image_classification.dali import training_pipe, validation_pipe
DATA_BACKEND_CHOICES.append("dali")
except ImportError as e:
print(
"Please install DALI from https://www.github.com/NVIDIA/DALI to run this example."
)
import torchvision.datasets as datasets
import torchvision.transforms as transforms
def load_jpeg_from_file(path, cuda=True):
img_transforms = transforms.Compose(
[transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor()]
)
img = img_transforms(Image.open(path))
with torch.no_grad():
# mean and std are not multiplied by 255 as they are in training script
# torch dataloader reads data into bytes whereas loading directly
# through PIL creates a tensor with floats in [0,1] range
mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
if cuda:
mean = mean.cuda()
std = std.cuda()
img = img.cuda()
img = img.float()
input = img.unsqueeze(0).sub_(mean).div_(std)
return input
class DALIWrapper(object):
def gen_wrapper(dalipipeline, num_classes, one_hot, memory_format):
for data in dalipipeline:
if memory_format == torch.channels_last:
# If we requested the data in channels_last form, utilize the fact that DALI
# can return it as NHWC. The network expects NCHW shape with NHWC internal memory,
# so we can keep the memory and just create a view with appropriate shape and
# strides reflacting that memory layouyt
shape = data[0]["data"].shape
stride = data[0]["data"].stride()
# permute shape and stride from NHWC to NCHW
def nhwc_to_nchw(t):
return t[0], t[3], t[1], t[2]
input = torch.as_strided(data[0]["data"], size=nhwc_to_nchw(shape),
stride=nhwc_to_nchw(stride))
else:
input = data[0]["data"].contiguous(memory_format=memory_format)
target = torch.reshape(data[0]["label"], [-1]).cuda().long()
if one_hot:
target = expand(num_classes, torch.float, target)
yield input, target
dalipipeline.reset()
def __init__(self, dalipipeline, num_classes, one_hot, memory_format):
self.dalipipeline = dalipipeline
self.num_classes = num_classes
self.one_hot = one_hot
self.memory_format = memory_format
def __iter__(self):
return DALIWrapper.gen_wrapper(
self.dalipipeline, self.num_classes, self.one_hot, self.memory_format
)
def get_dali_train_loader(dali_device="gpu"):
def gdtl(
data_path,
image_size,
batch_size,
num_classes,
one_hot,
interpolation="bilinear",
augmentation="disabled",
start_epoch=0,
workers=5,
_worker_init_fn=None,
memory_format=torch.contiguous_format,
**kwargs,
):
if torch.distributed.is_initialized():
rank = torch.distributed.get_rank()
world_size = torch.distributed.get_world_size()
else:
rank = 0
world_size = 1
interpolation = {
"bicubic": types.INTERP_CUBIC,
"bilinear": types.INTERP_LINEAR,
"triangular": types.INTERP_TRIANGULAR,
}[interpolation]
output_layout = "HWC" if memory_format == torch.channels_last else "CHW"
traindir = os.path.join(data_path, "train")
pipeline_kwargs = {
"batch_size" : batch_size,
"num_threads" : workers,
"device_id" : rank % torch.cuda.device_count(),
"seed": 12 + rank % torch.cuda.device_count(),
}
pipe = training_pipe(data_dir=traindir, interpolation=interpolation, image_size=image_size,
output_layout=output_layout, automatic_augmentation=augmentation,
dali_device=dali_device, rank=rank, world_size=world_size,
**pipeline_kwargs)
pipe.build()
train_loader = DALIClassificationIterator(
pipe, reader_name="Reader", fill_last_batch=False
)
return (
DALIWrapper(train_loader, num_classes, one_hot, memory_format),
int(pipe.epoch_size("Reader") / (world_size * batch_size)),
)
return gdtl
def get_dali_val_loader():
def gdvl(
data_path,
image_size,
batch_size,
num_classes,
one_hot,
interpolation="bilinear",
crop_padding=32,
workers=5,
_worker_init_fn=None,
memory_format=torch.contiguous_format,
**kwargs,
):
if torch.distributed.is_initialized():
rank = torch.distributed.get_rank()
world_size = torch.distributed.get_world_size()
else:
rank = 0
world_size = 1
interpolation = {
"bicubic": types.INTERP_CUBIC,
"bilinear": types.INTERP_LINEAR,
"triangular": types.INTERP_TRIANGULAR,
}[interpolation]
output_layout = "HWC" if memory_format == torch.channels_last else "CHW"
valdir = os.path.join(data_path, "val")
pipeline_kwargs = {
"batch_size" : batch_size,
"num_threads" : workers,
"device_id" : rank % torch.cuda.device_count(),
"seed": 12 + rank % torch.cuda.device_count(),
}
pipe = validation_pipe(data_dir=valdir, interpolation=interpolation,
image_size=image_size + crop_padding, image_crop=image_size,
output_layout=output_layout, **pipeline_kwargs)
pipe.build()
val_loader = DALIClassificationIterator(
pipe, reader_name="Reader", fill_last_batch=False
)
return (
DALIWrapper(val_loader, num_classes, one_hot, memory_format),
int(pipe.epoch_size("Reader") / (world_size * batch_size)),
)
return gdvl
def fast_collate(memory_format, batch):
imgs = [img[0] for img in batch]
targets = torch.tensor([target[1] for target in batch], dtype=torch.int64)
w = imgs[0].size[0]
h = imgs[0].size[1]
tensor = torch.zeros((len(imgs), 3, h, w), dtype=torch.uint8).contiguous(
memory_format=memory_format
)
for i, img in enumerate(imgs):
nump_array = np.asarray(img, dtype=np.uint8)
if nump_array.ndim < 3:
nump_array = np.expand_dims(nump_array, axis=-1)
nump_array = np.rollaxis(nump_array, 2)
tensor[i] += torch.from_numpy(nump_array.copy())
return tensor, targets
def expand(num_classes, dtype, tensor):
e = torch.zeros(
tensor.size(0), num_classes, dtype=dtype, device=torch.device("cuda")
)
e = e.scatter(1, tensor.unsqueeze(1), 1.0)
return e
class PrefetchedWrapper(object):
def prefetched_loader(loader, num_classes, one_hot):
mean = (
torch.tensor([0.485 * 255, 0.456 * 255, 0.406 * 255])
.cuda()
.view(1, 3, 1, 1)
)
std = (
torch.tensor([0.229 * 255, 0.224 * 255, 0.225 * 255])
.cuda()
.view(1, 3, 1, 1)
)
stream = torch.cuda.Stream()
first = True
for next_input, next_target in loader:
with torch.cuda.stream(stream):
next_input = next_input.cuda(non_blocking=True)
next_target = next_target.cuda(non_blocking=True)
next_input = next_input.float()
if one_hot:
next_target = expand(num_classes, torch.float, next_target)
next_input = next_input.sub_(mean).div_(std)
if not first:
yield input, target
else:
first = False
torch.cuda.current_stream().wait_stream(stream)
input = next_input
target = next_target
yield input, target
def __init__(self, dataloader, start_epoch, num_classes, one_hot):
self.dataloader = dataloader
self.epoch = start_epoch
self.one_hot = one_hot
self.num_classes = num_classes
def __iter__(self):
if self.dataloader.sampler is not None and isinstance(
self.dataloader.sampler, torch.utils.data.distributed.DistributedSampler
):
self.dataloader.sampler.set_epoch(self.epoch)
self.epoch += 1
return PrefetchedWrapper.prefetched_loader(
self.dataloader, self.num_classes, self.one_hot
)
def __len__(self):
return len(self.dataloader)
def get_pytorch_train_loader(
data_path,
image_size,
batch_size,
num_classes,
one_hot,
interpolation="bilinear",
augmentation=None,
start_epoch=0,
workers=5,
_worker_init_fn=None,
prefetch_factor=2,
memory_format=torch.contiguous_format,
):
interpolation = {"bicubic": Image.BICUBIC, "bilinear": Image.BILINEAR}[
interpolation
]
traindir = os.path.join(data_path, "train")
transforms_list = [
transforms.RandomResizedCrop(image_size, interpolation=interpolation),
transforms.RandomHorizontalFlip(),
]
if augmentation == "disabled":
pass
elif augmentation == "autoaugment":
transforms_list.append(AutoaugmentImageNetPolicy())
else:
raise NotImplementedError(f"Automatic augmentation: '{augmentation}' is not supported"
" for PyTorch data loader.")
train_dataset = datasets.ImageFolder(traindir, transforms.Compose(transforms_list))
if torch.distributed.is_initialized():
train_sampler = torch.utils.data.distributed.DistributedSampler(
train_dataset, shuffle=True
)
else:
train_sampler = None
train_loader = torch.utils.data.DataLoader(
train_dataset,
sampler=train_sampler,
batch_size=batch_size,
shuffle=(train_sampler is None),
num_workers=workers,
worker_init_fn=_worker_init_fn,
pin_memory=True,
collate_fn=partial(fast_collate, memory_format),
drop_last=True,
persistent_workers=True,
prefetch_factor=prefetch_factor,
)
return (
PrefetchedWrapper(train_loader, start_epoch, num_classes, one_hot),
len(train_loader),
)
def get_pytorch_val_loader(
data_path,
image_size,
batch_size,
num_classes,
one_hot,
interpolation="bilinear",
workers=5,
_worker_init_fn=None,
crop_padding=32,
memory_format=torch.contiguous_format,
prefetch_factor=2,
):
interpolation = {"bicubic": Image.BICUBIC, "bilinear": Image.BILINEAR}[
interpolation
]
valdir = os.path.join(data_path, "val")
val_dataset = datasets.ImageFolder(
valdir,
transforms.Compose(
[
transforms.Resize(
image_size + crop_padding, interpolation=interpolation
),
transforms.CenterCrop(image_size),
]
),
)
if torch.distributed.is_initialized():
val_sampler = torch.utils.data.distributed.DistributedSampler(
val_dataset, shuffle=False
)
else:
val_sampler = None
val_loader = torch.utils.data.DataLoader(
val_dataset,
sampler=val_sampler,
batch_size=batch_size,
shuffle=(val_sampler is None),
num_workers=workers,
worker_init_fn=_worker_init_fn,
pin_memory=True,
collate_fn=partial(fast_collate, memory_format),
drop_last=False,
persistent_workers=True,
prefetch_factor=prefetch_factor,
)
return PrefetchedWrapper(val_loader, 0, num_classes, one_hot), len(val_loader)
class SynteticDataLoader(object):
def __init__(
self,
batch_size,
num_classes,
num_channels,
height,
width,
one_hot,
memory_format=torch.contiguous_format,
):
input_data = (
torch.randn(batch_size, num_channels, height, width)
.contiguous(memory_format=memory_format)
.cuda()
.normal_(0, 1.0)
)
if one_hot:
input_target = torch.empty(batch_size, num_classes).cuda()
input_target[:, 0] = 1.0
else:
input_target = torch.randint(0, num_classes, (batch_size,))
input_target = input_target.cuda()
self.input_data = input_data
self.input_target = input_target
def __iter__(self):
while True:
yield self.input_data, self.input_target
def get_synthetic_loader(
data_path,
image_size,
batch_size,
num_classes,
one_hot,
interpolation=None,
augmentation=None,
start_epoch=0,
workers=None,
_worker_init_fn=None,
memory_format=torch.contiguous_format,
**kwargs,
):
return (
SynteticDataLoader(
batch_size,
num_classes,
3,
image_size,
image_size,
one_hot,
memory_format=memory_format,
),
-1,
)
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/dataloaders.py
|
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# 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 . import logger
#from . import dataloaders
#from . import training
#from . import utils
#from . import mixup
#from . import smoothing
from . import models
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/__init__.py
|
# Copyright (c) 2018-2019, NVIDIA CORPORATION
# Copyright (c) 2017- Facebook, Inc
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from collections import OrderedDict
from numbers import Number
import dllogger
import numpy as np
def format_step(step):
if isinstance(step, str):
return step
s = ""
if len(step) > 0:
if isinstance(step[0], Number):
s += "Epoch: {} ".format(step[0])
else:
s += "{} ".format(step[0])
if len(step) > 1:
s += "Iteration: {} ".format(step[1])
if len(step) > 2:
s += "Validation Iteration: {} ".format(step[2])
if len(step) == 0:
s = "Summary:"
return s
PERF_METER = lambda: Meter(AverageMeter(), AverageMeter(), AverageMeter())
LOSS_METER = lambda: Meter(AverageMeter(), AverageMeter(), MinMeter())
ACC_METER = lambda: Meter(AverageMeter(), AverageMeter(), MaxMeter())
LR_METER = lambda: Meter(LastMeter(), LastMeter(), LastMeter())
LAT_100 = lambda: Meter(QuantileMeter(1), QuantileMeter(1), QuantileMeter(1))
LAT_99 = lambda: Meter(QuantileMeter(0.99), QuantileMeter(0.99), QuantileMeter(0.99))
LAT_95 = lambda: Meter(QuantileMeter(0.95), QuantileMeter(0.95), QuantileMeter(0.95))
class Meter(object):
def __init__(self, iteration_aggregator, epoch_aggregator, run_aggregator):
self.run_aggregator = run_aggregator
self.epoch_aggregator = epoch_aggregator
self.iteration_aggregator = iteration_aggregator
def record(self, val, n=1):
self.iteration_aggregator.record(val, n=n)
def get_iteration(self):
v, n = self.iteration_aggregator.get_val()
return v
def reset_iteration(self):
v, n = self.iteration_aggregator.get_data()
self.iteration_aggregator.reset()
if v is not None:
self.epoch_aggregator.record(v, n=n)
def get_epoch(self):
v, n = self.epoch_aggregator.get_val()
return v
def reset_epoch(self):
v, n = self.epoch_aggregator.get_data()
self.epoch_aggregator.reset()
if v is not None:
self.run_aggregator.record(v, n=n)
def get_run(self):
v, n = self.run_aggregator.get_val()
return v
def reset_run(self):
self.run_aggregator.reset()
class QuantileMeter(object):
def __init__(self, q):
self.q = q
self.reset()
def reset(self):
self.vals = []
self.n = 0
def record(self, val, n=1):
if isinstance(val, list):
self.vals += val
self.n += len(val)
else:
self.vals += [val] * n
self.n += n
def get_val(self):
if not self.vals:
return None, self.n
return np.quantile(self.vals, self.q, interpolation="nearest"), self.n
def get_data(self):
return self.vals, self.n
class MaxMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.max = None
self.n = 0
def record(self, val, n=1):
if self.max is None:
self.max = val
else:
self.max = max(self.max, val)
self.n = n
def get_val(self):
return self.max, self.n
def get_data(self):
return self.max, self.n
class MinMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.min = None
self.n = 0
def record(self, val, n=1):
if self.min is None:
self.min = val
else:
self.min = max(self.min, val)
self.n = n
def get_val(self):
return self.min, self.n
def get_data(self):
return self.min, self.n
class LastMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.last = None
self.n = 0
def record(self, val, n=1):
self.last = val
self.n = n
def get_val(self):
return self.last, self.n
def get_data(self):
return self.last, self.n
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.n = 0
self.val = 0
def record(self, val, n=1):
self.n += n
self.val += val * n
def get_val(self):
if self.n == 0:
return None, 0
return self.val / self.n, self.n
def get_data(self):
if self.n == 0:
return None, 0
return self.val / self.n, self.n
class Logger(object):
def __init__(self, print_interval, backends, start_epoch=-1, verbose=False):
self.epoch = start_epoch
self.iteration = -1
self.val_iteration = -1
self.calib_iteration = -1
self.metrics = OrderedDict()
self.backends = backends
self.print_interval = print_interval
self.verbose = verbose
dllogger.init(backends)
def log_parameter(self, data, verbosity=0):
dllogger.log(step="PARAMETER", data=data, verbosity=verbosity)
def register_metric(self, metric_name, meter, verbosity=0, metadata={}):
if self.verbose:
print("Registering metric: {}".format(metric_name))
self.metrics[metric_name] = {"meter": meter, "level": verbosity}
dllogger.metadata(metric_name, metadata)
def log_metric(self, metric_name, val, n=1):
self.metrics[metric_name]["meter"].record(val, n=n)
def start_iteration(self, mode="train"):
if mode == "val":
self.val_iteration += 1
elif mode == "train":
self.iteration += 1
elif mode == "calib":
self.calib_iteration += 1
def end_iteration(self, mode="train"):
if mode == "val":
it = self.val_iteration
elif mode == "train":
it = self.iteration
elif mode == "calib":
it = self.calib_iteration
if it % self.print_interval == 0 or mode == "calib":
metrics = {n: m for n, m in self.metrics.items() if n.startswith(mode)}
if mode == "train":
step = (self.epoch, self.iteration)
elif mode == "val":
step = (self.epoch, self.iteration, self.val_iteration)
elif mode == "calib":
step = ("Calibration", self.calib_iteration)
verbositys = {m["level"] for _, m in metrics.items()}
for ll in verbositys:
llm = {n: m for n, m in metrics.items() if m["level"] == ll}
dllogger.log(
step=step,
data={n: m["meter"].get_iteration() for n, m in llm.items()},
verbosity=ll,
)
for n, m in metrics.items():
m["meter"].reset_iteration()
dllogger.flush()
def start_epoch(self):
self.epoch += 1
self.iteration = 0
self.val_iteration = 0
for n, m in self.metrics.items():
if not n.startswith("calib"):
m["meter"].reset_epoch()
def end_epoch(self):
for n, m in self.metrics.items():
if not n.startswith("calib"):
m["meter"].reset_iteration()
verbositys = {m["level"] for _, m in self.metrics.items()}
for ll in verbositys:
llm = {n: m for n, m in self.metrics.items() if m["level"] == ll}
dllogger.log(
step=(self.epoch,),
data={n: m["meter"].get_epoch() for n, m in llm.items()},
)
def start_calibration(self):
self.calib_iteration = 0
for n, m in self.metrics.items():
if n.startswith("calib"):
m["meter"].reset_epoch()
def end_calibration(self):
for n, m in self.metrics.items():
if n.startswith("calib"):
m["meter"].reset_iteration()
def end(self):
for n, m in self.metrics.items():
m["meter"].reset_epoch()
verbositys = {m["level"] for _, m in self.metrics.items()}
for ll in verbositys:
llm = {n: m for n, m in self.metrics.items() if m["level"] == ll}
dllogger.log(
step=tuple(), data={n: m["meter"].get_run() for n, m in llm.items()}
)
for n, m in self.metrics.items():
m["meter"].reset_epoch()
dllogger.flush()
def iteration_generator_wrapper(self, gen, mode="train"):
for g in gen:
self.start_iteration(mode=mode)
yield g
self.end_iteration(mode=mode)
def epoch_generator_wrapper(self, gen):
for g in gen:
self.start_epoch()
yield g
self.end_epoch()
class Metrics:
ACC_METADATA = {"unit": "%", "format": ":.2f"}
IPS_METADATA = {"unit": "images/s", "format": ":.2f"}
TIME_METADATA = {"unit": "s", "format": ":.5f"}
LOSS_METADATA = {"unit": None, "format": ":.5f"}
LR_METADATA = {"unit": None, "format": ":.5f"}
def __init__(self, logger):
self.logger = logger
self.map = {}
def log(self, **kwargs):
if self.logger is None:
return
for k, v in kwargs.items():
tks = self.map.get(k, [k])
for tk in tks:
if isinstance(v, tuple):
self.logger.log_metric(tk, v[0], v[1])
else:
self.logger.log_metric(tk, v)
class TrainingMetrics(Metrics):
def __init__(self, logger):
super().__init__(logger)
if self.logger is not None:
self.map = {
"loss": ["train.loss"],
"compute_ips": ["train.compute_ips"],
"total_ips": ["train.total_ips"],
"data_time": ["train.data_time"],
"compute_time": ["train.compute_time"],
"lr": ["train.lr"],
"grad_scale": ["train.grad_scale"],
}
logger.register_metric(
"train.loss",
LOSS_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=Metrics.LOSS_METADATA,
)
logger.register_metric(
"train.compute_ips",
PERF_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=Metrics.IPS_METADATA,
)
logger.register_metric(
"train.total_ips",
PERF_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=Metrics.IPS_METADATA,
)
logger.register_metric(
"train.data_time",
PERF_METER(),
verbosity=dllogger.Verbosity.VERBOSE,
metadata=Metrics.TIME_METADATA,
)
logger.register_metric(
"train.compute_time",
PERF_METER(),
verbosity=dllogger.Verbosity.VERBOSE,
metadata=Metrics.TIME_METADATA,
)
logger.register_metric(
"train.lr",
LR_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
)
logger.register_metric(
"train.grad_scale",
PERF_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=Metrics.LOSS_METADATA,
)
class ValidationMetrics(Metrics):
def __init__(self, logger, prefix, topk):
super().__init__(logger)
if self.logger is not None:
self.map = {
"loss": [f"{prefix}.loss"],
"top1": [f"{prefix}.top1"],
f"top{topk}": [f"{prefix}.top{topk}"],
"compute_ips": [f"{prefix}.compute_ips"],
"total_ips": [f"{prefix}.total_ips"],
"data_time": [f"{prefix}.data_time"],
"compute_time": [
f"{prefix}.compute_latency",
f"{prefix}.compute_latency_at100",
f"{prefix}.compute_latency_at99",
f"{prefix}.compute_latency_at95",
],
}
logger.register_metric(
f"{prefix}.top1",
ACC_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=Metrics.ACC_METADATA,
)
logger.register_metric(
f"{prefix}.top{topk}",
ACC_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=Metrics.ACC_METADATA,
)
logger.register_metric(
f"{prefix}.loss",
LOSS_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=Metrics.LOSS_METADATA,
)
logger.register_metric(
f"{prefix}.compute_ips",
PERF_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=Metrics.IPS_METADATA,
)
logger.register_metric(
f"{prefix}.total_ips",
PERF_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=Metrics.IPS_METADATA,
)
logger.register_metric(
f"{prefix}.data_time",
PERF_METER(),
verbosity=dllogger.Verbosity.VERBOSE,
metadata=Metrics.TIME_METADATA,
)
logger.register_metric(
f"{prefix}.compute_latency",
PERF_METER(),
verbosity=dllogger.Verbosity.DEFAULT,
metadata=Metrics.TIME_METADATA,
)
logger.register_metric(
f"{prefix}.compute_latency_at100",
LAT_100(),
verbosity=dllogger.Verbosity.VERBOSE,
metadata=Metrics.TIME_METADATA,
)
logger.register_metric(
f"{prefix}.compute_latency_at99",
LAT_99(),
verbosity=dllogger.Verbosity.VERBOSE,
metadata=Metrics.TIME_METADATA,
)
logger.register_metric(
f"{prefix}.compute_latency_at95",
LAT_95(),
verbosity=dllogger.Verbosity.VERBOSE,
metadata=Metrics.TIME_METADATA,
)
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/logger.py
|
# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. 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 nvidia.dali import fn
from nvidia.dali import types
from nvidia.dali.pipeline.experimental import pipeline_def
from nvidia.dali.auto_aug import auto_augment, trivial_augment
@pipeline_def(enable_conditionals=True)
def training_pipe(data_dir, interpolation, image_size, output_layout, automatic_augmentation,
dali_device="gpu", rank=0, world_size=1):
rng = fn.random.coin_flip(probability=0.5)
jpegs, labels = fn.readers.file(name="Reader", file_root=data_dir, shard_id=rank,
num_shards=world_size, random_shuffle=True, pad_last_batch=True)
if dali_device == "gpu":
decoder_device = "mixed"
resize_device = "gpu"
else:
decoder_device = "cpu"
resize_device = "cpu"
# This padding sets the size of the internal nvJPEG buffers to be able to handle all images
# from full-sized ImageNet without additional reallocations
images = fn.decoders.image_random_crop(jpegs, device=decoder_device, output_type=types.RGB,
device_memory_padding=211025920,
host_memory_padding=140544512,
random_aspect_ratio=[0.75, 4.0 / 3.0],
random_area=[0.08, 1.0])
images = fn.resize(images, device=resize_device, size=[image_size, image_size],
interp_type=interpolation, antialias=False)
# Make sure that from this point we are processing on GPU regardless of dali_device parameter
images = images.gpu()
images = fn.flip(images, horizontal=rng)
# Based on the specification, apply the automatic augmentation policy. Note, that from the point
# of Pipeline definition, this `if` statement relies on static scalar parameter, so it is
# evaluated exactly once during build - we either include automatic augmentations or not.
# We pass the shape of the image after the resize so the translate operations are done
# relative to the image size.
if automatic_augmentation == "autoaugment":
output = auto_augment.auto_augment_image_net(images, shape=[image_size, image_size])
elif automatic_augmentation == "trivialaugment":
output = trivial_augment.trivial_augment_wide(images, shape=[image_size, image_size])
else:
output = images
output = fn.crop_mirror_normalize(output, dtype=types.FLOAT, output_layout=output_layout,
crop=(image_size, image_size),
mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
return output, labels
@pipeline_def
def validation_pipe(data_dir, interpolation, image_size, image_crop, output_layout, rank=0,
world_size=1):
jpegs, label = fn.readers.file(name="Reader", file_root=data_dir, shard_id=rank,
num_shards=world_size, random_shuffle=False, pad_last_batch=True)
images = fn.decoders.image(jpegs, device="mixed", output_type=types.RGB)
images = fn.resize(images, resize_shorter=image_size, interp_type=interpolation,
antialias=False)
output = fn.crop_mirror_normalize(images, dtype=types.FLOAT, output_layout=output_layout,
crop=(image_crop, image_crop),
mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
return output, label
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/dali.py
|
import math
import numpy as np
import torch
from torch import optim
def get_optimizer(parameters, lr, args, state=None):
if args.optimizer == "sgd":
optimizer = get_sgd_optimizer(
parameters,
lr,
momentum=args.momentum,
weight_decay=args.weight_decay,
nesterov=args.nesterov,
bn_weight_decay=args.bn_weight_decay,
)
elif args.optimizer == "rmsprop":
optimizer = get_rmsprop_optimizer(
parameters,
lr,
alpha=args.rmsprop_alpha,
momentum=args.momentum,
weight_decay=args.weight_decay,
eps=args.rmsprop_eps,
bn_weight_decay=args.bn_weight_decay,
)
if not state is None:
optimizer.load_state_dict(state)
return optimizer
def get_sgd_optimizer(
parameters, lr, momentum, weight_decay, nesterov=False, bn_weight_decay=False
):
if bn_weight_decay:
print(" ! Weight decay applied to BN parameters ")
params = [v for n, v in parameters]
else:
print(" ! Weight decay NOT applied to BN parameters ")
bn_params = [v for n, v in parameters if "bn" in n]
rest_params = [v for n, v in parameters if not "bn" in n]
print(len(bn_params))
print(len(rest_params))
params = [
{"params": bn_params, "weight_decay": 0},
{"params": rest_params, "weight_decay": weight_decay},
]
optimizer = torch.optim.SGD(
params, lr, momentum=momentum, weight_decay=weight_decay, nesterov=nesterov
)
return optimizer
def get_rmsprop_optimizer(
parameters, lr, alpha, weight_decay, momentum, eps, bn_weight_decay=False
):
bn_params = [v for n, v in parameters if "bn" in n]
rest_params = [v for n, v in parameters if not "bn" in n]
params = [
{"params": bn_params, "weight_decay": weight_decay if bn_weight_decay else 0},
{"params": rest_params, "weight_decay": weight_decay},
]
optimizer = torch.optim.RMSprop(
params,
lr=lr,
alpha=alpha,
weight_decay=weight_decay,
momentum=momentum,
eps=eps,
)
return optimizer
def lr_policy(lr_fn):
def _alr(optimizer, iteration, epoch):
lr = lr_fn(iteration, epoch)
for param_group in optimizer.param_groups:
param_group["lr"] = lr
return lr
return _alr
def lr_step_policy(base_lr, steps, decay_factor, warmup_length):
def _lr_fn(iteration, epoch):
if epoch < warmup_length:
lr = base_lr * (epoch + 1) / warmup_length
else:
lr = base_lr
for s in steps:
if epoch >= s:
lr *= decay_factor
return lr
return lr_policy(_lr_fn)
def lr_linear_policy(base_lr, warmup_length, epochs):
def _lr_fn(iteration, epoch):
if epoch < warmup_length:
lr = base_lr * (epoch + 1) / warmup_length
else:
e = epoch - warmup_length
es = epochs - warmup_length
lr = base_lr * (1 - (e / es))
return lr
return lr_policy(_lr_fn)
def lr_cosine_policy(base_lr, warmup_length, epochs, end_lr=0):
def _lr_fn(iteration, epoch):
if epoch < warmup_length:
lr = base_lr * (epoch + 1) / warmup_length
else:
e = epoch - warmup_length
es = epochs - warmup_length
lr = end_lr + (0.5 * (1 + np.cos(np.pi * e / es)) * (base_lr - end_lr))
return lr
return lr_policy(_lr_fn)
def lr_exponential_policy(
base_lr,
warmup_length,
epochs,
final_multiplier=0.001,
decay_factor=None,
decay_step=1,
logger=None,
):
"""Exponential lr policy. Setting decay factor parameter overrides final_multiplier"""
es = epochs - warmup_length
if decay_factor is not None:
epoch_decay = decay_factor
else:
epoch_decay = np.power(
2, np.log2(final_multiplier) / math.floor(es / decay_step)
)
def _lr_fn(iteration, epoch):
if epoch < warmup_length:
lr = base_lr * (epoch + 1) / warmup_length
else:
e = epoch - warmup_length
lr = base_lr * (epoch_decay ** math.floor(e / decay_step))
return lr
return lr_policy(_lr_fn, logger=logger)
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/optimizers.py
|
# Copyright (c) 2018-2019, NVIDIA CORPORATION
# Copyright (c) 2017- Facebook, Inc
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
import os
import numpy as np
import torch
import shutil
import signal
import torch.distributed as dist
class Checkpointer:
def __init__(self, last_filename, checkpoint_dir="./", keep_last_n=0):
self.last_filename = last_filename
self.checkpoints = []
self.checkpoint_dir = checkpoint_dir
self.keep_last_n = keep_last_n
def cleanup(self):
to_delete = self.checkpoints[: -self.keep_last_n]
self.checkpoints = self.checkpoints[-self.keep_last_n :]
for f in to_delete:
full_path = os.path.join(self.checkpoint_dir, f)
os.remove(full_path)
def get_full_path(self, filename):
return os.path.join(self.checkpoint_dir, filename)
def save_checkpoint(
self,
state,
is_best,
filename,
):
if torch.distributed.is_initialized() and torch.distributed.get_rank() != 0:
assert False
full_path = self.get_full_path(filename)
print("SAVING {}".format(full_path))
torch.save(state, full_path)
self.checkpoints.append(filename)
shutil.copyfile(
full_path, self.get_full_path(self.last_filename)
)
if is_best:
shutil.copyfile(
full_path, self.get_full_path("model_best.pth.tar")
)
self.cleanup()
def timed_generator(gen):
start = time.time()
for g in gen:
end = time.time()
t = end - start
yield g, t
start = time.time()
def timed_function(f):
def _timed_function(*args, **kwargs):
start = time.time()
ret = f(*args, **kwargs)
return ret, time.time() - start
return _timed_function
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.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].float().sum()
res.append(correct_k.mul_(100.0 / batch_size))
return res
def reduce_tensor(tensor):
rt = tensor.clone().detach()
dist.all_reduce(rt, op=dist.ReduceOp.SUM)
rt /= (
torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1
)
return rt
def first_n(n, generator):
for i, d in zip(range(n), generator):
yield d
class TimeoutHandler:
def __init__(self, sig=signal.SIGTERM):
self.sig = sig
self.device = torch.device("cuda")
@property
def interrupted(self):
if not dist.is_initialized():
return self._interrupted
interrupted = torch.tensor(self._interrupted).int().to(self.device)
dist.broadcast(interrupted, 0)
interrupted = bool(interrupted.item())
return interrupted
def __enter__(self):
self._interrupted = False
self.released = False
self.original_handler = signal.getsignal(self.sig)
def master_handler(signum, frame):
self.release()
self._interrupted = True
print(f"Received SIGTERM")
def ignoring_handler(signum, frame):
self.release()
print("Received SIGTERM, ignoring")
rank = dist.get_rank() if dist.is_initialized() else 0
if rank == 0:
signal.signal(self.sig, master_handler)
else:
signal.signal(self.sig, ignoring_handler)
return self
def __exit__(self, type, value, tb):
self.release()
def release(self):
if self.released:
return False
signal.signal(self.sig, self.original_handler)
self.released = True
return True
def calc_ips(batch_size, time):
world_size = (
torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1
)
tbs = world_size * batch_size
return tbs / time
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/utils.py
|
from PIL import Image, ImageEnhance, ImageOps
import numpy as np
import random
class AutoaugmentImageNetPolicy(object):
"""
Randomly choose one of the best 24 Sub-policies on ImageNet.
Reference: https://arxiv.org/abs/1805.09501
"""
def __init__(self):
self.policies = [
SubPolicy(0.8, "equalize", 1, 0.8, "shearY", 4),
SubPolicy(0.4, "color", 9, 0.6, "equalize", 3),
SubPolicy(0.4, "color", 1, 0.6, "rotate", 8),
SubPolicy(0.8, "solarize", 3, 0.4, "equalize", 7),
SubPolicy(0.4, "solarize", 2, 0.6, "solarize", 2),
SubPolicy(0.2, "color", 0, 0.8, "equalize", 8),
SubPolicy(0.4, "equalize", 8, 0.8, "solarizeadd", 3),
SubPolicy(0.2, "shearX", 9, 0.6, "rotate", 8),
SubPolicy(0.6, "color", 1, 1.0, "equalize", 2),
SubPolicy(0.4, "invert", 9, 0.6, "rotate", 0),
SubPolicy(1.0, "equalize", 9, 0.6, "shearY", 3),
SubPolicy(0.4, "color", 7, 0.6, "equalize", 0),
SubPolicy(0.4, "posterize", 6, 0.4, "autocontrast", 7),
SubPolicy(0.6, "solarize", 8, 0.6, "color", 9),
SubPolicy(0.2, "solarize", 4, 0.8, "rotate", 9),
SubPolicy(1.0, "rotate", 7, 0.8, "translateY", 9),
SubPolicy(0.0, "shearX", 0, 0.8, "solarize", 4),
SubPolicy(0.8, "shearY", 0, 0.6, "color", 4),
SubPolicy(1.0, "color", 0, 0.6, "rotate", 2),
SubPolicy(0.8, "equalize", 4, 0.0, "equalize", 8),
SubPolicy(1.0, "equalize", 4, 0.6, "autocontrast", 2),
SubPolicy(0.4, "shearY", 7, 0.6, "solarizeadd", 7),
SubPolicy(0.8, "posterize", 2, 0.6, "solarize", 10),
SubPolicy(0.6, "solarize", 8, 0.6, "equalize", 1),
SubPolicy(0.8, "color", 6, 0.4, "rotate", 5),
]
def __call__(self, img):
policy_idx = random.randint(0, len(self.policies) - 1)
return self.policies[policy_idx](img)
def __repr__(self):
return "AutoAugment ImageNet Policy"
class SubPolicy(object):
def __init__(self, p1, method1, magnitude_idx1, p2, method2, magnitude_idx2):
operation_factory = OperationFactory()
self.p1 = p1
self.p2 = p2
self.operation1 = operation_factory.get_operation(method1, magnitude_idx1)
self.operation2 = operation_factory.get_operation(method2, magnitude_idx2)
def __call__(self, img):
if random.random() < self.p1:
img = self.operation1(img)
if random.random() < self.p2:
img = self.operation2(img)
return img
class OperationFactory:
def __init__(self):
fillcolor = (128, 128, 128)
self.ranges = {
"shearX": np.linspace(0, 0.3, 11),
"shearY": np.linspace(0, 0.3, 11),
"translateX": np.linspace(0, 250, 11),
"translateY": np.linspace(0, 250, 11),
"rotate": np.linspace(0, 30, 11),
"color": np.linspace(0.1, 1.9, 11),
"posterize": np.round(np.linspace(0, 4, 11), 0).astype(np.int),
"solarize": np.linspace(0, 256, 11),
"solarizeadd": np.linspace(0, 110, 11),
"contrast": np.linspace(0.1, 1.9, 11),
"sharpness": np.linspace(0.1, 1.9, 11),
"brightness": np.linspace(0.1, 1.9, 11),
"autocontrast": [0] * 10,
"equalize": [0] * 10,
"invert": [0] * 10
}
def rotate_with_fill(img, magnitude):
magnitude *= random.choice([-1, 1])
rot = img.convert("RGBA").rotate(magnitude)
return Image.composite(rot, Image.new("RGBA", rot.size, (128,) * 4), rot).convert(img.mode)
def solarize_add(image, addition=0, threshold=128):
lut = []
for i in range(256):
if i < threshold:
res = i + addition if i + addition <= 255 else 255
res = res if res >= 0 else 0
lut.append(res)
else:
lut.append(i)
from PIL.ImageOps import _lut
return _lut(image, lut)
self.operations = {
"shearX": lambda img, magnitude: img.transform(
img.size, Image.AFFINE, (1, magnitude * random.choice([-1, 1]), 0, 0, 1, 0),
Image.BICUBIC, fillcolor=fillcolor),
"shearY": lambda img, magnitude: img.transform(
img.size, Image.AFFINE, (1, 0, 0, magnitude * random.choice([-1, 1]), 1, 0),
Image.BICUBIC, fillcolor=fillcolor),
"translateX": lambda img, magnitude: img.transform(
img.size, Image.AFFINE, (1, 0, magnitude * random.choice([-1, 1]), 0, 1, 0),
fillcolor=fillcolor),
"translateY": lambda img, magnitude: img.transform(
img.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * random.choice([-1, 1])),
fillcolor=fillcolor),
"rotate": lambda img, magnitude: rotate_with_fill(img, magnitude),
"color": lambda img, magnitude: ImageEnhance.Color(img).enhance(magnitude),
"posterize": lambda img, magnitude: ImageOps.posterize(img, magnitude),
"solarize": lambda img, magnitude: ImageOps.solarize(img, magnitude),
"solarizeadd": lambda img, magnitude: solarize_add(img, magnitude),
"contrast": lambda img, magnitude: ImageEnhance.Contrast(img).enhance(magnitude),
"sharpness": lambda img, magnitude: ImageEnhance.Sharpness(img).enhance(magnitude),
"brightness": lambda img, magnitude: ImageEnhance.Brightness(img).enhance(magnitude),
"autocontrast": lambda img, _: ImageOps.autocontrast(img),
"equalize": lambda img, _: ImageOps.equalize(img),
"invert": lambda img, _: ImageOps.invert(img)
}
def get_operation(self, method, magnitude_idx):
magnitude = self.ranges[method][magnitude_idx]
return lambda img: self.operations[method](img, magnitude)
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/autoaugment.py
|
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# 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 torch
import torch.nn as nn
class LabelSmoothing(nn.Module):
"""
NLL loss with label smoothing.
"""
def __init__(self, smoothing=0.0):
"""
Constructor for the LabelSmoothing module.
:param smoothing: label smoothing factor
"""
super(LabelSmoothing, self).__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
def forward(self, x, target):
logprobs = torch.nn.functional.log_softmax(x, dim=-1)
nll_loss = -logprobs.gather(dim=-1, index=target.unsqueeze(1))
nll_loss = nll_loss.squeeze(1)
smooth_loss = -logprobs.mean(dim=-1)
loss = self.confidence * nll_loss + self.smoothing * smooth_loss
return loss.mean()
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/smoothing.py
|
# Copyright (c) 2018-2019, NVIDIA CORPORATION
# Copyright (c) 2017- Facebook, Inc
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import time
from copy import deepcopy
from functools import wraps
from typing import Callable, Dict, Optional, Tuple
import torch
import torch.nn as nn
from torch.cuda.amp import autocast
from torch.nn.parallel import DistributedDataParallel as DDP
from . import logger as log
from . import utils
from .logger import TrainingMetrics, ValidationMetrics
from .models.common import EMA
class Executor:
def __init__(
self,
model: nn.Module,
loss: Optional[nn.Module],
cuda: bool = True,
memory_format: torch.memory_format = torch.contiguous_format,
amp: bool = False,
scaler: Optional[torch.cuda.amp.GradScaler] = None,
divide_loss: int = 1,
ts_script: bool = False,
):
assert not (amp and scaler is None), "Gradient Scaler is needed for AMP"
def xform(m: nn.Module) -> nn.Module:
if cuda:
m = m.cuda()
m.to(memory_format=memory_format)
return m
self.model = xform(model)
if ts_script:
self.model = torch.jit.script(self.model)
self.ts_script = ts_script
self.loss = xform(loss) if loss is not None else None
self.amp = amp
self.scaler = scaler
self.is_distributed = False
self.divide_loss = divide_loss
self._fwd_bwd = None
self._forward = None
def distributed(self, gpu_id):
self.is_distributed = True
s = torch.cuda.Stream()
s.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(s):
self.model = DDP(self.model, device_ids=[gpu_id], output_device=gpu_id)
torch.cuda.current_stream().wait_stream(s)
def _fwd_bwd_fn(
self,
input: torch.Tensor,
target: torch.Tensor,
) -> torch.Tensor:
with autocast(enabled=self.amp):
loss = self.loss(self.model(input), target)
loss /= self.divide_loss
self.scaler.scale(loss).backward()
return loss
def _forward_fn(
self, input: torch.Tensor, target: torch.Tensor
) -> Tuple[torch.Tensor, torch.Tensor]:
with torch.no_grad(), autocast(enabled=self.amp):
output = self.model(input)
loss = None if self.loss is None else self.loss(output, target)
return output if loss is None else loss, output
def optimize(self, fn):
return fn
@property
def forward_backward(self):
if self._fwd_bwd is None:
if self.loss is None:
raise NotImplementedError(
"Loss must not be None for forward+backward step"
)
self._fwd_bwd = self.optimize(self._fwd_bwd_fn)
return self._fwd_bwd
@property
def forward(self):
if self._forward is None:
self._forward = self.optimize(self._forward_fn)
return self._forward
def train(self):
self.model.train()
if self.loss is not None:
self.loss.train()
def eval(self):
self.model.eval()
if self.loss is not None:
self.loss.eval()
class Trainer:
def __init__(
self,
executor: Executor,
optimizer: torch.optim.Optimizer,
grad_acc_steps: int,
ema: Optional[float] = None,
):
self.executor = executor
self.optimizer = optimizer
self.grad_acc_steps = grad_acc_steps
self.use_ema = False
if ema is not None:
self.ema_executor = deepcopy(self.executor)
self.ema = EMA(ema, self.ema_executor.model)
self.use_ema = True
self.optimizer.zero_grad(set_to_none=True)
self.steps_since_update = 0
def train(self):
self.executor.train()
if self.use_ema:
self.ema_executor.train()
def eval(self):
self.executor.eval()
if self.use_ema:
self.ema_executor.eval()
def train_step(self, input, target, step=None):
loss = self.executor.forward_backward(input, target)
self.steps_since_update += 1
if self.steps_since_update == self.grad_acc_steps:
if self.executor.scaler is not None:
self.executor.scaler.step(self.optimizer)
self.executor.scaler.update()
else:
self.optimizer.step()
self.optimizer.zero_grad()
self.steps_since_update = 0
torch.cuda.synchronize()
if self.use_ema:
self.ema(self.executor.model, step=step)
return loss
def validation_steps(self) -> Dict[str, Callable]:
vsd: Dict[str, Callable] = {"val": self.executor.forward}
if self.use_ema:
vsd["val_ema"] = self.ema_executor.forward
return vsd
def state_dict(self) -> dict:
res = {
"state_dict": self.executor.model.state_dict(),
"optimizer": self.optimizer.state_dict(),
}
if self.use_ema:
res["state_dict_ema"] = self.ema_executor.model.state_dict()
return res
def train(
train_step,
train_loader,
lr_scheduler,
grad_scale_fn,
log_fn,
timeout_handler,
prof=-1,
step=0,
):
interrupted = False
end = time.time()
data_iter = enumerate(train_loader)
for i, (input, target) in data_iter:
bs = input.size(0)
lr = lr_scheduler(i)
data_time = time.time() - end
loss = train_step(input, target, step=step + i)
it_time = time.time() - end
with torch.no_grad():
if torch.distributed.is_initialized():
reduced_loss = utils.reduce_tensor(loss.detach())
else:
reduced_loss = loss.detach()
log_fn(
compute_ips=utils.calc_ips(bs, it_time - data_time),
total_ips=utils.calc_ips(bs, it_time),
data_time=data_time,
compute_time=it_time - data_time,
lr=lr,
loss=reduced_loss.item(),
grad_scale=grad_scale_fn(),
)
end = time.time()
if prof > 0 and (i + 1 >= prof):
time.sleep(5)
break
if ((i + 1) % 20 == 0) and timeout_handler.interrupted:
time.sleep(5)
interrupted = True
break
return interrupted
def validate(infer_fn, val_loader, log_fn, prof=-1, with_loss=True, topk=5):
top1 = log.AverageMeter()
# switch to evaluate mode
end = time.time()
data_iter = enumerate(val_loader)
for i, (input, target) in data_iter:
bs = input.size(0)
data_time = time.time() - end
if with_loss:
loss, output = infer_fn(input, target)
else:
output = infer_fn(input)
with torch.no_grad():
precs = utils.accuracy(output.data, target, topk=(1, topk))
if torch.distributed.is_initialized():
if with_loss:
reduced_loss = utils.reduce_tensor(loss.detach())
precs = map(utils.reduce_tensor, precs)
else:
if with_loss:
reduced_loss = loss.detach()
precs = map(lambda t: t.item(), precs)
infer_result = {f"top{k}": (p, bs) for k, p in zip((1, topk), precs)}
if with_loss:
infer_result["loss"] = (reduced_loss.item(), bs)
torch.cuda.synchronize()
it_time = time.time() - end
top1.record(infer_result["top1"][0], bs)
log_fn(
compute_ips=utils.calc_ips(bs, it_time - data_time),
total_ips=utils.calc_ips(bs, it_time),
data_time=data_time,
compute_time=it_time - data_time,
**infer_result,
)
end = time.time()
if (prof > 0) and (i + 1 >= prof):
time.sleep(5)
break
return top1.get_val()
# Train loop {{{
def train_loop(
trainer: Trainer,
lr_scheduler,
train_loader,
train_loader_len,
val_loader,
logger,
best_prec1=0,
start_epoch=0,
end_epoch=0,
early_stopping_patience=-1,
prof=-1,
skip_training=False,
skip_validation=False,
save_checkpoints=True,
checkpoint_dir="./",
checkpoint_filename="checkpoint.pth.tar",
keep_last_n_checkpoints=0,
topk=5,
):
checkpointer = utils.Checkpointer(
last_filename=checkpoint_filename,
checkpoint_dir=checkpoint_dir,
keep_last_n=keep_last_n_checkpoints,
)
train_metrics = TrainingMetrics(logger)
val_metrics = {
k: ValidationMetrics(logger, k, topk) for k in trainer.validation_steps().keys()
}
training_step = trainer.train_step
prec1 = -1
if early_stopping_patience > 0:
epochs_since_improvement = 0
print(f"RUNNING EPOCHS FROM {start_epoch} TO {end_epoch}")
with utils.TimeoutHandler() as timeout_handler:
interrupted = False
for epoch in range(start_epoch, end_epoch):
if logger is not None:
logger.start_epoch()
if not skip_training:
if logger is not None:
data_iter = logger.iteration_generator_wrapper(
train_loader, mode="train"
)
else:
data_iter = train_loader
trainer.train()
interrupted = train(
training_step,
data_iter,
lambda i: lr_scheduler(trainer.optimizer, i, epoch),
trainer.executor.scaler.get_scale,
train_metrics.log,
timeout_handler,
prof=prof,
step=epoch * train_loader_len,
)
if not skip_validation:
trainer.eval()
for k, infer_fn in trainer.validation_steps().items():
if logger is not None:
data_iter = logger.iteration_generator_wrapper(
val_loader, mode="val"
)
else:
data_iter = val_loader
step_prec1, _ = validate(
infer_fn,
data_iter,
val_metrics[k].log,
prof=prof,
topk=topk,
)
if k == "val":
prec1 = step_prec1
if prec1 > best_prec1:
is_best = True
best_prec1 = prec1
else:
is_best = False
else:
is_best = False
best_prec1 = 0
if logger is not None:
logger.end_epoch()
if save_checkpoints and (
not torch.distributed.is_initialized()
or torch.distributed.get_rank() == 0
):
checkpoint_state = {
"epoch": epoch + 1,
"best_prec1": best_prec1,
**trainer.state_dict(),
}
checkpointer.save_checkpoint(
checkpoint_state,
is_best,
filename=f"checkpoint_{epoch:04}.pth.tar",
)
if early_stopping_patience > 0:
if not is_best:
epochs_since_improvement += 1
else:
epochs_since_improvement = 0
if epochs_since_improvement >= early_stopping_patience:
break
if interrupted:
break
# }}}
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/training.py
|
# Copyright (c) 2019-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# 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 .entrypoints import nvidia_convnets_processing_utils, nvidia_efficientnet
from .efficientnet import efficientnet_b0
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/models/__init__.py
|
import argparse
import random
import math
import warnings
from typing import List, Any, Optional
from collections import namedtuple, OrderedDict
from dataclasses import dataclass, replace
import torch
from torch import nn
from functools import partial
try:
from pytorch_quantization import nn as quant_nn
from ..quantization import switch_on_quantization
except ImportError as e:
warnings.warn(
"pytorch_quantization module not found, quantization will not be available"
)
quant_nn = None
import contextlib
@contextlib.contextmanager
def switch_on_quantization(do_quantization=False):
assert not do_quantization, "quantization is not available"
try:
yield
finally:
pass
from .common import (
SequentialSqueezeAndExcitation,
SequentialSqueezeAndExcitationTRT,
LayerBuilder,
StochasticDepthResidual,
Flatten,
)
from .model import (
Model,
ModelParams,
ModelArch,
OptimizerParams,
create_entrypoint,
EntryPoint,
)
# EffNetArch {{{
@dataclass
class EffNetArch(ModelArch):
block: Any
stem_channels: int
feature_channels: int
kernel: List[int]
stride: List[int]
num_repeat: List[int]
expansion: List[int]
channels: List[int]
default_image_size: int
squeeze_excitation_ratio: float = 0.25
def enumerate(self):
return enumerate(
zip(
self.kernel, self.stride, self.num_repeat, self.expansion, self.channels
)
)
def num_layers(self):
_f = lambda l: len(set(map(len, l)))
l = [self.kernel, self.stride, self.num_repeat, self.expansion, self.channels]
assert _f(l) == 1
return len(self.kernel)
@staticmethod
def _scale_width(width_coeff, divisor=8):
def _sw(num_channels):
num_channels *= width_coeff
# Rounding should not go down by more than 10%
rounded_num_channels = max(
divisor, int(num_channels + divisor / 2) // divisor * divisor
)
if rounded_num_channels < 0.9 * num_channels:
rounded_num_channels += divisor
return rounded_num_channels
return _sw
@staticmethod
def _scale_depth(depth_coeff):
def _sd(num_repeat):
return int(math.ceil(num_repeat * depth_coeff))
return _sd
def scale(self, wc, dc, dis, divisor=8) -> "EffNetArch":
sw = EffNetArch._scale_width(wc, divisor=divisor)
sd = EffNetArch._scale_depth(dc)
return EffNetArch(
block=self.block,
stem_channels=sw(self.stem_channels),
feature_channels=sw(self.feature_channels),
kernel=self.kernel,
stride=self.stride,
num_repeat=list(map(sd, self.num_repeat)),
expansion=self.expansion,
channels=list(map(sw, self.channels)),
default_image_size=dis,
squeeze_excitation_ratio=self.squeeze_excitation_ratio,
)
# }}}
# EffNetParams {{{
@dataclass
class EffNetParams(ModelParams):
dropout: float
num_classes: int = 1000
activation: str = "silu"
conv_init: str = "fan_in"
bn_momentum: float = 1 - 0.99
bn_epsilon: float = 1e-3
survival_prob: float = 1
quantized: bool = False
trt: bool = False
def parser(self, name):
p = super().parser(name)
p.add_argument(
"--num_classes",
metavar="N",
default=self.num_classes,
type=int,
help="number of classes",
)
p.add_argument(
"--conv_init",
default=self.conv_init,
choices=["fan_in", "fan_out"],
type=str,
help="initialization mode for convolutional layers, see https://pytorch.org/docs/stable/nn.init.html#torch.nn.init.kaiming_normal_",
)
p.add_argument(
"--bn_momentum",
default=self.bn_momentum,
type=float,
help="Batch Norm momentum",
)
p.add_argument(
"--bn_epsilon",
default=self.bn_epsilon,
type=float,
help="Batch Norm epsilon",
)
p.add_argument(
"--survival_prob",
default=self.survival_prob,
type=float,
help="Survival probability for stochastic depth",
)
p.add_argument(
"--dropout", default=self.dropout, type=float, help="Dropout drop prob"
)
p.add_argument("--trt", metavar="True|False", default=self.trt, type=bool)
return p
# }}}
class EfficientNet(nn.Module):
def __init__(
self,
arch: EffNetArch,
dropout: float,
num_classes: int = 1000,
activation: str = "silu",
conv_init: str = "fan_in",
bn_momentum: float = 1 - 0.99,
bn_epsilon: float = 1e-3,
survival_prob: float = 1,
quantized: bool = False,
trt: bool = False,
):
self.quantized = quantized
with switch_on_quantization(self.quantized):
super(EfficientNet, self).__init__()
self.arch = arch
self.num_layers = arch.num_layers()
self.num_blocks = sum(arch.num_repeat)
self.survival_prob = survival_prob
self.builder = LayerBuilder(
LayerBuilder.Config(
activation=activation,
conv_init=conv_init,
bn_momentum=bn_momentum,
bn_epsilon=bn_epsilon,
)
)
self.stem = self._make_stem(arch.stem_channels)
out_channels = arch.stem_channels
plc = 0
layers = []
for i, (k, s, r, e, c) in arch.enumerate():
layer, out_channels = self._make_layer(
block=arch.block,
kernel_size=k,
stride=s,
num_repeat=r,
expansion=e,
in_channels=out_channels,
out_channels=c,
squeeze_excitation_ratio=arch.squeeze_excitation_ratio,
prev_layer_count=plc,
trt=trt,
)
plc = plc + r
layers.append(layer)
self.layers = nn.Sequential(*layers)
self.features = self._make_features(out_channels, arch.feature_channels)
self.classifier = self._make_classifier(
arch.feature_channels, num_classes, dropout
)
def forward(self, x):
x = self.stem(x)
x = self.layers(x)
x = self.features(x)
x = self.classifier(x)
return x
def extract_features(self, x, layers=None):
if layers is None:
layers = [f"layer{i+1}" for i in range(self.num_layers)] + [
"features",
"classifier",
]
run = [
i
for i in range(self.num_layers)
if "classifier" in layers
or "features" in layers
or any([f"layer{j+1}" in layers for j in range(i, self.num_layers)])
]
output = {}
x = self.stem(x)
for l in run:
fn = self.layers[l]
x = fn(x)
if f"layer{l+1}" in layers:
output[f"layer{l+1}"] = x
if "features" in layers or "classifier" in layers:
x = self.features(x)
if "features" in layers:
output["features"] = x
if "classifier" in layers:
output["classifier"] = self.classifier(x)
return output
# helper functions {{{
def _make_stem(self, stem_width):
return nn.Sequential(
OrderedDict(
[
("conv", self.builder.conv3x3(3, stem_width, stride=2)),
("bn", self.builder.batchnorm(stem_width)),
("activation", self.builder.activation()),
]
)
)
def _get_survival_prob(self, block_id):
drop_rate = 1.0 - self.survival_prob
sp = 1.0 - drop_rate * float(block_id) / self.num_blocks
return sp
def _make_features(self, in_channels, num_features):
return nn.Sequential(
OrderedDict(
[
("conv", self.builder.conv1x1(in_channels, num_features)),
("bn", self.builder.batchnorm(num_features)),
("activation", self.builder.activation()),
]
)
)
def _make_classifier(self, num_features, num_classes, dropout):
return nn.Sequential(
OrderedDict(
[
("pooling", nn.AdaptiveAvgPool2d(1)),
("squeeze", Flatten()),
("dropout", nn.Dropout(dropout)),
("fc", nn.Linear(num_features, num_classes)),
]
)
)
def _make_layer(
self,
block,
kernel_size,
stride,
num_repeat,
expansion,
in_channels,
out_channels,
squeeze_excitation_ratio,
prev_layer_count,
trt,
):
layers = []
idx = 0
survival_prob = self._get_survival_prob(idx + prev_layer_count)
blk = block(
self.builder,
kernel_size,
in_channels,
out_channels,
expansion,
stride,
self.arch.squeeze_excitation_ratio,
survival_prob if stride == 1 and in_channels == out_channels else 1.0,
self.quantized,
trt=trt,
)
layers.append((f"block{idx}", blk))
for idx in range(1, num_repeat):
survival_prob = self._get_survival_prob(idx + prev_layer_count)
blk = block(
self.builder,
kernel_size,
out_channels,
out_channels,
expansion,
1, # stride
squeeze_excitation_ratio,
survival_prob,
self.quantized,
trt=trt,
)
layers.append((f"block{idx}", blk))
return nn.Sequential(OrderedDict(layers)), out_channels
def ngc_checkpoint_remap(self, url=None, version=None):
if version is None:
version = url.split("/")[8]
def to_sequential_remap(s):
splited = s.split(".")
if splited[0].startswith("layer"):
return ".".join(
["layers." + str(int(splited[0][len("layer") :]) - 1)] + splited[1:]
)
else:
return s
def no_remap(s):
return s
return {"20.12.0": to_sequential_remap, "21.03.0": to_sequential_remap}.get(
version, no_remap
)
# }}}
# MBConvBlock {{{
class MBConvBlock(nn.Module):
__constants__ = ["quantized"]
def __init__(
self,
builder: LayerBuilder,
depsep_kernel_size: int,
in_channels: int,
out_channels: int,
expand_ratio: int,
stride: int,
squeeze_excitation_ratio: float,
squeeze_hidden=False,
survival_prob: float = 1.0,
quantized: bool = False,
trt: bool = False,
):
super().__init__()
self.quantized = quantized
self.residual = stride == 1 and in_channels == out_channels
hidden_dim = in_channels * expand_ratio
squeeze_base = hidden_dim if squeeze_hidden else in_channels
squeeze_dim = max(1, int(squeeze_base * squeeze_excitation_ratio))
self.expand = (
None
if in_channels == hidden_dim
else builder.conv1x1(in_channels, hidden_dim, bn=True, act=True)
)
self.depsep = builder.convDepSep(
depsep_kernel_size, hidden_dim, hidden_dim, stride, bn=True, act=True
)
if trt or self.quantized:
# Need TRT mode for quantized in order to automatically insert quantization before pooling
self.se: nn.Module = SequentialSqueezeAndExcitationTRT(
hidden_dim, squeeze_dim, builder.activation(), self.quantized
)
else:
self.se: nn.Module = SequentialSqueezeAndExcitation(
hidden_dim, squeeze_dim, builder.activation(), self.quantized
)
self.proj = builder.conv1x1(hidden_dim, out_channels, bn=True)
if survival_prob == 1.0:
self.residual_add = torch.add
else:
self.residual_add = StochasticDepthResidual(survival_prob=survival_prob)
if self.quantized and self.residual:
assert quant_nn is not None, "pytorch_quantization is not available"
self.residual_quantizer = quant_nn.TensorQuantizer(
quant_nn.QuantConv2d.default_quant_desc_input
) # TODO QuantConv2d ?!?
else:
self.residual_quantizer = nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
if not self.residual:
return self.proj(
self.se(self.depsep(x if self.expand is None else self.expand(x)))
)
b = self.proj(
self.se(self.depsep(x if self.expand is None else self.expand(x)))
)
if self.quantized:
x = self.residual_quantizer(x)
return self.residual_add(x, b)
def original_mbconv(
builder: LayerBuilder,
depsep_kernel_size: int,
in_channels: int,
out_channels: int,
expand_ratio: int,
stride: int,
squeeze_excitation_ratio: int,
survival_prob: float,
quantized: bool,
trt: bool,
):
return MBConvBlock(
builder,
depsep_kernel_size,
in_channels,
out_channels,
expand_ratio,
stride,
squeeze_excitation_ratio,
squeeze_hidden=False,
survival_prob=survival_prob,
quantized=quantized,
trt=trt,
)
def widese_mbconv(
builder: LayerBuilder,
depsep_kernel_size: int,
in_channels: int,
out_channels: int,
expand_ratio: int,
stride: int,
squeeze_excitation_ratio: int,
survival_prob: float,
quantized: bool,
trt: bool,
):
return MBConvBlock(
builder,
depsep_kernel_size,
in_channels,
out_channels,
expand_ratio,
stride,
squeeze_excitation_ratio,
squeeze_hidden=True,
survival_prob=survival_prob,
quantized=quantized,
trt=trt,
)
# }}}
# EffNet configs {{{
# fmt: off
effnet_b0_layers = EffNetArch(
block = original_mbconv,
stem_channels = 32,
feature_channels=1280,
kernel = [ 3, 3, 5, 3, 5, 5, 3],
stride = [ 1, 2, 2, 2, 1, 2, 1],
num_repeat = [ 1, 2, 2, 3, 3, 4, 1],
expansion = [ 1, 6, 6, 6, 6, 6, 6],
channels = [16, 24, 40, 80, 112, 192, 320],
default_image_size=224,
)
effnet_b1_layers=effnet_b0_layers.scale(wc=1, dc=1.1, dis=240)
effnet_b2_layers=effnet_b0_layers.scale(wc=1.1, dc=1.2, dis=260)
effnet_b3_layers=effnet_b0_layers.scale(wc=1.2, dc=1.4, dis=300)
effnet_b4_layers=effnet_b0_layers.scale(wc=1.4, dc=1.8, dis=380)
effnet_b5_layers=effnet_b0_layers.scale(wc=1.6, dc=2.2, dis=456)
effnet_b6_layers=effnet_b0_layers.scale(wc=1.8, dc=2.6, dis=528)
effnet_b7_layers=effnet_b0_layers.scale(wc=2.0, dc=3.1, dis=600)
urls = {
"efficientnet-b0": "https://api.ngc.nvidia.com/v2/models/nvidia/efficientnet_b0_pyt_amp/versions/20.12.0/files/nvidia_efficientnet-b0_210412.pth",
"efficientnet-b4": "https://api.ngc.nvidia.com/v2/models/nvidia/efficientnet_b4_pyt_amp/versions/20.12.0/files/nvidia_efficientnet-b4_210412.pth",
"efficientnet-widese-b0": "https://api.ngc.nvidia.com/v2/models/nvidia/efficientnet_widese_b0_pyt_amp/versions/20.12.0/files/nvidia_efficientnet-widese-b0_210412.pth",
"efficientnet-widese-b4": "https://api.ngc.nvidia.com/v2/models/nvidia/efficientnet_widese_b4_pyt_amp/versions/20.12.0/files/nvidia_efficientnet-widese-b4_210412.pth",
"efficientnet-quant-b0": "https://api.ngc.nvidia.com/v2/models/nvidia/efficientnet_b0_pyt_qat_ckpt_fp32/versions/21.03.0/files/nvidia-efficientnet-quant-b0-130421.pth",
"efficientnet-quant-b4": "https://api.ngc.nvidia.com/v2/models/nvidia/efficientnet_b4_pyt_qat_ckpt_fp32/versions/21.03.0/files/nvidia-efficientnet-quant-b4-130421.pth",
}
def _m(*args, **kwargs):
return Model(constructor=EfficientNet, *args, **kwargs)
architectures = {
"efficientnet-b0": _m(arch=effnet_b0_layers, params=EffNetParams(dropout=0.2), checkpoint_url=urls["efficientnet-b0"]),
"efficientnet-b1": _m(arch=effnet_b1_layers, params=EffNetParams(dropout=0.2)),
"efficientnet-b2": _m(arch=effnet_b2_layers, params=EffNetParams(dropout=0.3)),
"efficientnet-b3": _m(arch=effnet_b3_layers, params=EffNetParams(dropout=0.3)),
"efficientnet-b4": _m(arch=effnet_b4_layers, params=EffNetParams(dropout=0.4, survival_prob=0.8), checkpoint_url=urls["efficientnet-b4"]),
"efficientnet-b5": _m(arch=effnet_b5_layers, params=EffNetParams(dropout=0.4)),
"efficientnet-b6": _m(arch=effnet_b6_layers, params=EffNetParams(dropout=0.5)),
"efficientnet-b7": _m(arch=effnet_b7_layers, params=EffNetParams(dropout=0.5)),
"efficientnet-widese-b0": _m(arch=replace(effnet_b0_layers, block=widese_mbconv), params=EffNetParams(dropout=0.2), checkpoint_url=urls["efficientnet-widese-b0"]),
"efficientnet-widese-b1": _m(arch=replace(effnet_b1_layers, block=widese_mbconv), params=EffNetParams(dropout=0.2)),
"efficientnet-widese-b2": _m(arch=replace(effnet_b2_layers, block=widese_mbconv), params=EffNetParams(dropout=0.3)),
"efficientnet-widese-b3": _m(arch=replace(effnet_b3_layers, block=widese_mbconv), params=EffNetParams(dropout=0.3)),
"efficientnet-widese-b4": _m(arch=replace(effnet_b4_layers, block=widese_mbconv), params=EffNetParams(dropout=0.4, survival_prob=0.8), checkpoint_url=urls["efficientnet-widese-b4"]),
"efficientnet-widese-b5": _m(arch=replace(effnet_b5_layers, block=widese_mbconv), params=EffNetParams(dropout=0.4)),
"efficientnet-widese-b6": _m(arch=replace(effnet_b6_layers, block=widese_mbconv), params=EffNetParams(dropout=0.5)),
"efficientnet-widese-b7": _m(arch=replace(effnet_b7_layers, block=widese_mbconv), params=EffNetParams(dropout=0.5)),
"efficientnet-quant-b0": _m(arch=effnet_b0_layers, params=EffNetParams(dropout=0.2, quantized=True), checkpoint_url=urls["efficientnet-quant-b0"]),
"efficientnet-quant-b1": _m(arch=effnet_b1_layers, params=EffNetParams(dropout=0.2, quantized=True)),
"efficientnet-quant-b2": _m(arch=effnet_b2_layers, params=EffNetParams(dropout=0.3, quantized=True)),
"efficientnet-quant-b3": _m(arch=effnet_b3_layers, params=EffNetParams(dropout=0.3, quantized=True)),
"efficientnet-quant-b4": _m(arch=effnet_b4_layers, params=EffNetParams(dropout=0.4, survival_prob=0.8, quantized=True), checkpoint_url=urls["efficientnet-quant-b4"]),
"efficientnet-quant-b5": _m(arch=effnet_b5_layers, params=EffNetParams(dropout=0.4, quantized=True)),
"efficientnet-quant-b6": _m(arch=effnet_b6_layers, params=EffNetParams(dropout=0.5, quantized=True)),
"efficientnet-quant-b7": _m(arch=effnet_b7_layers, params=EffNetParams(dropout=0.5, quantized=True)),
}
# fmt: on
# }}}
_ce = lambda n: EntryPoint.create(n, architectures[n])
efficientnet_b0 = _ce("efficientnet-b0")
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/models/efficientnet.py
|
from dataclasses import dataclass, asdict, replace
from .common import (
SequentialSqueezeAndExcitationTRT,
SequentialSqueezeAndExcitation,
SqueezeAndExcitation,
SqueezeAndExcitationTRT,
)
from typing import Optional, Callable
import os
import torch
import argparse
from functools import partial
@dataclass
class ModelArch:
pass
@dataclass
class ModelParams:
def parser(self, name):
return argparse.ArgumentParser(
description=f"{name} arguments", add_help=False, usage=""
)
@dataclass
class OptimizerParams:
pass
@dataclass
class Model:
constructor: Callable
arch: ModelArch
params: Optional[ModelParams]
optimizer_params: Optional[OptimizerParams] = None
checkpoint_url: Optional[str] = None
def torchhub_docstring(name: str):
return f"""Constructs a {name} model.
For detailed information on model input and output, training recipies, inference and performance
visit: github.com/NVIDIA/DeepLearningExamples and/or ngc.nvidia.com
Args:
pretrained (bool, True): If True, returns a model pretrained on IMAGENET dataset.
"""
class EntryPoint:
@staticmethod
def create(name: str, model: Model):
ep = EntryPoint(name, model)
ep.__doc__ = torchhub_docstring(name)
return ep
def __init__(self, name: str, model: Model):
self.name = name
self.model = model
def __call__(
self,
pretrained=True,
pretrained_from_file=None,
state_dict_key_map_fn=None,
**kwargs,
):
assert not (pretrained and (pretrained_from_file is not None))
params = replace(self.model.params, **kwargs)
model = self.model.constructor(arch=self.model.arch, **asdict(params))
state_dict = None
if pretrained:
assert self.model.checkpoint_url is not None
state_dict = torch.hub.load_state_dict_from_url(
self.model.checkpoint_url,
map_location=torch.device("cpu"),
progress=True,
)
if pretrained_from_file is not None:
if os.path.isfile(pretrained_from_file):
print(
"=> loading pretrained weights from '{}'".format(
pretrained_from_file
)
)
state_dict = torch.load(
pretrained_from_file, map_location=torch.device("cpu")
)
else:
print(
"=> no pretrained weights found at '{}'".format(
pretrained_from_file
)
)
if state_dict is not None:
state_dict = {
k[len("module.") :] if k.startswith("module.") else k: v
for k, v in state_dict.items()
}
def reshape(t, conv):
if conv:
if len(t.shape) == 4:
return t
else:
return t.view(t.shape[0], -1, 1, 1)
else:
if len(t.shape) == 4:
return t.view(t.shape[0], t.shape[1])
else:
return t
if state_dict_key_map_fn is not None:
state_dict = {
state_dict_key_map_fn(k): v for k, v in state_dict.items()
}
if pretrained and hasattr(model, "ngc_checkpoint_remap"):
remap_fn = model.ngc_checkpoint_remap(url=self.model.checkpoint_url)
state_dict = {remap_fn(k): v for k, v in state_dict.items()}
def _se_layer_uses_conv(m):
return any(
map(
partial(isinstance, m),
[
SqueezeAndExcitationTRT,
SequentialSqueezeAndExcitationTRT,
],
)
)
state_dict = {
k: reshape(
v,
conv=_se_layer_uses_conv(
dict(model.named_modules())[".".join(k.split(".")[:-2])]
),
)
if is_se_weight(k, v)
else v
for k, v in state_dict.items()
}
model.load_state_dict(state_dict)
return model
def parser(self):
if self.model.params is None:
return None
parser = self.model.params.parser(self.name)
parser.add_argument(
"--pretrained-from-file",
default=None,
type=str,
metavar="PATH",
help="load weights from local file",
)
if self.model.checkpoint_url is not None:
parser.add_argument(
"--pretrained",
default=False,
action="store_true",
help="load pretrained weights from NGC",
)
return parser
def is_se_weight(key, value):
return key.endswith("squeeze.weight") or key.endswith("expand.weight")
def create_entrypoint(m: Model):
def _ep(**kwargs):
params = replace(m.params, **kwargs)
return m.constructor(arch=m.arch, **asdict(params))
return _ep
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/models/model.py
|
import copy
from collections import OrderedDict
from dataclasses import dataclass
from typing import Optional
import torch
import warnings
from torch import nn
import torch.nn.functional as F
try:
from pytorch_quantization import nn as quant_nn
except ImportError as e:
warnings.warn(
"pytorch_quantization module not found, quantization will not be available"
)
quant_nn = None
# LayerBuilder {{{
class LayerBuilder(object):
@dataclass
class Config:
activation: str = "relu"
conv_init: str = "fan_in"
bn_momentum: Optional[float] = None
bn_epsilon: Optional[float] = None
def __init__(self, config: "LayerBuilder.Config"):
self.config = config
def conv(
self,
kernel_size,
in_planes,
out_planes,
groups=1,
stride=1,
bn=False,
zero_init_bn=False,
act=False,
):
conv = nn.Conv2d(
in_planes,
out_planes,
kernel_size=kernel_size,
groups=groups,
stride=stride,
padding=int((kernel_size - 1) / 2),
bias=False,
)
nn.init.kaiming_normal_(
conv.weight, mode=self.config.conv_init, nonlinearity="relu"
)
layers = [("conv", conv)]
if bn:
layers.append(("bn", self.batchnorm(out_planes, zero_init_bn)))
if act:
layers.append(("act", self.activation()))
if bn or act:
return nn.Sequential(OrderedDict(layers))
else:
return conv
def convDepSep(
self, kernel_size, in_planes, out_planes, stride=1, bn=False, act=False
):
"""3x3 depthwise separable convolution with padding"""
c = self.conv(
kernel_size,
in_planes,
out_planes,
groups=in_planes,
stride=stride,
bn=bn,
act=act,
)
return c
def conv3x3(self, in_planes, out_planes, stride=1, groups=1, bn=False, act=False):
"""3x3 convolution with padding"""
c = self.conv(
3, in_planes, out_planes, groups=groups, stride=stride, bn=bn, act=act
)
return c
def conv1x1(self, in_planes, out_planes, stride=1, groups=1, bn=False, act=False):
"""1x1 convolution with padding"""
c = self.conv(
1, in_planes, out_planes, groups=groups, stride=stride, bn=bn, act=act
)
return c
def conv7x7(self, in_planes, out_planes, stride=1, groups=1, bn=False, act=False):
"""7x7 convolution with padding"""
c = self.conv(
7, in_planes, out_planes, groups=groups, stride=stride, bn=bn, act=act
)
return c
def conv5x5(self, in_planes, out_planes, stride=1, groups=1, bn=False, act=False):
"""5x5 convolution with padding"""
c = self.conv(
5, in_planes, out_planes, groups=groups, stride=stride, bn=bn, act=act
)
return c
def batchnorm(self, planes, zero_init=False):
bn_cfg = {}
if self.config.bn_momentum is not None:
bn_cfg["momentum"] = self.config.bn_momentum
if self.config.bn_epsilon is not None:
bn_cfg["eps"] = self.config.bn_epsilon
bn = nn.BatchNorm2d(planes, **bn_cfg)
gamma_init_val = 0 if zero_init else 1
nn.init.constant_(bn.weight, gamma_init_val)
nn.init.constant_(bn.bias, 0)
return bn
def activation(self):
return {
"silu": lambda: nn.SiLU(inplace=True),
"relu": lambda: nn.ReLU(inplace=True),
"onnx-silu": ONNXSiLU,
}[self.config.activation]()
# LayerBuilder }}}
# LambdaLayer {{{
class LambdaLayer(nn.Module):
def __init__(self, lmbd):
super().__init__()
self.lmbd = lmbd
def forward(self, x):
return self.lmbd(x)
# }}}
# SqueezeAndExcitation {{{
class SqueezeAndExcitation(nn.Module):
def __init__(self, in_channels, squeeze, activation):
super(SqueezeAndExcitation, self).__init__()
self.squeeze = nn.Linear(in_channels, squeeze)
self.expand = nn.Linear(squeeze, in_channels)
self.activation = activation
self.sigmoid = nn.Sigmoid()
def forward(self, x):
return self._attention(x)
def _attention(self, x):
out = torch.mean(x, [2, 3])
out = self.squeeze(out)
out = self.activation(out)
out = self.expand(out)
out = self.sigmoid(out)
out = out.unsqueeze(2).unsqueeze(3)
return out
class SqueezeAndExcitationTRT(nn.Module):
def __init__(self, in_channels, squeeze, activation):
super(SqueezeAndExcitationTRT, self).__init__()
self.pooling = nn.AdaptiveAvgPool2d(1)
self.squeeze = nn.Conv2d(in_channels, squeeze, 1)
self.expand = nn.Conv2d(squeeze, in_channels, 1)
self.activation = activation
self.sigmoid = nn.Sigmoid()
def forward(self, x):
return self._attention(x)
def _attention(self, x):
out = self.pooling(x)
out = self.squeeze(out)
out = self.activation(out)
out = self.expand(out)
out = self.sigmoid(out)
return out
# }}}
# EMA {{{
class EMA:
def __init__(self, mu, module_ema):
self.mu = mu
self.module_ema = module_ema
def __call__(self, module, step=None):
if step is None:
mu = self.mu
else:
mu = min(self.mu, (1.0 + step) / (10 + step))
def strip_module(s: str) -> str:
return s
mesd = self.module_ema.state_dict()
with torch.no_grad():
for name, x in module.state_dict().items():
if name.endswith("num_batches_tracked"):
continue
n = strip_module(name)
mesd[n].mul_(mu)
mesd[n].add_((1.0 - mu) * x)
# }}}
# ONNXSiLU {{{
# Since torch.nn.SiLU is not supported in ONNX,
# it is required to use this implementation in exported model (15-20% more GPU memory is needed)
class ONNXSiLU(nn.Module):
def __init__(self, *args, **kwargs):
super(ONNXSiLU, self).__init__()
def forward(self, x):
return x * torch.sigmoid(x)
# }}}
class SequentialSqueezeAndExcitation(SqueezeAndExcitation):
def __init__(self, in_channels, squeeze, activation, quantized=False):
super().__init__(in_channels, squeeze, activation)
self.quantized = quantized
if quantized:
assert quant_nn is not None, "pytorch_quantization is not available"
self.mul_a_quantizer = quant_nn.TensorQuantizer(
quant_nn.QuantConv2d.default_quant_desc_input
)
self.mul_b_quantizer = quant_nn.TensorQuantizer(
quant_nn.QuantConv2d.default_quant_desc_input
)
else:
self.mul_a_quantizer = nn.Identity()
self.mul_b_quantizer = nn.Identity()
def forward(self, x):
out = self._attention(x)
if not self.quantized:
return out * x
else:
x_quant = self.mul_a_quantizer(out)
return x_quant * self.mul_b_quantizer(x)
class SequentialSqueezeAndExcitationTRT(SqueezeAndExcitationTRT):
def __init__(self, in_channels, squeeze, activation, quantized=False):
super().__init__(in_channels, squeeze, activation)
self.quantized = quantized
if quantized:
assert quant_nn is not None, "pytorch_quantization is not available"
self.mul_a_quantizer = quant_nn.TensorQuantizer(
quant_nn.QuantConv2d.default_quant_desc_input
)
self.mul_b_quantizer = quant_nn.TensorQuantizer(
quant_nn.QuantConv2d.default_quant_desc_input
)
else:
self.mul_a_quantizer = nn.Identity()
self.mul_b_quantizer = nn.Identity()
def forward(self, x):
out = self._attention(x)
if not self.quantized:
return out * x
else:
x_quant = self.mul_a_quantizer(out)
return x_quant * self.mul_b_quantizer(x)
class StochasticDepthResidual(nn.Module):
def __init__(self, survival_prob: float):
super().__init__()
self.survival_prob = survival_prob
self.register_buffer("mask", torch.ones(()), persistent=False)
def forward(self, residual: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
if not self.training:
return torch.add(residual, other=x)
else:
with torch.no_grad():
mask = F.dropout(
self.mask,
p=1 - self.survival_prob,
training=self.training,
inplace=False,
)
return torch.addcmul(residual, mask, x)
class Flatten(nn.Module):
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x.squeeze(-1).squeeze(-1)
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/models/common.py
|
# Copyright (c) 2018-2019, NVIDIA CORPORATION
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
def nvidia_efficientnet(type='efficient-b0', pretrained=True, **kwargs):
"""Constructs a EfficientNet model.
For detailed information on model input and output, training recipies, inference and performance
visit: github.com/NVIDIA/DeepLearningExamples and/or ngc.nvidia.com
Args:
pretrained (bool, True): If True, returns a model pretrained on IMAGENET dataset.
"""
from .efficientnet import _ce
return _ce(type)(pretrained=pretrained, **kwargs)
def nvidia_convnets_processing_utils():
import numpy as np
import torch
from PIL import Image
import torchvision.transforms as transforms
import numpy as np
import json
import requests
import validators
class Processing:
@staticmethod
def prepare_input_from_uri(uri, cuda=False):
img_transforms = transforms.Compose(
[transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor()]
)
if (validators.url(uri)):
img = Image.open(requests.get(uri, stream=True).raw)
else:
img = Image.open(uri)
img = img_transforms(img)
with torch.no_grad():
# mean and std are not multiplied by 255 as they are in training script
# torch dataloader reads data into bytes whereas loading directly
# through PIL creates a tensor with floats in [0,1] range
mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
img = img.float()
if cuda:
mean = mean.cuda()
std = std.cuda()
img = img.cuda()
input = img.unsqueeze(0).sub_(mean).div_(std)
return input
@staticmethod
def pick_n_best(predictions, n=5):
predictions = predictions.float().cpu().numpy()
topN = np.argsort(-1*predictions, axis=-1)[:,:n]
imgnet_classes = Processing.get_imgnet_classes()
results=[]
for idx,case in enumerate(topN):
r = []
for c, v in zip(imgnet_classes[case], predictions[idx, case]):
r.append((f"{c}", f"{100*v:.1f}%"))
print(f"sample {idx}: {r}")
results.append(r)
return results
@staticmethod
def get_imgnet_classes():
import os
import json
imgnet_classes_json = "LOC_synset_mapping.json"
if not os.path.exists(imgnet_classes_json):
print("Downloading Imagenet Classes names.")
import urllib
urllib.request.urlretrieve(
"https://raw.githubusercontent.com/NVIDIA/DeepLearningExamples/master/PyTorch/Classification/ConvNets/LOC_synset_mapping.json",
filename=imgnet_classes_json)
print("Downloading finished.")
imgnet_classes = np.array(json.load(open(imgnet_classes_json, "r")))
return imgnet_classes
return Processing()
|
DALI-main
|
docs/examples/use_cases/pytorch/efficientnet/image_classification/models/entrypoints.py
|
import os
import sys
import time
from argparse import ArgumentParser
import math
import numpy as np
import time
import torch
from torch.optim.lr_scheduler import MultiStepLR
import torch.utils.data.distributed
from src.model import model, Loss
from src.utils import dboxes300_coco, Encoder
from src.evaluate import evaluate
from src.train import train_loop, tencent_trick
from src.data import *
class Logger:
def __init__(self, batch_size, local_rank, n_gpu, print_freq=20):
self.batch_size = batch_size
self.local_rank = local_rank
self.n_gpu = n_gpu
self.print_freq = print_freq
self.processed_samples = 0
self.epochs_times = []
self.epochs_speeds = []
def update_iter(self, epoch, iteration, loss):
if self.local_rank != 0:
return
if iteration % self.print_freq == 0:
print('Epoch: {:2d}, Iteration: {}, Loss: {}'.format(epoch, iteration, loss))
self.processed_samples = self.processed_samples + self.batch_size
def start_epoch(self):
self.epoch_start = time.time()
def end_epoch(self):
epoch_time = time.time() - self.epoch_start
epoch_speed = self.processed_samples / epoch_time
self.epochs_times.append(epoch_time)
self.epochs_speeds.append(epoch_speed)
self.processed_samples = 0
if self.local_rank == 0:
print('Epoch {:2d} finished. Time: {:4f} s, Speed: {:4f} img/sec, Average speed: {:4f}'
.format(len(self.epochs_times)-1, epoch_time, epoch_speed * self.n_gpu, self.average_speed() * self.n_gpu))
def average_speed(self):
return sum(self.epochs_speeds) / len(self.epochs_speeds)
def make_parser():
parser = ArgumentParser(
description="Train Single Shot MultiBox Detector on COCO")
parser.add_argument(
'--data', '-d', type=str, default='/coco', required=True,
help='path to test and training data files')
parser.add_argument(
'--epochs', '-e', type=int, default=65,
help='number of epochs for training')
parser.add_argument(
'--batch-size', '--bs', type=int, default=32,
help='number of examples for each iteration')
parser.add_argument(
'--eval-batch-size', '--ebs', type=int, default=32,
help='number of examples for each evaluation iteration')
parser.add_argument(
'--seed', '-s', type=int, default=0,
help='manually set random seed for torch')
parser.add_argument(
'--evaluation', nargs='*', type=int,
default=[3, 21, 31, 37, 42, 48, 53, 59, 64],
help='epochs at which to evaluate')
parser.add_argument(
'--multistep', nargs='*', type=int, default=[43, 54],
help='epochs at which to decay learning rate')
parser.add_argument(
'--target', type=float, default=None,
help='target mAP to assert against at the end')
# Hyperparameters
parser.add_argument(
'--learning-rate', '--lr', type=float, default=2.6e-3, help='learning rate')
parser.add_argument(
'--momentum', '-m', type=float, default=0.9,
help='momentum argument for SGD optimizer')
parser.add_argument(
'--weight-decay', '--wd', type=float, default=0.0005,
help='momentum argument for SGD optimizer')
parser.add_argument('--warmup', type=int, default=None)
parser.add_argument(
'--backbone', type=str, default='resnet50',
choices=['resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'])
parser.add_argument('--num-workers', type=int, default=4)
parser.add_argument('--fp16-mode', default=True, action='store_true',
help='Enable half precision mode')
# Pipeline control
parser.add_argument(
'--data_pipeline', type=str, default='dali', choices=['dali', 'no_dali'],
help='data preprocessing pipeline to use')
return parser
def train(args):
args.distributed = False
if 'WORLD_SIZE' in os.environ:
args.distributed = int(os.environ['WORLD_SIZE']) > 1
if args.distributed:
torch.cuda.set_device(args.local_rank)
torch.distributed.init_process_group(backend='nccl', init_method='env://')
args.N_gpu = torch.distributed.get_world_size()
else:
args.N_gpu = 1
dboxes = dboxes300_coco()
encoder = Encoder(dboxes)
cocoGt = get_coco_ground_truth(args)
ssd300 = model(args)
args.learning_rate = args.learning_rate * args.N_gpu * (args.batch_size / 32)
iteration = 0
loss_func = Loss(dboxes)
loss_func.cuda()
optimizer = torch.optim.SGD(
tencent_trick(ssd300),
lr=args.learning_rate,
momentum=args.momentum,
weight_decay=args.weight_decay)
scheduler = MultiStepLR(
optimizer=optimizer,
milestones=args.multistep,
gamma=0.1)
scaler = torch.cuda.amp.GradScaler(enabled=args.fp16_mode)
val_dataloader, inv_map = get_val_dataloader(args)
train_loader = get_train_loader(args, dboxes)
acc = 0
logger = Logger(args.batch_size, args.local_rank, args.N_gpu)
for epoch in range(0, args.epochs):
logger.start_epoch()
scheduler.step()
iteration = train_loop(
ssd300, loss_func, scaler, epoch, optimizer,
train_loader, iteration, logger, args)
logger.end_epoch()
if epoch in args.evaluation:
acc = evaluate(ssd300, val_dataloader, cocoGt, encoder, inv_map, args)
if args.local_rank == 0:
print('Epoch {:2d}, Accuracy: {:4f} mAP'.format(epoch, acc))
return acc, logger.average_speed()
if __name__ == "__main__":
parser = make_parser()
args = parser.parse_args()
if 'LOCAL_RANK' in os.environ:
args.local_rank = int(os.environ['LOCAL_RANK'])
else:
args.local_rank = 0
if args.local_rank == 0:
os.makedirs('./models', exist_ok=True)
torch.backends.cudnn.benchmark = True
start_time = time.time()
acc, avg_speed = train(args)
# avg_speed is reported per node, adjust for the global speed
try:
num_shards = torch.distributed.get_world_size()
except RuntimeError:
num_shards = 1
avg_speed = num_shards * avg_speed
training_time = time.time() - start_time
if args.local_rank == 0:
print("Training end: Average speed: {:3f} img/sec, Total time: {:3f} sec, Final accuracy: {:3f} mAP"
.format(avg_speed, training_time, acc))
if args.target is not None:
if args.target > acc:
print('Target mAP of {} not met. Possible regression'.format(args.target))
sys.exit(1)
|
DALI-main
|
docs/examples/use_cases/pytorch/single_stage_detector/main.py
|
__author__ = 'tylin'
__version__ = '2.0'
# Interface for accessing the Microsoft COCO dataset.
# Microsoft COCO is a large image dataset designed for object detection,
# segmentation, and caption generation. pycocotools is a Python API that
# assists in loading, parsing and visualizing the annotations in COCO.
# Please visit http://mscoco.org/ for more information on COCO, including
# for the data, paper, and tutorials. The exact format of the annotations
# is also described on the COCO website. For example usage of the pycocotools
# please see pycocotools_demo.ipynb. In addition to this API, please download both
# the COCO images and annotations in order to run the demo.
# An alternative to using the API is to load the annotations directly
# into Python dictionary
# Using the API provides additional utility functions. Note that this API
# supports both *instance* and *caption* annotations. In the case of
# captions not all functions are defined (e.g. categories are undefined).
# The following API functions are defined:
# COCO - COCO api class that loads COCO annotation file and prepare data structures.
# decodeMask - Decode binary mask M encoded via run-length encoding.
# encodeMask - Encode binary mask M using run-length encoding.
# getAnnIds - Get ann ids that satisfy given filter conditions.
# getCatIds - Get cat ids that satisfy given filter conditions.
# getImgIds - Get img ids that satisfy given filter conditions.
# loadAnns - Load anns with the specified ids.
# loadCats - Load cats with the specified ids.
# loadImgs - Load imgs with the specified ids.
# annToMask - Convert segmentation in an annotation to binary mask.
# showAnns - Display the specified annotations.
# loadRes - Load algorithm results and create API for accessing them.
# download - Download COCO images from mscoco.org server.
# Throughout the API "ann"=annotation, "cat"=category, and "img"=image.
# Help on each functions can be accessed by: "help COCO>function".
# See also COCO>decodeMask,
# COCO>encodeMask, COCO>getAnnIds, COCO>getCatIds,
# COCO>getImgIds, COCO>loadAnns, COCO>loadCats,
# COCO>loadImgs, COCO>annToMask, COCO>showAnns
# Microsoft COCO Toolbox. version 2.0
# Data, paper, and tutorials available at: http://mscoco.org/
# Code written by Piotr Dollar and Tsung-Yi Lin, 2014.
# Licensed under the Simplified BSD License [see bsd.txt]
import json
import time
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
import numpy as np
import copy
import itertools
from pycocotools import mask as maskUtils
import os
from collections import defaultdict
import sys
PYTHON_VERSION = sys.version_info[0]
if PYTHON_VERSION == 2:
from urllib import urlretrieve
elif PYTHON_VERSION == 3:
from urllib.request import urlretrieve
def _isArrayLike(obj):
return hasattr(obj, '__iter__') and hasattr(obj, '__len__')
class COCO:
def __init__(self, annotation_file=None):
"""
Constructor of Microsoft COCO helper class for reading and visualizing annotations.
:param annotation_file (str): location of annotation file
:param image_folder (str): location to the folder that hosts images.
:return:
"""
# load dataset
self.dataset,self.anns,self.cats,self.imgs = dict(),dict(),dict(),dict()
self.imgToAnns, self.catToImgs = defaultdict(list), defaultdict(list)
if not annotation_file == None:
print('loading annotations into memory...')
tic = time.time()
dataset = json.load(open(annotation_file, 'r'))
assert type(dataset)==dict, 'annotation file format {} not supported'.format(type(dataset))
print('Done (t={:0.2f}s)'.format(time.time()- tic))
self.dataset = dataset
self.createIndex()
def createIndex(self):
# create index
print('creating index...')
anns, cats, imgs = {}, {}, {}
imgToAnns,catToImgs = defaultdict(list),defaultdict(list)
if 'annotations' in self.dataset:
for ann in self.dataset['annotations']:
imgToAnns[ann['image_id']].append(ann)
anns[ann['id']] = ann
if 'images' in self.dataset:
for img in self.dataset['images']:
imgs[img['id']] = img
if 'categories' in self.dataset:
for cat in self.dataset['categories']:
cats[cat['id']] = cat
if 'annotations' in self.dataset and 'categories' in self.dataset:
for ann in self.dataset['annotations']:
catToImgs[ann['category_id']].append(ann['image_id'])
print('index created!')
# create class members
self.anns = anns
self.imgToAnns = imgToAnns
self.catToImgs = catToImgs
self.imgs = imgs
self.cats = cats
def info(self):
"""
Print information about the annotation file.
:return:
"""
for key, value in self.dataset['info'].items():
print('{}: {}'.format(key, value))
def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None):
"""
Get ann ids that satisfy given filter conditions. default skips that filter
:param imgIds (int array) : get anns for given imgs
catIds (int array) : get anns for given cats
areaRng (float array) : get anns for given area range (e.g. [0 inf])
iscrowd (boolean) : get anns for given crowd label (False or True)
:return: ids (int array) : integer array of ann ids
"""
imgIds = imgIds if _isArrayLike(imgIds) else [imgIds]
catIds = catIds if _isArrayLike(catIds) else [catIds]
if len(imgIds) == len(catIds) == len(areaRng) == 0:
anns = self.dataset['annotations']
else:
if not len(imgIds) == 0:
lists = [self.imgToAnns[imgId] for imgId in imgIds if imgId in self.imgToAnns]
anns = list(itertools.chain.from_iterable(lists))
else:
anns = self.dataset['annotations']
anns = anns if len(catIds) == 0 else [ann for ann in anns if ann['category_id'] in catIds]
anns = anns if len(areaRng) == 0 else [ann for ann in anns if ann['area'] > areaRng[0] and ann['area'] < areaRng[1]]
if not iscrowd == None:
ids = [ann['id'] for ann in anns if ann['iscrowd'] == iscrowd]
else:
ids = [ann['id'] for ann in anns]
return ids
def getCatIds(self, catNms=[], supNms=[], catIds=[]):
"""
filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given cat ids
:return: ids (int array) : integer array of cat ids
"""
catNms = catNms if _isArrayLike(catNms) else [catNms]
supNms = supNms if _isArrayLike(supNms) else [supNms]
catIds = catIds if _isArrayLike(catIds) else [catIds]
if len(catNms) == len(supNms) == len(catIds) == 0:
cats = self.dataset['categories']
else:
cats = self.dataset['categories']
cats = cats if len(catNms) == 0 else [cat for cat in cats if cat['name'] in catNms]
cats = cats if len(supNms) == 0 else [cat for cat in cats if cat['supercategory'] in supNms]
cats = cats if len(catIds) == 0 else [cat for cat in cats if cat['id'] in catIds]
ids = [cat['id'] for cat in cats]
return ids
def getImgIds(self, imgIds=[], catIds=[]):
'''
Get img ids that satisfy given filter conditions.
:param imgIds (int array) : get imgs for given ids
:param catIds (int array) : get imgs with all given cats
:return: ids (int array) : integer array of img ids
'''
imgIds = imgIds if _isArrayLike(imgIds) else [imgIds]
catIds = catIds if _isArrayLike(catIds) else [catIds]
if len(imgIds) == len(catIds) == 0:
ids = self.imgs.keys()
else:
ids = set(imgIds)
for i, catId in enumerate(catIds):
if i == 0 and len(ids) == 0:
ids = set(self.catToImgs[catId])
else:
ids &= set(self.catToImgs[catId])
return list(ids)
def loadAnns(self, ids=[]):
"""
Load anns with the specified ids.
:param ids (int array) : integer ids specifying anns
:return: anns (object array) : loaded ann objects
"""
if _isArrayLike(ids):
return [self.anns[id] for id in ids]
elif type(ids) == int:
return [self.anns[ids]]
def loadCats(self, ids=[]):
"""
Load cats with the specified ids.
:param ids (int array) : integer ids specifying cats
:return: cats (object array) : loaded cat objects
"""
if _isArrayLike(ids):
return [self.cats[id] for id in ids]
elif type(ids) == int:
return [self.cats[ids]]
def loadImgs(self, ids=[]):
"""
Load anns with the specified ids.
:param ids (int array) : integer ids specifying img
:return: imgs (object array) : loaded img objects
"""
if _isArrayLike(ids):
return [self.imgs[id] for id in ids]
elif type(ids) == int:
return [self.imgs[ids]]
def showAnns(self, anns):
"""
Display the specified annotations.
:param anns (array of object): annotations to display
:return: None
"""
if len(anns) == 0:
return 0
if 'segmentation' in anns[0] or 'keypoints' in anns[0]:
datasetType = 'instances'
elif 'caption' in anns[0]:
datasetType = 'captions'
else:
raise Exception('datasetType not supported')
if datasetType == 'instances':
ax = plt.gca()
ax.set_autoscale_on(False)
polygons = []
color = []
for ann in anns:
c = (np.random.random((1, 3))*0.6+0.4).tolist()[0]
if 'segmentation' in ann:
if type(ann['segmentation']) == list:
# polygon
for seg in ann['segmentation']:
poly = np.array(seg).reshape((int(len(seg)/2), 2))
polygons.append(Polygon(poly))
color.append(c)
else:
# mask
t = self.imgs[ann['image_id']]
if type(ann['segmentation']['counts']) == list:
rle = maskUtils.frPyObjects([ann['segmentation']], t['height'], t['width'])
else:
rle = [ann['segmentation']]
m = maskUtils.decode(rle)
img = np.ones( (m.shape[0], m.shape[1], 3) )
if ann['iscrowd'] == 1:
color_mask = np.array([2.0,166.0,101.0])/255
if ann['iscrowd'] == 0:
color_mask = np.random.random((1, 3)).tolist()[0]
for i in range(3):
img[:,:,i] = color_mask[i]
ax.imshow(np.dstack( (img, m*0.5) ))
if 'keypoints' in ann and type(ann['keypoints']) == list:
# turn skeleton into zero-based index
sks = np.array(self.loadCats(ann['category_id'])[0]['skeleton'])-1
kp = np.array(ann['keypoints'])
x = kp[0::3]
y = kp[1::3]
v = kp[2::3]
for sk in sks:
if np.all(v[sk]>0):
plt.plot(x[sk],y[sk], linewidth=3, color=c)
plt.plot(x[v>0], y[v>0],'o',markersize=8, markerfacecolor=c, markeredgecolor='k',markeredgewidth=2)
plt.plot(x[v>1], y[v>1],'o',markersize=8, markerfacecolor=c, markeredgecolor=c, markeredgewidth=2)
p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.4)
ax.add_collection(p)
p = PatchCollection(polygons, facecolor='none', edgecolors=color, linewidths=2)
ax.add_collection(p)
elif datasetType == 'captions':
for ann in anns:
print(ann['caption'])
def loadRes(self, resFile):
"""
Load result file and return a result api object.
:param resFile (str) : file name of result file
:return: res (obj) : result api object
"""
res = COCO()
res.dataset['images'] = [img for img in self.dataset['images']]
print('Loading and preparing results...')
tic = time.time()
if type(resFile) == str: #or type(resFile) == unicode:
anns = json.load(open(resFile))
elif type(resFile) == np.ndarray:
anns = self.loadNumpyAnnotations(resFile)
else:
anns = resFile
assert type(anns) == list, 'results in not an array of objects'
annsImgIds = [ann['image_id'] for ann in anns]
assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \
'Results do not correspond to current coco set'
if 'caption' in anns[0]:
imgIds = set([img['id'] for img in res.dataset['images']]) & set([ann['image_id'] for ann in anns])
res.dataset['images'] = [img for img in res.dataset['images'] if img['id'] in imgIds]
for id, ann in enumerate(anns):
ann['id'] = id+1
elif 'bbox' in anns[0] and not anns[0]['bbox'] == []:
res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
for id, ann in enumerate(anns):
bb = ann['bbox']
x1, x2, y1, y2 = [bb[0], bb[0]+bb[2], bb[1], bb[1]+bb[3]]
if not 'segmentation' in ann:
ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]]
ann['area'] = bb[2]*bb[3]
ann['id'] = id+1
ann['iscrowd'] = 0
elif 'segmentation' in anns[0]:
res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
for id, ann in enumerate(anns):
# now only support compressed RLE format as segmentation results
ann['area'] = maskUtils.area(ann['segmentation'])
if not 'bbox' in ann:
ann['bbox'] = maskUtils.toBbox(ann['segmentation'])
ann['id'] = id+1
ann['iscrowd'] = 0
elif 'keypoints' in anns[0]:
res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
for id, ann in enumerate(anns):
s = ann['keypoints']
x = s[0::3]
y = s[1::3]
x0,x1,y0,y1 = np.min(x), np.max(x), np.min(y), np.max(y)
ann['area'] = (x1-x0)*(y1-y0)
ann['id'] = id + 1
ann['bbox'] = [x0,y0,x1-x0,y1-y0]
print('DONE (t={:0.2f}s)'.format(time.time()- tic))
res.dataset['annotations'] = anns
res.createIndex()
return res
def download(self, tarDir = None, imgIds = [] ):
'''
Download COCO images from mscoco.org server.
:param tarDir (str): COCO results directory name
imgIds (list): images to be downloaded
:return:
'''
if tarDir is None:
print('Please specify target directory')
return -1
if len(imgIds) == 0:
imgs = self.imgs.values()
else:
imgs = self.loadImgs(imgIds)
N = len(imgs)
if not os.path.exists(tarDir):
os.makedirs(tarDir)
for i, img in enumerate(imgs):
tic = time.time()
fname = os.path.join(tarDir, img['file_name'])
if not os.path.exists(fname):
urlretrieve(img['coco_url'], fname)
print('downloaded {}/{} images (t={:0.1f}s)'.format(i, N, time.time()- tic))
def loadNumpyAnnotations(self, data):
"""
Convert result data from a numpy array [Nx7] where each row contains {imageID,x1,y1,w,h,score,class}
:param data (numpy.ndarray)
:return: annotations (python nested list)
"""
print('Converting ndarray to lists...')
assert(type(data) == np.ndarray)
print(data.shape)
assert(data.shape[1] == 7)
N = data.shape[0]
ann = []
for i in range(N):
if i % 1000000 == 0:
print('{}/{}'.format(i,N))
ann += [{
'image_id' : int(data[i, 0]),
'bbox' : [ data[i, 1], data[i, 2], data[i, 3], data[i, 4] ],
'score' : data[i, 5],
'category_id': int(data[i, 6]),
}]
return ann
def annToRLE(self, ann):
"""
Convert annotation which can be polygons, uncompressed RLE to RLE.
:return: binary mask (numpy 2D array)
"""
t = self.imgs[ann['image_id']]
h, w = t['height'], t['width']
segm = ann['segmentation']
if type(segm) == list:
# polygon -- a single object might consist of multiple parts
# we merge all parts into one mask rle code
rles = maskUtils.frPyObjects(segm, h, w)
rle = maskUtils.merge(rles)
elif type(segm['counts']) == list:
# uncompressed RLE
rle = maskUtils.frPyObjects(segm, h, w)
else:
# rle
rle = ann['segmentation']
return rle
def annToMask(self, ann):
"""
Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask.
:return: binary mask (numpy 2D array)
"""
rle = self.annToRLE(ann)
m = maskUtils.decode(rle)
return m
|
DALI-main
|
docs/examples/use_cases/pytorch/single_stage_detector/src/coco.py
|
# Copyright (c) 2018-2021, NVIDIA CORPORATION & AFFILIATES. 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 torch
from nvidia.dali.pipeline import pipeline_def
import nvidia.dali.types as types
import nvidia.dali.fn as fn
@pipeline_def
def create_coco_pipeline(default_boxes, args):
try:
shard_id = torch.distributed.get_rank()
num_shards = torch.distributed.get_world_size()
except RuntimeError:
shard_id = 0
num_shards = 1
images, bboxes, labels = fn.readers.coco(file_root=args.train_coco_root,
annotations_file=args.train_annotate,
skip_empty=True,
shard_id=shard_id,
num_shards=num_shards,
ratio=True,
ltrb=True,
random_shuffle=False,
shuffle_after_epoch=True,
name="Reader")
crop_begin, crop_size, bboxes, labels = fn.random_bbox_crop(bboxes, labels,
device="cpu",
aspect_ratio=[0.5, 2.0],
thresholds=[0, 0.1, 0.3, 0.5, 0.7, 0.9],
scaling=[0.3, 1.0],
bbox_layout="xyXY",
allow_no_crop=True,
num_attempts=50)
images = fn.decoders.image_slice(images, crop_begin, crop_size, device="mixed", output_type=types.RGB)
flip_coin = fn.random.coin_flip(probability=0.5)
images = fn.resize(images,
resize_x=300,
resize_y=300,
min_filter=types.DALIInterpType.INTERP_TRIANGULAR)
saturation = fn.random.uniform(range=[0.5, 1.5])
contrast = fn.random.uniform(range=[0.5, 1.5])
brightness = fn.random.uniform(range=[0.875, 1.125])
hue = fn.random.uniform(range=[-0.5, 0.5])
images = fn.hsv(images, dtype=types.FLOAT, hue=hue, saturation=saturation) # use float to avoid clipping and
# quantizing the intermediate result
images = fn.brightness_contrast(images,
contrast_center = 128, # input is in float, but in 0..255 range
dtype = types.UINT8,
brightness = brightness,
contrast = contrast)
dtype = types.FLOAT16 if args.fp16_mode else types.FLOAT
bboxes = fn.bb_flip(bboxes, ltrb=True, horizontal=flip_coin)
images = fn.crop_mirror_normalize(images,
crop=(300, 300),
mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255],
mirror=flip_coin,
dtype=dtype,
output_layout="CHW",
pad_output=False)
bboxes, labels = fn.box_encoder(bboxes, labels,
criteria=0.5,
anchors=default_boxes.as_ltrb_list())
labels=labels.gpu()
bboxes=bboxes.gpu()
return images, bboxes, labels
|
DALI-main
|
docs/examples/use_cases/pytorch/single_stage_detector/src/coco_pipeline.py
|
DALI-main
|
docs/examples/use_cases/pytorch/single_stage_detector/src/__init__.py
|
|
import torch
import torch.nn as nn
from torchvision.models.resnet import resnet18, resnet34, resnet50, resnet101, resnet152
from torch.nn.parallel import DistributedDataParallel as DDP
class ResNet(nn.Module):
def __init__(self, backbone='resnet50'):
super().__init__()
if backbone == 'resnet18':
backbone = resnet18(pretrained=True)
self.out_channels = [256, 512, 512, 256, 256, 128]
elif backbone == 'resnet34':
backbone = resnet34(pretrained=True)
self.out_channels = [256, 512, 512, 256, 256, 256]
elif backbone == 'resnet50':
backbone = resnet50(pretrained=True)
self.out_channels = [1024, 512, 512, 256, 256, 256]
elif backbone == 'resnet101':
backbone = resnet101(pretrained=True)
self.out_channels = [1024, 512, 512, 256, 256, 256]
else: # backbone == 'resnet152':
backbone = resnet152(pretrained=True)
self.out_channels = [1024, 512, 512, 256, 256, 256]
self.feature_extractor = nn.Sequential(*list(backbone.children())[:7])
conv4_block1 = self.feature_extractor[-1][0]
conv4_block1.conv1.stride = (1, 1)
conv4_block1.conv2.stride = (1, 1)
conv4_block1.downsample[0].stride = (1, 1)
def forward(self, x):
x = self.feature_extractor(x)
return x
class SSD300(nn.Module):
def __init__(self, backbone='resnet50'):
super().__init__()
self.feature_extractor = ResNet(backbone=backbone)
self.label_num = 81 # number of COCO classes
self._build_additional_features(self.feature_extractor.out_channels)
self.num_defaults = [4, 6, 6, 6, 4, 4]
self.loc = []
self.conf = []
for nd, oc in zip(self.num_defaults, self.feature_extractor.out_channels):
self.loc.append(nn.Conv2d(oc, nd * 4, kernel_size=3, padding=1))
self.conf.append(nn.Conv2d(oc, nd * self.label_num, kernel_size=3, padding=1))
self.loc = nn.ModuleList(self.loc)
self.conf = nn.ModuleList(self.conf)
self._init_weights()
def _build_additional_features(self, input_size):
self.additional_blocks = []
for i, (input_size, output_size, channels) in enumerate(zip(input_size[:-1], input_size[1:], [256, 256, 128, 128, 128])):
if i < 3:
layer = nn.Sequential(
nn.Conv2d(input_size, channels, kernel_size=1, bias=False),
nn.BatchNorm2d(channels),
nn.ReLU(inplace=True),
nn.Conv2d(channels, output_size, kernel_size=3, padding=1, stride=2, bias=False),
nn.BatchNorm2d(output_size),
nn.ReLU(inplace=True),
)
else:
layer = nn.Sequential(
nn.Conv2d(input_size, channels, kernel_size=1, bias=False),
nn.BatchNorm2d(channels),
nn.ReLU(inplace=True),
nn.Conv2d(channels, output_size, kernel_size=3, bias=False),
nn.BatchNorm2d(output_size),
nn.ReLU(inplace=True),
)
self.additional_blocks.append(layer)
self.additional_blocks = nn.ModuleList(self.additional_blocks)
def _init_weights(self):
layers = [*self.additional_blocks, *self.loc, *self.conf]
for layer in layers:
for param in layer.parameters():
if param.dim() > 1: nn.init.xavier_uniform_(param)
# Shape the classifier to the view of bboxes
def bbox_view(self, src, loc, conf):
ret = []
for s, l, c in zip(src, loc, conf):
ret.append((l(s).view(s.size(0), 4, -1), c(s).view(s.size(0), self.label_num, -1)))
locs, confs = list(zip(*ret))
locs, confs = torch.cat(locs, 2).contiguous(), torch.cat(confs, 2).contiguous()
return locs, confs
def forward(self, x):
x = self.feature_extractor(x)
detection_feed = [x]
for l in self.additional_blocks:
x = l(x)
detection_feed.append(x)
# Feature Map 38x38x4, 19x19x6, 10x10x6, 5x5x6, 3x3x4, 1x1x4
locs, confs = self.bbox_view(detection_feed, self.loc, self.conf)
# For SSD 300, shall return nbatch x 8732 x {nlabels, nlocs} results
return locs, confs
def model(args):
ssd300 = SSD300(backbone=args.backbone)
ssd300.cuda()
if args.distributed:
ssd300 = DDP(ssd300, device_ids=[args.local_rank], output_device=args.local_rank)
return ssd300
class Loss(nn.Module):
"""
Implements the loss as the sum of the followings:
1. Confidence Loss: All labels, with hard negative mining
2. Localization Loss: Only on positive labels
Suppose input dboxes has the shape 8732x4
"""
def __init__(self, dboxes):
super(Loss, self).__init__()
self.scale_xy = 1.0/dboxes.scale_xy
self.scale_wh = 1.0/dboxes.scale_wh
self.sl1_loss = nn.SmoothL1Loss(reduction="none")
self.dboxes = nn.Parameter(dboxes(order="xywh").transpose(0, 1).unsqueeze(dim = 0),
requires_grad=False)
# Two factor are from following links
# http://jany.st/post/2017-11-05-single-shot-detector-ssd-from-scratch-in-tensorflow.html
self.con_loss = nn.CrossEntropyLoss(reduction="none")
def _loc_vec(self, loc):
"""
Generate Location Vectors
"""
gxy = self.scale_xy*(loc[:, :2, :] - self.dboxes[:, :2, :])/self.dboxes[:, 2:, ]
gwh = self.scale_wh*(loc[:, 2:, :]/self.dboxes[:, 2:, :]).log()
return torch.cat((gxy, gwh), dim=1).contiguous()
def forward(self, ploc, plabel, gloc, glabel):
"""
ploc, plabel: Nx4x8732, Nxlabel_numx8732
predicted location and labels
gloc, glabel: Nx4x8732, Nx8732
ground truth location and labels
"""
mask = glabel > 0
pos_num = mask.sum(dim=1)
vec_gd = self._loc_vec(gloc)
# sum on four coordinates, and mask
sl1 = self.sl1_loss(ploc, vec_gd).sum(dim=1)
sl1 = (mask.float()*sl1).sum(dim=1)
# hard negative mining
con = self.con_loss(plabel, glabel)
# postive mask will never selected
con_neg = con.clone()
con_neg[mask] = 0
_, con_idx = con_neg.sort(dim=1, descending=True)
_, con_rank = con_idx.sort(dim=1)
# number of negative three times positive
neg_num = torch.clamp(3*pos_num, max=mask.size(1)).unsqueeze(-1)
neg_mask = con_rank < neg_num
#print(con.shape, mask.shape, neg_mask.shape)
closs = (con*(mask.float() + neg_mask.float())).sum(dim=1)
# avoid no object detected
total_loss = sl1 + closs
num_mask = (pos_num > 0).float()
pos_num = pos_num.float().clamp(min=1e-6)
ret = (total_loss*num_mask/pos_num).mean(dim=0)
return ret
|
DALI-main
|
docs/examples/use_cases/pytorch/single_stage_detector/src/model.py
|
import torch
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
import torch.distributed as dist
from torch.nn.modules import Module
'''
This version of DistributedDataParallel is designed to be used in conjunction with the multiproc.py
launcher included with this example. It assumes that your run is using multiprocess with 1
GPU/process, that the model is on the correct device, and that torch.set_device has been
used to set the device.
Parameters are broadcasted to the other processes on initialization of DistributedDataParallel,
and will be allreduced at the finish of the backward pass.
'''
class DistributedDataParallel(Module):
def __init__(self, module):
super(DistributedDataParallel, self).__init__()
self.warn_on_half = True if dist._backend == dist.dist_backend.GLOO else False
self.module = module
for p in self.module.state_dict().values():
if not torch.is_tensor(p):
continue
if dist._backend == dist.dist_backend.NCCL:
assert p.is_cuda, "NCCL backend only supports model parameters to be on GPU."
dist.broadcast(p, 0)
def allreduce_params():
if(self.needs_reduction):
self.needs_reduction = False
buckets = {}
for param in self.module.parameters():
if param.requires_grad and param.grad is not None:
tp = param.data.type()
if tp not in buckets:
buckets[tp] = []
buckets[tp].append(param)
if self.warn_on_half:
if torch.cuda.HalfTensor in buckets:
print("WARNING: gloo dist backend for half parameters may be extremely slow." +
" It is recommended to use the NCCL backend in this case.")
self.warn_on_half = False
for tp in buckets:
bucket = buckets[tp]
grads = [param.grad.data for param in bucket]
coalesced = _flatten_dense_tensors(grads)
dist.all_reduce(coalesced)
coalesced /= dist.get_world_size()
for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)):
buf.copy_(synced)
for param in list(self.module.parameters()):
def allreduce_hook(*unused):
param._execution_engine.queue_callback(allreduce_params)
if param.requires_grad:
param.register_hook(allreduce_hook)
def forward(self, *inputs, **kwargs):
self.needs_reduction = True
return self.module(*inputs, **kwargs)
'''
def _sync_buffers(self):
buffers = list(self.module._all_buffers())
if len(buffers) > 0:
# cross-node buffer sync
flat_buffers = _flatten_dense_tensors(buffers)
dist.broadcast(flat_buffers, 0)
for buf, synced in zip(buffers, _unflatten_dense_tensors(flat_buffers, buffers)):
buf.copy_(synced)
def train(self, mode=True):
# Clear NCCL communicator and CUDA event cache of the default group ID,
# These cache will be recreated at the later call. This is currently a
# work-around for a potential NCCL deadlock.
if dist._backend == dist.dist_backend.NCCL:
dist._clear_group_cache()
super(DistributedDataParallel, self).train(mode)
self.module.train(mode)
'''
|
DALI-main
|
docs/examples/use_cases/pytorch/single_stage_detector/src/distributed.py
|
import torch
import torchvision.transforms as transforms
import torch.utils.data as data
from PIL import Image
import os
import numpy as np
import random
import itertools
import torch.nn.functional as F
import json
import time
import bz2
import pickle
from math import sqrt
# from src.coco_pipeline import COCOReaderPipeline
# This function is from https://github.com/kuangliu/pytorch-ssd.
def calc_iou_tensor(box1, box2):
""" Calculation of IoU based on two boxes tensor,
Reference to https://github.com/kuangliu/pytorch-src
input:
box1 (N, 4)
box2 (M, 4)
output:
IoU (N, M)
"""
N = box1.size(0)
M = box2.size(0)
be1 = box1.unsqueeze(1).expand(-1, M, -1)
be2 = box2.unsqueeze(0).expand(N, -1, -1)
# Left Top & Right Bottom
lt = torch.max(be1[:,:,:2], be2[:,:,:2])
#mask1 = (be1[:,:, 0] < be2[:,:, 0]) ^ (be1[:,:, 1] < be2[:,:, 1])
#mask1 = ~mask1
rb = torch.min(be1[:,:,2:], be2[:,:,2:])
#mask2 = (be1[:,:, 2] < be2[:,:, 2]) ^ (be1[:,:, 3] < be2[:,:, 3])
#mask2 = ~mask2
delta = rb - lt
delta[delta < 0] = 0
intersect = delta[:,:,0]*delta[:,:,1]
#*mask1.float()*mask2.float()
delta1 = be1[:,:,2:] - be1[:,:,:2]
area1 = delta1[:,:,0]*delta1[:,:,1]
delta2 = be2[:,:,2:] - be2[:,:,:2]
area2 = delta2[:,:,0]*delta2[:,:,1]
iou = intersect/(area1 + area2 - intersect)
return iou
# This function is from https://github.com/kuangliu/pytorch-ssd.
class Encoder(object):
"""
Inspired by https://github.com/kuangliu/pytorch-src
Transform between (bboxes, lables) <-> SSD output
dboxes: default boxes in size 8732 x 4,
encoder: input ltrb format, output xywh format
decoder: input xywh format, output ltrb format
encode:
input : bboxes_in (Tensor nboxes x 4), labels_in (Tensor nboxes)
output : bboxes_out (Tensor 8732 x 4), labels_out (Tensor 8732)
criteria : IoU threshold of bboexes
decode:
input : bboxes_in (Tensor 8732 x 4), scores_in (Tensor 8732 x nitems)
output : bboxes_out (Tensor nboxes x 4), labels_out (Tensor nboxes)
criteria : IoU threshold of bboexes
max_output : maximum number of output bboxes
"""
def __init__(self, dboxes):
self.dboxes = dboxes(order="ltrb")
self.dboxes_xywh = dboxes(order="xywh").unsqueeze(dim=0)
self.nboxes = self.dboxes.size(0)
#print("# Bounding boxes: {}".format(self.nboxes))
self.scale_xy = dboxes.scale_xy
self.scale_wh = dboxes.scale_wh
def encode(self, bboxes_in, labels_in, criteria = 0.5):
ious = calc_iou_tensor(bboxes_in, self.dboxes)
best_dbox_ious, best_dbox_idx = ious.max(dim=0)
best_bbox_ious, best_bbox_idx = ious.max(dim=1)
# set best ious 2.0
best_dbox_ious.index_fill_(0, best_bbox_idx, 2.0)
idx = torch.arange(0, best_bbox_idx.size(0), dtype=torch.int64)
best_dbox_idx[best_bbox_idx[idx]] = idx
# filter IoU > 0.5
masks = best_dbox_ious > criteria
labels_out = torch.zeros(self.nboxes, dtype=torch.long)
#print(maxloc.shape, labels_in.shape, labels_out.shape)
labels_out[masks] = labels_in[best_dbox_idx[masks]]
bboxes_out = self.dboxes.clone()
bboxes_out[masks, :] = bboxes_in[best_dbox_idx[masks], :]
# Transform format to xywh format
x, y, w, h = 0.5*(bboxes_out[:, 0] + bboxes_out[:, 2]), \
0.5*(bboxes_out[:, 1] + bboxes_out[:, 3]), \
-bboxes_out[:, 0] + bboxes_out[:, 2], \
-bboxes_out[:, 1] + bboxes_out[:, 3]
bboxes_out[:, 0] = x
bboxes_out[:, 1] = y
bboxes_out[:, 2] = w
bboxes_out[:, 3] = h
return bboxes_out, labels_out
def scale_back_batch(self, bboxes_in, scores_in):
"""
Do scale and transform from xywh to ltrb
suppose input Nx4xnum_bbox Nxlabel_numxnum_bbox
"""
if bboxes_in.device == torch.device("cpu"):
self.dboxes = self.dboxes.cpu()
self.dboxes_xywh = self.dboxes_xywh.cpu()
else:
self.dboxes = self.dboxes.cuda()
self.dboxes_xywh = self.dboxes_xywh.cuda()
bboxes_in = bboxes_in.permute(0, 2, 1)
scores_in = scores_in.permute(0, 2, 1)
#print(bboxes_in.device, scores_in.device, self.dboxes_xywh.device)
bboxes_in[:, :, :2] = self.scale_xy*bboxes_in[:, :, :2]
bboxes_in[:, :, 2:] = self.scale_wh*bboxes_in[:, :, 2:]
bboxes_in[:, :, :2] = bboxes_in[:, :, :2]*self.dboxes_xywh[:, :, 2:] + self.dboxes_xywh[:, :, :2]
bboxes_in[:, :, 2:] = bboxes_in[:, :, 2:].exp()*self.dboxes_xywh[:, :, 2:]
# Transform format to ltrb
l, t, r, b = bboxes_in[:, :, 0] - 0.5*bboxes_in[:, :, 2],\
bboxes_in[:, :, 1] - 0.5*bboxes_in[:, :, 3],\
bboxes_in[:, :, 0] + 0.5*bboxes_in[:, :, 2],\
bboxes_in[:, :, 1] + 0.5*bboxes_in[:, :, 3]
bboxes_in[:, :, 0] = l
bboxes_in[:, :, 1] = t
bboxes_in[:, :, 2] = r
bboxes_in[:, :, 3] = b
return bboxes_in, F.softmax(scores_in, dim=-1)
def decode_batch(self, bboxes_in, scores_in, criteria = 0.45, max_output=200):
bboxes, probs = self.scale_back_batch(bboxes_in, scores_in)
output = []
for bbox, prob in zip(bboxes.split(1, 0), probs.split(1, 0)):
bbox = bbox.squeeze(0)
prob = prob.squeeze(0)
output.append(self.decode_single(bbox, prob, criteria, max_output))
#print(output[-1])
return output
# perform non-maximum suppression
def decode_single(self, bboxes_in, scores_in, criteria, max_output, max_num=200):
# Reference to https://github.com/amdegroot/ssd.pytorch
bboxes_out = []
scores_out = []
labels_out = []
for i, score in enumerate(scores_in.split(1, 1)):
# skip background
# print(score[score>0.90])
if i == 0: continue
# print(i)
score = score.squeeze(1)
mask = score > 0.05
bboxes, score = bboxes_in[mask, :], score[mask]
if score.size(0) == 0: continue
score_sorted, score_idx_sorted = score.sort(dim=0)
# select max_output indices
score_idx_sorted = score_idx_sorted[-max_num:]
candidates = []
#maxdata, maxloc = scores_in.sort()
while score_idx_sorted.numel() > 0:
idx = score_idx_sorted[-1].item()
bboxes_sorted = bboxes[score_idx_sorted, :]
bboxes_idx = bboxes[idx, :].unsqueeze(dim=0)
iou_sorted = calc_iou_tensor(bboxes_sorted, bboxes_idx).squeeze()
# we only need iou < criteria
score_idx_sorted = score_idx_sorted[iou_sorted < criteria]
candidates.append(idx)
bboxes_out.append(bboxes[candidates, :])
scores_out.append(score[candidates])
labels_out.extend([i]*len(candidates))
bboxes_out, labels_out, scores_out = torch.cat(bboxes_out, dim=0), \
torch.tensor(labels_out, dtype=torch.long), \
torch.cat(scores_out, dim=0)
labels_out = labels_out.to(scores_out.device)
_, max_ids = scores_out.sort(dim=0)
max_ids = max_ids[-max_output:]
return bboxes_out[max_ids, :], labels_out[max_ids], scores_out[max_ids]
class DefaultBoxes(object):
def __init__(self, fig_size, feat_size, steps, scales, aspect_ratios, \
scale_xy=0.1, scale_wh=0.2):
self.feat_size = feat_size
self.fig_size = fig_size
self.scale_xy_ = scale_xy
self.scale_wh_ = scale_wh
# According to https://github.com/weiliu89/caffe
# Calculation method slightly different from paper
self.steps = steps
self.scales = scales
fk = fig_size/np.array(steps)
self.aspect_ratios = aspect_ratios
self.default_boxes = []
# size of feature and number of feature
for idx, sfeat in enumerate(self.feat_size):
sk1 = scales[idx]/fig_size
sk2 = scales[idx+1]/fig_size
sk3 = sqrt(sk1*sk2)
all_sizes = [(sk1, sk1), (sk3, sk3)]
for alpha in aspect_ratios[idx]:
w, h = sk1*sqrt(alpha), sk1/sqrt(alpha)
all_sizes.append((w, h))
all_sizes.append((h, w))
for w, h in all_sizes:
for i, j in itertools.product(range(sfeat), repeat=2):
cx, cy = (j+0.5)/fk[idx], (i+0.5)/fk[idx]
self.default_boxes.append((cx, cy, w, h))
self.dboxes = torch.tensor(self.default_boxes, dtype = torch.float)
self.dboxes.clamp_(min=0, max=1)
# For IoU calculation
self.dboxes_ltrb = self.dboxes.clone()
self.dboxes_ltrb[:, 0] = self.dboxes[:, 0] - 0.5 * self.dboxes[:, 2]
self.dboxes_ltrb[:, 1] = self.dboxes[:, 1] - 0.5 * self.dboxes[:, 3]
self.dboxes_ltrb[:, 2] = self.dboxes[:, 0] + 0.5 * self.dboxes[:, 2]
self.dboxes_ltrb[:, 3] = self.dboxes[:, 1] + 0.5 * self.dboxes[:, 3]
@property
def scale_xy(self):
return self.scale_xy_
@property
def scale_wh(self):
return self.scale_wh_
def as_ltrb_list(self):
return [x for x in self.dboxes_ltrb.view(-1).numpy()]
def __call__(self, order="ltrb"):
if order == "ltrb": return self.dboxes_ltrb
if order == "xywh": return self.dboxes
def dboxes300_coco():
figsize = 300
feat_size = [38, 19, 10, 5, 3, 1]
steps = [8, 16, 32, 64, 100, 300]
# use the scales here: https://github.com/amdegroot/ssd.pytorch/blob/master/data/config.py
scales = [21, 45, 99, 153, 207, 261, 315]
aspect_ratios = [[2], [2, 3], [2, 3], [2, 3], [2], [2]]
dboxes = DefaultBoxes(figsize, feat_size, steps, scales, aspect_ratios)
return dboxes
# This function is from https://github.com/chauhan-utk/ssd.DomainAdaptation.
class SSDCropping(object):
""" Cropping for SSD, according to original paper
Choose between following 3 conditions:
1. Preserve the original image
2. Random crop minimum IoU is among 0.1, 0.3, 0.5, 0.7, 0.9
3. Random crop
Reference to https://github.com/chauhan-utk/src.DomainAdaptation
"""
def __init__(self):
self.sample_options = (
# Do nothing
None,
# min IoU, max IoU
(0.1, None),
(0.3, None),
(0.5, None),
(0.7, None),
(0.9, None),
# no IoU requirements
(None, None),
)
def __call__(self, img, img_size, bboxes, labels):
# Ensure always return cropped image
while True:
mode = random.choice(self.sample_options)
if mode is None:
return img, img_size, bboxes, labels
htot, wtot = img_size
min_iou, max_iou = mode
min_iou = float("-inf") if min_iou is None else min_iou
max_iou = float("+inf") if max_iou is None else max_iou
# Implementation use 50 iteration to find possible candidate
for _ in range(1):
# suze of each sampled path in [0.1, 1] 0.3*0.3 approx. 0.1
w = random.uniform(0.3 , 1.0)
h = random.uniform(0.3 , 1.0)
if w/h < 0.5 or w/h > 2:
continue
# left 0 ~ wtot - w, top 0 ~ htot - h
left = random.uniform(0, 1.0 - w)
top = random.uniform(0, 1.0 - h)
right = left + w
bottom = top + h
ious = calc_iou_tensor(bboxes, torch.tensor([[left, top, right, bottom]]))
# tailor all the bboxes and return
if not ((ious > min_iou) & (ious < max_iou)).all():
continue
# discard any bboxes whose center not in the cropped image
xc = 0.5*(bboxes[:, 0] + bboxes[:, 2])
yc = 0.5*(bboxes[:, 1] + bboxes[:, 3])
masks = (xc > left) & (xc < right) & (yc > top) & (yc < bottom)
# if no such boxes, continue searching again
if not masks.any():
continue
bboxes[bboxes[:, 0] < left, 0] = left
bboxes[bboxes[:, 1] < top, 1] = top
bboxes[bboxes[:, 2] > right, 2] = right
bboxes[bboxes[:, 3] > bottom, 3] = bottom
#print(left, top, right, bottom)
#print(labels, bboxes, masks)
bboxes = bboxes[masks, :]
labels = labels[masks]
left_idx = int(left*wtot)
top_idx = int(top*htot)
right_idx = int(right*wtot)
bottom_idx = int(bottom*htot)
#print(left_idx,top_idx,right_idx,bottom_idx)
#img = img[:, top_idx:bottom_idx, left_idx:right_idx]
img = img.crop((left_idx, top_idx, right_idx, bottom_idx))
bboxes[:, 0] = (bboxes[:, 0] - left)/w
bboxes[:, 1] = (bboxes[:, 1] - top)/h
bboxes[:, 2] = (bboxes[:, 2] - left)/w
bboxes[:, 3] = (bboxes[:, 3] - top)/h
htot = bottom_idx - top_idx
wtot = right_idx - left_idx
return img, (htot, wtot), bboxes, labels
class RandomHorizontalFlip(object):
def __init__(self, p=0.5):
self.p = p
def __call__(self, image, bboxes):
if random.random() < self.p:
bboxes[:, 0], bboxes[:, 2] = 1.0 - bboxes[:, 2], 1.0 - bboxes[:, 0]
return image.transpose(Image.FLIP_LEFT_RIGHT), bboxes
return image, bboxes
# Do data augumentation
class SSDTransformer(object):
""" SSD Data Augumentation, according to original paper
Composed by several steps:
Cropping
Resize
Flipping
Jittering
"""
def __init__(self, dboxes, args, size = (300, 300), val=False):
self.args = args
self.size = size
self.val = val
self.dboxes_ = dboxes
self.encoder = Encoder(self.dboxes_)
self.crop = SSDCropping()
train_trans = [transforms.Resize(self.size)]
train_trans.append(transforms.ColorJitter(
brightness=0.125,
contrast=0.5,
saturation=0.5,
hue=0.05))
train_trans.append(transforms.ToTensor())
self.img_trans = transforms.Compose(train_trans)
self.hflip = RandomHorizontalFlip()
# All PyTorch Tensor will be normalized
# https://discuss.pytorch.org/t/how-to-preprocess-input-for-pre-trained-networks/683
self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
self.trans_val = transforms.Compose([
transforms.Resize(self.size),
transforms.ToTensor(),
self.normalize])
@property
def dboxes(self):
return self.dboxes_
def __call__(self, img, img_size, bbox=None, label=None, max_num=200):
if self.val:
bbox_out = torch.zeros(max_num, 4)
label_out = torch.zeros(max_num, dtype=torch.long)
bbox_out[:bbox.size(0), :] = bbox
label_out[:label.size(0)] = label
return self.trans_val(img), img_size, bbox_out, label_out
img, img_size, bbox, label = self.crop(img, img_size, bbox, label)
img, bbox = self.hflip(img, bbox)
img = self.img_trans(img).contiguous()
img = self.normalize(img)
bbox, label = self.encoder.encode(bbox, label)
return img, img_size, bbox, label
# Implement a datareader for COCO dataset
class COCODetection(data.Dataset):
def __init__(self, img_folder, annotate_file, transform=None):
self.img_folder = img_folder
self.annotate_file = annotate_file
# Start processing annotation
with open(annotate_file) as fin:
self.data = json.load(fin)
self.images = {}
self.label_map = {}
self.label_info = {}
#print("Parsing COCO data...")
start_time = time.time()
# 0 stand for the background
cnt = 0
self.label_info[cnt] = "background"
for cat in self.data["categories"]:
cnt += 1
self.label_map[cat["id"]] = cnt
self.label_info[cnt] = cat["name"]
# build inference for images
for img in self.data["images"]:
img_id = img["id"]
img_name = img["file_name"]
img_size = (img["height"],img["width"])
#print(img_name)
if img_id in self.images: raise Exception("dulpicated image record")
self.images[img_id] = (img_name, img_size, [])
# read bboxes
for bboxes in self.data["annotations"]:
img_id = bboxes["image_id"]
category_id = bboxes["category_id"]
bbox = bboxes["bbox"]
bbox_label = self.label_map[bboxes["category_id"]]
self.images[img_id][2].append((bbox, bbox_label))
for k, v in list(self.images.items()):
if len(v[2]) == 0:
#print("empty image: {}".format(k))
self.images.pop(k)
self.img_keys = list(self.images.keys())
self.transform = transform
@property
def labelnum(self):
return len(self.label_info)
@staticmethod
def load(pklfile):
#print("Loading from {}".format(pklfile))
with bz2.open(pklfile, "rb") as fin:
ret = pickle.load(fin)
return ret
def save(self, pklfile):
#print("Saving to {}".format(pklfile))
with bz2.open(pklfile, "wb") as fout:
pickle.dump(self, fout)
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
img_id = self.img_keys[idx]
img_data = self.images[img_id]
fn = img_data[0]
img_path = os.path.join(self.img_folder, fn)
img = Image.open(img_path).convert("RGB")
htot, wtot = img_data[1]
bbox_sizes = []
bbox_labels = []
#for (xc, yc, w, h), bbox_label in img_data[2]:
for (l,t,w,h), bbox_label in img_data[2]:
r = l + w
b = t + h
#l, t, r, b = xc - 0.5*w, yc - 0.5*h, xc + 0.5*w, yc + 0.5*h
bbox_size = (l/wtot, t/htot, r/wtot, b/htot)
bbox_sizes.append(bbox_size)
bbox_labels.append(bbox_label)
bbox_sizes = torch.tensor(bbox_sizes)
bbox_labels = torch.tensor(bbox_labels)
if self.transform != None:
img, (htot, wtot), bbox_sizes, bbox_labels = \
self.transform(img, (htot, wtot), bbox_sizes, bbox_labels)
else:
pass
return img, img_id, (htot, wtot), bbox_sizes, bbox_labels
def draw_patches(img, bboxes, labels, order="xywh", label_map={}):
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Suppose bboxes in fractional coordinate:
# cx, cy, w, h
# img = img.numpy()
img = np.array(img)
labels = np.array(labels)
bboxes = bboxes.numpy()
if label_map:
labels = [label_map.get(l) for l in labels]
if order == "ltrb":
xmin, ymin, xmax, ymax = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]
cx, cy, w, h = (xmin + xmax)/2, (ymin + ymax)/2, xmax - xmin, ymax - ymin
else:
cx, cy, w, h = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]
htot, wtot,_ = img.shape
cx *= wtot
cy *= htot
w *= wtot
h *= htot
bboxes = zip(cx, cy, w, h)
plt.imshow(img)
ax = plt.gca()
for (cx, cy, w, h), label in zip(bboxes, labels):
if label == "background": continue
ax.add_patch(patches.Rectangle((cx-0.5*w, cy-0.5*h),
w, h, fill=False, color="r"))
bbox_props = dict(boxstyle="round", fc="y", ec="0.5", alpha=0.3)
ax.text(cx-0.5*w, cy-0.5*h, label, ha="center", va="center", size=15, bbox=bbox_props)
plt.show()
|
DALI-main
|
docs/examples/use_cases/pytorch/single_stage_detector/src/utils.py
|
from torch.autograd import Variable
import torch
import time
def train_loop(model, loss_func, scaler, epoch, optim, train_loader, iteration, logger, args):
for nbatch, data in enumerate(train_loader):
if args.data_pipeline == 'no_dali':
(img, _, img_size, bbox, label) = data
img = img.cuda()
bbox = bbox.cuda()
label = label.cuda()
else:
img = data[0]["images"]
bbox = data[0]["boxes"]
label = data[0]["labels"]
label = label.type(torch.cuda.LongTensor)
boxes_in_batch = len(label.nonzero())
if boxes_in_batch != 0:
with torch.cuda.amp.autocast(enabled=args.fp16_mode):
ploc, plabel = model(img)
ploc, plabel = ploc.float(), plabel.float()
trans_bbox = bbox.transpose(1, 2).contiguous().cuda()
label = label.cuda()
gloc = Variable(trans_bbox, requires_grad=False)
glabel = Variable(label, requires_grad=False)
loss = loss_func(ploc, plabel, gloc, glabel)
scaler.scale(loss).backward()
logger.update_iter(epoch, iteration, loss.item())
if args.warmup is not None:
warmup(optim, args.warmup, iteration, args.learning_rate)
scaler.step(optim)
scaler.update()
optim.zero_grad()
iteration += 1
return iteration
def warmup(optim, warmup_iters, iteration, base_lr):
if iteration < warmup_iters:
new_lr = 1. * base_lr / warmup_iters * iteration
for param_group in optim.param_groups:
param_group['lr'] = new_lr
def tencent_trick(model):
"""
Divide parameters into 2 groups.
First group is BNs and all biases.
Second group is the remaining model's parameters.
Weight decay will be disabled in first group (aka tencent trick).
"""
decay, no_decay = [], []
for name, param in model.named_parameters():
if not param.requires_grad:
continue # frozen weights
if len(param.shape) == 1 or name.endswith(".bias"):
no_decay.append(param)
else:
decay.append(param)
return [{'params': no_decay, 'weight_decay': 0.0},
{'params': decay}]
|
DALI-main
|
docs/examples/use_cases/pytorch/single_stage_detector/src/train.py
|
import torch
import time
import numpy as np
from contextlib import redirect_stdout
import io
from pycocotools.cocoeval import COCOeval
def evaluate(model, coco, cocoGt, encoder, inv_map, args):
if args.distributed:
N_gpu = torch.distributed.get_world_size()
else:
N_gpu = 1
model.eval()
model.cuda()
ret = []
start = time.time()
# for idx, image_id in enumerate(coco.img_keys):
for nbatch, (img, img_id, img_size, _, _) in enumerate(coco):
print("Parsing batch: {}/{}".format(nbatch, len(coco)), end='\r')
with torch.no_grad():
inp = img.cuda()
with torch.cuda.amp.autocast(enabled=args.fp16_mode):
# Get predictions
ploc, plabel = model(inp)
ploc, plabel = ploc.float(), plabel.float()
# Handle the batch of predictions produced
# This is slow, but consistent with old implementation.
for idx in range(ploc.shape[0]):
# ease-of-use for specific predictions
ploc_i = ploc[idx, :, :].unsqueeze(0)
plabel_i = plabel[idx, :, :].unsqueeze(0)
try:
result = encoder.decode_batch(ploc_i, plabel_i, 0.50, 200)[0]
except:
# raise
print("")
print("No object detected in idx: {}".format(idx))
continue
htot, wtot = img_size[0][idx].item(), img_size[1][idx].item()
loc, label, prob = [r.cpu().numpy() for r in result]
for loc_, label_, prob_ in zip(loc, label, prob):
ret.append([img_id[idx], loc_[0] * wtot, \
loc_[1] * htot,
(loc_[2] - loc_[0]) * wtot,
(loc_[3] - loc_[1]) * htot,
prob_,
inv_map[label_]])
# Now we have all predictions from this rank, gather them all together
# if necessary
ret = np.array(ret).astype(np.float32)
# Multi-GPU eval
if args.distributed:
# NCCL backend means we can only operate on GPU tensors
ret_copy = torch.tensor(ret).cuda()
# Everyone exchanges the size of their results
ret_sizes = [torch.tensor(0).cuda() for _ in range(N_gpu)]
torch.cuda.synchronize()
torch.distributed.all_gather(ret_sizes, torch.tensor(ret_copy.shape[0]).cuda())
torch.cuda.synchronize()
# Get the maximum results size, as all tensors must be the same shape for
# the all_gather call we need to make
max_size = 0
sizes = []
for s in ret_sizes:
max_size = max(max_size, s.item())
sizes.append(s.item())
# Need to pad my output to max_size in order to use in all_gather
ret_pad = torch.cat([ret_copy, torch.zeros(max_size - ret_copy.shape[0], 7, dtype=torch.float32).cuda()])
# allocate storage for results from all other processes
other_ret = [torch.zeros(max_size, 7, dtype=torch.float32).cuda() for i in range(N_gpu)]
# Everyone exchanges (padded) results
torch.cuda.synchronize()
torch.distributed.all_gather(other_ret, ret_pad)
torch.cuda.synchronize()
# Now need to reconstruct the _actual_ results from the padded set using slices.
cat_tensors = []
for i in range(N_gpu):
cat_tensors.append(other_ret[i][:sizes[i]][:])
final_results = torch.cat(cat_tensors).cpu().numpy()
else:
# Otherwise full results are just our results
final_results = ret
if args.local_rank == 0:
print("")
print("Predicting Ended, total time: {:.2f} s".format(time.time() - start))
cocoDt = cocoGt.loadRes(final_results)
E = COCOeval(cocoGt, cocoDt, iouType='bbox')
E.evaluate()
E.accumulate()
if args.local_rank == 0:
E.summarize()
print("Current AP: {:.5f}".format(E.stats[0]))
else:
# fix for cocoeval indiscriminate prints
with redirect_stdout(io.StringIO()):
E.summarize()
# put your model in training mode back on
model.train()
return E.stats[0] # Average Precision (AP) @[ IoU=050:0.95 | area= all | maxDets=100 ]
|
DALI-main
|
docs/examples/use_cases/pytorch/single_stage_detector/src/evaluate.py
|
import os
import numpy as np
import torch
from torch.utils.data import DataLoader
from src.utils import dboxes300_coco, COCODetection, SSDTransformer
from src.coco import COCO
from src.coco_pipeline import create_coco_pipeline
from nvidia.dali.plugin.pytorch import DALIGenericIterator, LastBatchPolicy
def set_seeds(args):
torch.cuda.set_device(args.local_rank)
device = torch.device('cuda')
if args.distributed:
args.seed = broadcast_seeds(args.seed, device)
local_seed = (args.seed + torch.distributed.get_rank()) % 2**32
local_rank = torch.distributed.get_rank()
else:
local_seed = args.seed % 2**32
local_rank = 0
print("Rank", local_rank, "using seed = {}".format(local_seed))
torch.manual_seed(local_seed)
np.random.seed(seed=local_seed)
return local_seed
def broadcast_seeds(seed, device):
if torch.distributed.is_initialized():
seeds_tensor = torch.LongTensor([seed]).to(device)
torch.distributed.broadcast(seeds_tensor, 0)
seed = seeds_tensor.item()
return seed
def get_train_pytorch_loader(args, num_workers, default_boxes):
dataset = COCODetection(
args.train_coco_root,
args.train_annotate,
SSDTransformer(default_boxes, args, (300, 300), val=False))
if args.distributed:
train_sampler = torch.utils.data.distributed.DistributedSampler(dataset)
else:
train_sampler = None
train_dataloader = DataLoader(
dataset,
batch_size=args.batch_size,
shuffle=(train_sampler is None),
sampler=train_sampler,
drop_last=True,
num_workers=num_workers)
return train_dataloader
def get_train_dali_loader(args, default_boxes, local_seed):
train_pipe = create_coco_pipeline(
default_boxes,
args,
batch_size=args.batch_size,
num_threads=args.num_workers,
device_id=args.local_rank,
seed=local_seed)
train_loader = DALIGenericIterator(
train_pipe,
["images", "boxes", "labels"],
reader_name="Reader",
last_batch_policy=LastBatchPolicy.FILL)
return train_loader
def get_train_loader(args, dboxes):
args.train_annotate = os.path.join(
args.data, "annotations/instances_train2017.json")
args.train_coco_root = os.path.join(args.data, "train2017")
local_seed = set_seeds(args)
if args.data_pipeline == 'no_dali':
return get_train_pytorch_loader(args, args.num_workers, dboxes)
elif args.data_pipeline == 'dali':
return get_train_dali_loader(args, dboxes, local_seed)
def get_val_dataset(args):
dboxes = dboxes300_coco()
val_trans = SSDTransformer(dboxes, args,(300, 300), val=True)
val_annotate = os.path.join(args.data, "annotations/instances_val2017.json")
val_coco_root = os.path.join(args.data, "val2017")
val_coco = COCODetection(val_coco_root, val_annotate, val_trans)
return val_coco
def get_val_dataloader(args):
dataset = get_val_dataset(args)
inv_map = {v: k for k, v in dataset.label_map.items()}
if args.distributed:
val_sampler = torch.utils.data.distributed.DistributedSampler(dataset)
else:
val_sampler = None
val_dataloader = DataLoader(
dataset,
batch_size=args.eval_batch_size,
shuffle=False, # Note: distributed sampler is shuffled :(
sampler=val_sampler,
num_workers=args.num_workers)
return val_dataloader, inv_map
def get_coco_ground_truth(args):
val_annotate = os.path.join(args.data, "annotations/instances_val2017.json")
cocoGt = COCO(annotation_file=val_annotate)
return cocoGt
|
DALI-main
|
docs/examples/use_cases/pytorch/single_stage_detector/src/data.py
|
doc(title="Video Processing",
underline_char="=",
entries=[
doc_entry("video/video_reader_simple_example.ipynb",
op_reference('fn.readers.video', "Tutorial describing how to use video reader")),
doc_entry("video/video_reader_label_example.ipynb",
op_reference('fn.readers.video', "Tutorial describing how to use video reader to output frames with labels")),
doc_entry("video/video_file_list_outputs.ipynb",
op_reference('fn.readers.video', "Tutorial describing how to output frames with \
labels assigned to dedicated ranges of frame numbers/timestamps")),
doc_entry("sequence_reader_simple_example.ipynb",
op_reference('fn.readers.sequence', "Tutorial describing how to read sequence of video frames stored as separate files")),
doc_entry("video/video_processing_per_frame_arguments.ipynb",
[op_reference('fn.readers.video', "Examples of processing video in DALI"),
op_reference(
'fn.per_frame', "Using per-frame operator to specify arguments to video processing operators"),
op_reference(
'fn.gaussian_blur', "Specifying per-frame arguments when processing video"),
op_reference(
'fn.laplacian', "Specifying per-frame arguments when processing video"),
op_reference(
'fn.rotate', "Specifying per-frame arguments when processing video"),
op_reference(
'fn.warp_affine', "Specifying per-frame arguments when processing video"),
op_reference('fn.transforms', "Specifying per-frame arguments when processing video"), ]),
doc_entry("optical_flow_example.ipynb",
[op_reference('fn.readers.video', "Tutorial describing how to calculate optical flow from video inputs"),
op_reference('fn.optical_flow', "Tutorial describing how to calculate optical flow from sequence inputs")]),
])
|
DALI-main
|
docs/examples/sequence_processing/index.py
|
#!/bin/env python
import os
import numpy as np
from nvidia.dali import pipeline_def
import nvidia.dali.fn as fn
import nvidia.dali.types as types
try:
from matplotlib import pyplot as plt
has_matplotlib = True
except ImportError:
has_matplotlib = False
try:
from PIL import Image
has_PIL = True
except ImportError:
has_PIL = False
BATCH_SIZE=4
COUNT=5
def YUV2RGB(yuv):
yuv = np.multiply(yuv, 255)
m = np.array([[ 1.0, 1.0, 1.0],
[-0.000007154783816076815, -0.3441331386566162, 1.7720025777816772],
[ 1.4019975662231445, -0.7141380310058594 , 0.00001542569043522235] ])
rgb = np.dot(yuv,m)
rgb[:,:,0]-=179.45477266423404
rgb[:,:,1]+=135.45870971679688
rgb[:,:,2]-=226.8183044444304
return rgb
VIDEO_FILE_ROOT = os.path.join(os.environ['DALI_EXTRA_PATH'], "db", "video", "sintel", "labelled_videos")
ITER=100
@pipeline_def
def video_pipe(file_root):
video, label = fn.readers.video(device="gpu", file_root=file_root, sequence_length=COUNT,
shard_id=0, num_shards=1, random_shuffle=False,
normalized=True, image_type=types.YCbCr, dtype=types.FLOAT)
# instead of file_root, path to text file with pairs video_filepath label_value can be provided
# self.input = fn.readers.video(device="gpu", file_list = "file_list.txt", sequence_length=COUNT, ...)
return video, label
if __name__ == "__main__":
pipe = video_pipe(batch_size=BATCH_SIZE, num_threads=2, device_id=0, file_root=VIDEO_FILE_ROOT)
pipe.build()
for i in range(ITER):
print("Iteration " + str(i))
sequences_out, label = pipe.run()
sequences_out = sequences_out.as_cpu().as_array()
label = label.as_cpu().as_array()
print("sequences shape: ", sequences_out.shape)
print("labels shape: ", label.shape)
print("Got sequence " + str(i*COUNT) + " " + str((i + 1)*COUNT - 1))
for b in range(BATCH_SIZE):
batch_sequences = sequences_out[b]
print(label[b])
print(batch_sequences.shape)
save_dir = 'extracted_frames/' + str(label[b][0]) + '/'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
for c in range(COUNT):
sample_frame = batch_sequences[c]
if has_PIL:
im = Image.fromarray(YUV2RGB(sample_frame).astype('uint8'))
im.save(save_dir + str(i * BATCH_SIZE * COUNT + b * COUNT + c) + '.png')
frame_to_show = sequences_out[0][0]
frame_to_show = YUV2RGB(frame_to_show)
if has_matplotlib:
plt.imshow(frame_to_show.astype('uint8'), interpolation='bicubic')
plt.show()
plt.savefig('saved_frame.png')
|
DALI-main
|
docs/examples/sequence_processing/video/video_label_example.py
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/__init__.py
|
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 argparse
import logging
logging.basicConfig(level=logging.DEBUG)
from common import find_mxnet, data, fit
from common.util import download_file
import mxnet as mx
if __name__ == '__main__':
# parse args
parser = argparse.ArgumentParser(description="train imagenet-1k",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
fit.add_fit_args(parser)
data.add_data_args(parser)
data.add_data_aug_args(parser)
# use a large aug level
data.set_data_aug_level(parser, 3)
parser.set_defaults(
# network
network = 'resnet',
num_layers = 50,
# data
num_classes = 1000,
num_examples = 1281167,
image_shape = '3,224,224',
min_random_scale = 1, # if input image has min size k, suggest to use
# 256.0/x, e.g. 0.533 for 480
# train
num_epochs = 80,
lr_step_epochs = '30,60',
dtype = 'float32'
)
args = parser.parse_args()
# load network
from importlib import import_module
net = import_module('symbols.'+args.network)
sym = net.get_symbol(**vars(args))
# train
fit.fit(args, sym, data.get_rec_iter)
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/train_imagenet.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
""" example train fit utility """
import logging
import os
import time
import re
import math
import mxnet as mx
def _get_lr_scheduler(args, kv):
if 'lr_factor' not in args or args.lr_factor >= 1:
return (args.lr, None)
epoch_size = args.num_examples / args.batch_size
if 'dist' in args.kv_store:
epoch_size /= kv.num_workers
begin_epoch = args.load_epoch if args.load_epoch else 0
if 'pow' in args.lr_step_epochs:
lr = args.lr
max_up = args.num_epochs * epoch_size
pwr = float(re.sub('pow[- ]*', '', args.lr_step_epochs))
poly_sched = mx.lr_scheduler.PolyScheduler(max_up, lr, pwr)
return (lr, poly_sched)
step_epochs = [int(l) for l in args.lr_step_epochs.split(',')]
lr = args.lr
for s in step_epochs:
if begin_epoch >= s:
lr *= args.lr_factor
if lr != args.lr:
logging.info('Adjust learning rate to %e for epoch %d',
lr, begin_epoch)
steps = [epoch_size * (x - begin_epoch)
for x in step_epochs if x - begin_epoch > 0]
return (lr, mx.lr_scheduler.MultiFactorScheduler(step=steps, factor=args.lr_factor))
def _load_model(args, rank=0):
if 'load_epoch' not in args or args.load_epoch is None:
return (None, None, None)
assert args.model_prefix is not None
model_prefix = args.model_prefix
if rank > 0 and os.path.exists("%s-%d-symbol.json" % (model_prefix, rank)):
model_prefix += "-%d" % (rank)
sym, arg_params, aux_params = mx.model.load_checkpoint(
model_prefix, args.load_epoch)
logging.info('Loaded model %s_%04d.params', model_prefix, args.load_epoch)
return (sym, arg_params, aux_params)
def _save_model(args, rank=0):
if args.model_prefix is None:
return None
dst_dir = os.path.dirname(args.model_prefix)
if not os.path.isdir(dst_dir):
os.mkdir(dst_dir)
return mx.callback.do_checkpoint(args.model_prefix if rank == 0 else "%s-%d" % (
args.model_prefix, rank))
def add_fit_args(parser):
"""
parser : argparse.ArgumentParser
return a parser added with args required by fit
"""
train = parser.add_argument_group('Training', 'model training')
train.add_argument('--network', type=str,
help='the neural network to use')
train.add_argument('--num-layers', type=int,
help='number of layers in the neural network, \
required by some networks such as resnet')
train.add_argument('--gpus', type=str,
help='list of gpus to run, e.g. 0 or 0,2,5. empty means using cpu')
train.add_argument('--kv-store', type=str, default='device',
help='key-value store type')
train.add_argument('--num-epochs', type=int, default=100,
help='max num of epochs')
train.add_argument('--lr', type=float, default=0.1,
help='initial learning rate')
train.add_argument('--lr-factor', type=float, default=0.1,
help='the ratio to reduce lr on each step')
train.add_argument('--lr-step-epochs', type=str,
help='the epochs to reduce the lr, e.g. 30,60')
train.add_argument('--initializer', type=str, default='default',
help='the initializer type')
train.add_argument('--optimizer', type=str, default='sgd',
help='the optimizer type')
train.add_argument('--mom', type=float, default=0.9,
help='momentum for sgd')
train.add_argument('--wd', type=float, default=0.0001,
help='weight decay for sgd')
train.add_argument('--batch-size', type=int, default=128,
help='the batch size')
train.add_argument('--disp-batches', type=int, default=20,
help='show progress for every n batches')
train.add_argument('--model-prefix', type=str,
help='model prefix')
parser.add_argument('--monitor', dest='monitor', type=int, default=0,
help='log network parameters every N iters if larger than 0')
train.add_argument('--load-epoch', type=int,
help='load the model on an epoch using the model-load-prefix')
train.add_argument('--top-k', type=int, default=0,
help='report the top-k accuracy. 0 means no report.')
train.add_argument('--loss', type=str, default='',
help='show the cross-entropy or nll loss. ce strands for cross-entropy, nll-loss stands for likelihood loss')
train.add_argument('--test-io', type=int, default=0,
help='1 means test reading speed without training')
train.add_argument('--dtype', type=str, default='float32',
help='precision: float32 or float16')
train.add_argument('--gc-type', type=str, default='none',
help='type of gradient compression to use, \
takes `2bit` or `none` for now')
train.add_argument('--gc-threshold', type=float, default=0.5,
help='threshold for 2bit gradient compression')
# additional parameters for large batch sgd
train.add_argument('--macrobatch-size', type=int, default=0,
help='distributed effective batch size')
train.add_argument('--warmup-epochs', type=int, default=5,
help='the epochs to ramp-up lr to scaled large-batch value')
train.add_argument('--warmup-strategy', type=str, default='linear',
help='the ramping-up strategy for large batch sgd')
return train
def fit(args, network, data_loader, **kwargs):
"""
train a model
args : argparse returns
network : the symbol definition of the nerual network
data_loader : function that returns the train and val data iterators
"""
# kvstore
kv = mx.kvstore.create(args.kv_store)
if args.gc_type != 'none':
kv.set_gradient_compression({'type': args.gc_type,
'threshold': args.gc_threshold})
# logging
head = '%(asctime)-15s Node[' + str(kv.rank) + '] %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
logging.info('start with arguments %s', args)
# data iterators
(train, val) = data_loader(args, kv)
if args.test_io:
tic = time.time()
for i, batch in enumerate(train):
if isinstance(batch, list):
for b in batch:
for j in b.data:
j.wait_to_read()
else:
for j in batch.data:
j.wait_to_read()
if (i + 1) % args.disp_batches == 0:
logging.info('Batch [%d]\tSpeed: %.2f samples/sec', i,
args.disp_batches * args.batch_size / (time.time() - tic))
tic = time.time()
return
# load model
if 'arg_params' in kwargs and 'aux_params' in kwargs:
arg_params = kwargs['arg_params']
aux_params = kwargs['aux_params']
else:
sym, arg_params, aux_params = _load_model(args, kv.rank)
if sym is not None:
assert sym.tojson() == network.tojson()
# save model
checkpoint = _save_model(args, kv.rank)
# devices for training
devs = mx.cpu() if args.gpus is None or args.gpus == "" else [
mx.gpu(int(i)) for i in args.gpus.split(',')]
# learning rate
lr, lr_scheduler = _get_lr_scheduler(args, kv)
# create model
model = mx.mod.Module(
context=devs,
symbol=network
)
lr_scheduler = lr_scheduler
optimizer_params = {
'learning_rate': lr,
'wd': args.wd,
'lr_scheduler': lr_scheduler,
'multi_precision': True}
# Only a limited number of optimizers have 'momentum' property
has_momentum = {'sgd', 'dcasgd', 'nag'}
if args.optimizer in has_momentum:
optimizer_params['momentum'] = args.mom
monitor = mx.mon.Monitor(
args.monitor, pattern=".*") if args.monitor > 0 else None
# A limited number of optimizers have a warmup period
has_warmup = {'lbsgd', 'lbnag'}
if args.optimizer in has_warmup:
if 'dist' in args.kv_store:
nworkers = kv.num_workers
else:
nworkers = 1
epoch_size = args.num_examples / args.batch_size / nworkers
if epoch_size < 1:
epoch_size = 1
macrobatch_size = args.macrobatch_size
if macrobatch_size < args.batch_size * nworkers:
macrobatch_size = args.batch_size * nworkers
#batch_scale = round(float(macrobatch_size) / args.batch_size / nworkers +0.4999)
batch_scale = math.ceil(
float(macrobatch_size) / args.batch_size / nworkers)
optimizer_params['updates_per_epoch'] = epoch_size
optimizer_params['begin_epoch'] = args.load_epoch if args.load_epoch else 0
optimizer_params['batch_scale'] = batch_scale
optimizer_params['warmup_strategy'] = args.warmup_strategy
optimizer_params['warmup_epochs'] = args.warmup_epochs
optimizer_params['num_epochs'] = args.num_epochs
if args.initializer == 'default':
if args.network == 'alexnet':
# AlexNet will not converge using Xavier
initializer = mx.init.Normal()
# VGG will not trend to converge using Xavier-Gaussian
elif 'vgg' in args.network:
initializer = mx.init.Xavier()
else:
initializer = mx.init.Xavier(
rnd_type='gaussian', factor_type="in", magnitude=2)
# initializer = mx.init.Xavier(factor_type="in", magnitude=2.34),
elif args.initializer == 'xavier':
initializer = mx.init.Xavier()
elif args.initializer == 'msra':
initializer = mx.init.MSRAPrelu()
elif args.initializer == 'orthogonal':
initializer = mx.init.Orthogonal()
elif args.initializer == 'normal':
initializer = mx.init.Normal()
elif args.initializer == 'uniform':
initializer = mx.init.Uniform()
elif args.initializer == 'one':
initializer = mx.init.One()
elif args.initializer == 'zero':
initializer = mx.init.Zero()
# evaluation metrices
eval_metrics = ['accuracy']
if args.top_k > 0:
eval_metrics.append(mx.metric.create(
'top_k_accuracy', top_k=args.top_k))
supported_loss = ['ce', 'nll_loss']
if len(args.loss) > 0:
# ce or nll loss is only applicable to softmax output
loss_type_list = args.loss.split(',')
if 'softmax_output' in network.list_outputs():
for loss_type in loss_type_list:
loss_type = loss_type.strip()
if loss_type == 'nll':
loss_type = 'nll_loss'
if loss_type not in supported_loss:
logging.warning(loss_type + ' is not an valid loss type, only cross-entropy or ' \
'negative likelihood loss is supported!')
else:
eval_metrics.append(mx.metric.create(loss_type))
else:
logging.warning("The output is not softmax_output, loss argument will be skipped!")
# callbacks that run after each batch
batch_end_callbacks = [mx.callback.Speedometer(
args.batch_size, args.disp_batches)]
if 'batch_end_callback' in kwargs:
cbs = kwargs['batch_end_callback']
batch_end_callbacks += cbs if isinstance(cbs, list) else [cbs]
# run
model.fit(train,
begin_epoch=args.load_epoch if args.load_epoch else 0,
num_epoch=args.num_epochs,
eval_data=val,
eval_metric=eval_metrics,
kvstore=kv,
optimizer=args.optimizer,
optimizer_params=optimizer_params,
initializer=initializer,
arg_params=arg_params,
aux_params=aux_params,
batch_end_callback=batch_end_callbacks,
epoch_end_callback=checkpoint,
allow_missing=True,
monitor=monitor)
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/common/fit.py
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/common/__init__.py
|
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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, sys
try:
import mxnet as mx
except ImportError:
curr_path = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(curr_path, "../../../python"))
import mxnet as mx
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/common/find_mxnet.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 mxnet as mx
import random
from mxnet.io import DataBatch, DataIter
import numpy as np
def add_data_args(parser):
data = parser.add_argument_group('Data', 'the input images')
data.add_argument('--data-train', type=str, help='the training data')
data.add_argument('--data-train-idx', type=str, default='', help='the index of training data')
data.add_argument('--data-val', type=str, help='the validation data')
data.add_argument('--data-val-idx', type=str, default='', help='the index of validation data')
data.add_argument('--rgb-mean', type=str, default='123.68,116.779,103.939',
help='a tuple of size 3 for the mean rgb')
data.add_argument('--pad-size', type=int, default=0,
help='padding the input image')
data.add_argument('--image-shape', type=str,
help='the image shape feed into the network, e.g. (3,224,224)')
data.add_argument('--num-classes', type=int, help='the number of classes')
data.add_argument('--num-examples', type=int, help='the number of training examples')
data.add_argument('--data-nthreads', type=int, default=4,
help='number of threads for data decoding')
data.add_argument('--benchmark', type=int, default=0,
help='if 1, then feed the network with synthetic data')
return data
def add_data_aug_args(parser):
aug = parser.add_argument_group(
'Image augmentations', 'implemented in src/io/image_aug_default.cc')
aug.add_argument('--random-crop', type=int, default=1,
help='if or not randomly crop the image')
aug.add_argument('--random-mirror', type=int, default=1,
help='if or not randomly flip horizontally')
aug.add_argument('--max-random-h', type=int, default=0,
help='max change of hue, whose range is [0, 180]')
aug.add_argument('--max-random-s', type=int, default=0,
help='max change of saturation, whose range is [0, 255]')
aug.add_argument('--max-random-l', type=int, default=0,
help='max change of intensity, whose range is [0, 255]')
aug.add_argument('--max-random-aspect-ratio', type=float, default=0,
help='max change of aspect ratio, whose range is [0, 1]')
aug.add_argument('--max-random-rotate-angle', type=int, default=0,
help='max angle to rotate, whose range is [0, 360]')
aug.add_argument('--max-random-shear-ratio', type=float, default=0,
help='max ratio to shear, whose range is [0, 1]')
aug.add_argument('--max-random-scale', type=float, default=1,
help='max ratio to scale')
aug.add_argument('--min-random-scale', type=float, default=1,
help='min ratio to scale, should >= img_size/input_shape. otherwise use --pad-size')
return aug
def set_data_aug_level(aug, level):
if level >= 1:
aug.set_defaults(random_crop=1, random_mirror=1)
if level >= 2:
aug.set_defaults(max_random_h=36, max_random_s=50, max_random_l=50)
if level >= 3:
aug.set_defaults(max_random_rotate_angle=10, max_random_shear_ratio=0.1, max_random_aspect_ratio=0.25)
class SyntheticDataIter(DataIter):
def __init__(self, num_classes, data_shape, max_iter, dtype):
self.batch_size = data_shape[0]
self.cur_iter = 0
self.max_iter = max_iter
self.dtype = dtype
label = np.random.randint(0, num_classes, [self.batch_size,])
data = np.random.uniform(-1, 1, data_shape)
self.data = mx.nd.array(data, dtype=self.dtype, ctx=mx.Context('cpu_pinned', 0))
self.label = mx.nd.array(label, dtype=self.dtype, ctx=mx.Context('cpu_pinned', 0))
def __iter__(self):
return self
@property
def provide_data(self):
return [mx.io.DataDesc('data', self.data.shape, self.dtype)]
@property
def provide_label(self):
return [mx.io.DataDesc('softmax_label', (self.batch_size,), self.dtype)]
def next(self):
self.cur_iter += 1
if self.cur_iter <= self.max_iter:
return DataBatch(data=(self.data,),
label=(self.label,),
pad=0,
index=None,
provide_data=self.provide_data,
provide_label=self.provide_label)
else:
raise StopIteration
def __next__(self):
return self.next()
def reset(self):
self.cur_iter = 0
def get_rec_iter(args, kv=None):
image_shape = tuple([int(l) for l in args.image_shape.split(',')])
if 'benchmark' in args and args.benchmark:
data_shape = (args.batch_size,) + image_shape
train = SyntheticDataIter(args.num_classes, data_shape, 1000, np.float32)
return (train, None)
if kv:
(rank, nworker) = (kv.rank, kv.num_workers)
else:
(rank, nworker) = (0, 1)
rgb_mean = [float(i) for i in args.rgb_mean.split(',')]
train = mx.io.ImageRecordIter(
path_imgrec = args.data_train,
path_imgidx = args.data_train_idx,
label_width = 1,
mean_r = rgb_mean[0],
mean_g = rgb_mean[1],
mean_b = rgb_mean[2],
data_name = 'data',
label_name = 'softmax_label',
data_shape = image_shape,
batch_size = args.batch_size,
rand_crop = args.random_crop,
max_random_scale = args.max_random_scale,
pad = args.pad_size,
fill_value = 127,
min_random_scale = args.min_random_scale,
max_aspect_ratio = args.max_random_aspect_ratio,
random_h = args.max_random_h,
random_s = args.max_random_s,
random_l = args.max_random_l,
max_rotate_angle = args.max_random_rotate_angle,
max_shear_ratio = args.max_random_shear_ratio,
rand_mirror = args.random_mirror,
preprocess_threads = args.data_nthreads,
shuffle = True,
num_parts = nworker,
part_index = rank)
if args.data_val is None:
return (train, None)
val = mx.io.ImageRecordIter(
path_imgrec = args.data_val,
path_imgidx = args.data_val_idx,
label_width = 1,
mean_r = rgb_mean[0],
mean_g = rgb_mean[1],
mean_b = rgb_mean[2],
data_name = 'data',
label_name = 'softmax_label',
batch_size = args.batch_size,
data_shape = image_shape,
preprocess_threads = args.data_nthreads,
rand_crop = False,
rand_mirror = False,
num_parts = nworker,
part_index = rank)
return (train, val)
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/common/data.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""References:
Szegedy, Christian, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed, Dragomir
Anguelov, Dumitru Erhan, Vincent Vanhoucke, and Andrew Rabinovich. "Going deeper
with convolutions." arXiv preprint arXiv:1409.4842 (2014).
"""
import mxnet as mx
def ConvFactory(data, num_filter, kernel, stride=(1,1), pad=(0, 0), name=None, suffix=''):
conv = mx.symbol.Convolution(data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, name='conv_%s%s' %(name, suffix))
act = mx.symbol.Activation(data=conv, act_type='relu', name='relu_%s%s' %(name, suffix))
return act
def InceptionFactory(data, num_1x1, num_3x3red, num_3x3, num_d5x5red, num_d5x5, pool, proj, name):
# 1x1
c1x1 = ConvFactory(data=data, num_filter=num_1x1, kernel=(1, 1), name=('%s_1x1' % name))
# 3x3 reduce + 3x3
c3x3r = ConvFactory(data=data, num_filter=num_3x3red, kernel=(1, 1), name=('%s_3x3' % name), suffix='_reduce')
c3x3 = ConvFactory(data=c3x3r, num_filter=num_3x3, kernel=(3, 3), pad=(1, 1), name=('%s_3x3' % name))
# double 3x3 reduce + double 3x3
cd5x5r = ConvFactory(data=data, num_filter=num_d5x5red, kernel=(1, 1), name=('%s_5x5' % name), suffix='_reduce')
cd5x5 = ConvFactory(data=cd5x5r, num_filter=num_d5x5, kernel=(5, 5), pad=(2, 2), name=('%s_5x5' % name))
# pool + proj
pooling = mx.symbol.Pooling(data=data, kernel=(3, 3), stride=(1, 1), pad=(1, 1), pool_type=pool, name=('%s_pool_%s_pool' % (pool, name)))
cproj = ConvFactory(data=pooling, num_filter=proj, kernel=(1, 1), name=('%s_proj' % name))
# concat
concat = mx.symbol.Concat(*[c1x1, c3x3, cd5x5, cproj], name='ch_concat_%s_chconcat' % name)
return concat
def get_symbol(num_classes = 1000, **kwargs):
data = mx.sym.Variable("data")
conv1 = ConvFactory(data, 64, kernel=(7, 7), stride=(2,2), pad=(3, 3), name="conv1")
pool1 = mx.sym.Pooling(conv1, kernel=(3, 3), stride=(2, 2), pool_type="max")
conv2 = ConvFactory(pool1, 64, kernel=(1, 1), stride=(1,1), name="conv2")
conv3 = ConvFactory(conv2, 192, kernel=(3, 3), stride=(1, 1), pad=(1,1), name="conv3")
pool3 = mx.sym.Pooling(conv3, kernel=(3, 3), stride=(2, 2), pool_type="max")
in3a = InceptionFactory(pool3, 64, 96, 128, 16, 32, "max", 32, name="in3a")
in3b = InceptionFactory(in3a, 128, 128, 192, 32, 96, "max", 64, name="in3b")
pool4 = mx.sym.Pooling(in3b, kernel=(3, 3), stride=(2, 2), pool_type="max")
in4a = InceptionFactory(pool4, 192, 96, 208, 16, 48, "max", 64, name="in4a")
in4b = InceptionFactory(in4a, 160, 112, 224, 24, 64, "max", 64, name="in4b")
in4c = InceptionFactory(in4b, 128, 128, 256, 24, 64, "max", 64, name="in4c")
in4d = InceptionFactory(in4c, 112, 144, 288, 32, 64, "max", 64, name="in4d")
in4e = InceptionFactory(in4d, 256, 160, 320, 32, 128, "max", 128, name="in4e")
pool5 = mx.sym.Pooling(in4e, kernel=(3, 3), stride=(2, 2), pool_type="max")
in5a = InceptionFactory(pool5, 256, 160, 320, 32, 128, "max", 128, name="in5a")
in5b = InceptionFactory(in5a, 384, 192, 384, 48, 128, "max", 128, name="in5b")
pool6 = mx.sym.Pooling(in5b, kernel=(7, 7), stride=(1,1), pool_type="avg")
flatten = mx.sym.Flatten(data=pool6)
fc1 = mx.sym.FullyConnected(data=flatten, num_hidden=num_classes)
softmax = mx.symbol.SoftmaxOutput(data=fc1, name='softmax')
return softmax
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/googlenet.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""References:
Simonyan, Karen, and Andrew Zisserman. "Very deep convolutional networks for
large-scale image recognition." arXiv preprint arXiv:1409.1556 (2014).
"""
import mxnet as mx
import numpy as np
def get_feature(internel_layer, layers, filters, batch_norm = False, **kwargs):
for i, num in enumerate(layers):
for j in range(num):
internel_layer = mx.sym.Convolution(data = internel_layer, kernel=(3, 3), pad=(1, 1), num_filter=filters[i], name="conv%s_%s" %(i + 1, j + 1))
if batch_norm:
internel_layer = mx.symbol.BatchNorm(data=internel_layer, name="bn%s_%s" %(i + 1, j + 1))
internel_layer = mx.sym.Activation(data=internel_layer, act_type="relu", name="relu%s_%s" %(i + 1, j + 1))
internel_layer = mx.sym.Pooling(data=internel_layer, pool_type="max", kernel=(2, 2), stride=(2,2), name="pool%s" %(i + 1))
return internel_layer
def get_classifier(input_data, num_classes, **kwargs):
flatten = mx.sym.Flatten(data=input_data, name="flatten")
fc6 = mx.sym.FullyConnected(data=flatten, num_hidden=4096, name="fc6")
relu6 = mx.sym.Activation(data=fc6, act_type="relu", name="relu6")
drop6 = mx.sym.Dropout(data=relu6, p=0.5, name="drop6")
fc7 = mx.sym.FullyConnected(data=drop6, num_hidden=4096, name="fc7")
relu7 = mx.sym.Activation(data=fc7, act_type="relu", name="relu7")
drop7 = mx.sym.Dropout(data=relu7, p=0.5, name="drop7")
fc8 = mx.sym.FullyConnected(data=drop7, num_hidden=num_classes, name="fc8")
return fc8
def get_symbol(num_classes, num_layers=11, batch_norm=False, dtype='float32', **kwargs):
"""
Parameters
----------
num_classes : int, default 1000
Number of classification classes.
num_layers : int
Number of layers for the variant of densenet. Options are 11, 13, 16, 19.
batch_norm : bool, default False
Use batch normalization.
dtype: str, float32 or float16
Data precision.
"""
vgg_spec = {11: ([1, 1, 2, 2, 2], [64, 128, 256, 512, 512]),
13: ([2, 2, 2, 2, 2], [64, 128, 256, 512, 512]),
16: ([2, 2, 3, 3, 3], [64, 128, 256, 512, 512]),
19: ([2, 2, 4, 4, 4], [64, 128, 256, 512, 512])}
if not vgg_spec.has_key(num_layers):
raise ValueError("Invalide num_layers {}. Possible choices are 11,13,16,19.".format(num_layers))
layers, filters = vgg_spec[num_layers]
data = mx.sym.Variable(name="data")
if dtype == 'float16':
data = mx.sym.Cast(data=data, dtype=np.float16)
feature = get_feature(data, layers, filters, batch_norm)
classifier = get_classifier(feature, num_classes)
if dtype == 'float16':
classifier = mx.sym.Cast(data=classifier, dtype=np.float32)
symbol = mx.sym.SoftmaxOutput(data=classifier, name='softmax')
return symbol
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/vgg.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# -*- coding:utf-8 -*-
__author__ = 'zhangshuai'
modified_date = '16/7/5'
__modify__ = 'anchengwu'
modified_date = '17/2/22'
'''
Inception v4 , suittable for image with around 299 x 299
Reference:
Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning
Christian Szegedy, Sergey Ioffe, Vincent Vanhoucke
arXiv.1602.07261
'''
import mxnet as mx
import numpy as np
def Conv(data, num_filter, kernel=(1, 1), stride=(1, 1), pad=(0, 0), name=None, suffix=''):
conv = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, no_bias=True, name='%s%s_conv2d' %(name, suffix))
bn = mx.sym.BatchNorm(data=conv, name='%s%s_batchnorm' %(name, suffix), fix_gamma=True)
act = mx.sym.Activation(data=bn, act_type='relu', name='%s%s_relu' %(name, suffix))
return act
def Inception_stem(data, name= None):
c = Conv(data, 32, kernel=(3, 3), stride=(2, 2), name='%s_conv1_3*3' %name)
c = Conv(c, 32, kernel=(3, 3), name='%s_conv2_3*3' %name)
c = Conv(c, 64, kernel=(3, 3), pad=(1, 1), name='%s_conv3_3*3' %name)
p1 = mx.sym.Pooling(c, kernel=(3, 3), stride=(2, 2), pool_type='max', name='%s_maxpool_1' %name)
c2 = Conv(c, 96, kernel=(3, 3), stride=(2, 2), name='%s_conv4_3*3' %name)
concat = mx.sym.Concat(*[p1, c2], name='%s_concat_1' %name)
c1 = Conv(concat, 64, kernel=(1, 1), pad=(0, 0), name='%s_conv5_1*1' %name)
c1 = Conv(c1, 96, kernel=(3, 3), name='%s_conv6_3*3' %name)
c2 = Conv(concat, 64, kernel=(1, 1), pad=(0, 0), name='%s_conv7_1*1' %name)
c2 = Conv(c2, 64, kernel=(7, 1), pad=(3, 0), name='%s_conv8_7*1' %name)
c2 = Conv(c2, 64, kernel=(1, 7), pad=(0, 3), name='%s_conv9_1*7' %name)
c2 = Conv(c2, 96, kernel=(3, 3), pad=(0, 0), name='%s_conv10_3*3' %name)
concat = mx.sym.Concat(*[c1, c2], name='%s_concat_2' %name)
c1 = Conv(concat, 192, kernel=(3, 3), stride=(2, 2), name='%s_conv11_3*3' %name)
p1 = mx.sym.Pooling(concat, kernel=(3, 3), stride=(2, 2), pool_type='max', name='%s_maxpool_2' %name)
concat = mx.sym.Concat(*[c1, p1], name='%s_concat_3' %name)
return concat
def InceptionA(input, name=None):
p1 = mx.sym.Pooling(input, kernel=(3, 3), pad=(1, 1), pool_type='avg', name='%s_avgpool_1' %name)
c1 = Conv(p1, 96, kernel=(1, 1), pad=(0, 0), name='%s_conv1_1*1' %name)
c2 = Conv(input, 96, kernel=(1, 1), pad=(0, 0), name='%s_conv2_1*1' %name)
c3 = Conv(input, 64, kernel=(1, 1), pad=(0, 0), name='%s_conv3_1*1' %name)
c3 = Conv(c3, 96, kernel=(3, 3), pad=(1, 1), name='%s_conv4_3*3' %name)
c4 = Conv(input, 64, kernel=(1, 1), pad=(0, 0), name='%s_conv5_1*1' % name)
c4 = Conv(c4, 96, kernel=(3, 3), pad=(1, 1), name='%s_conv6_3*3' % name)
c4 = Conv(c4, 96, kernel=(3, 3), pad=(1, 1), name='%s_conv7_3*3' %name)
concat = mx.sym.Concat(*[c1, c2, c3, c4], name='%s_concat_1' %name)
return concat
def ReductionA(input, name=None):
p1 = mx.sym.Pooling(input, kernel=(3, 3), stride=(2, 2), pool_type='max', name='%s_maxpool_1' %name)
c2 = Conv(input, 384, kernel=(3, 3), stride=(2, 2), name='%s_conv1_3*3' %name)
c3 = Conv(input, 192, kernel=(1, 1), pad=(0, 0), name='%s_conv2_1*1' %name)
c3 = Conv(c3, 224, kernel=(3, 3), pad=(1, 1), name='%s_conv3_3*3' %name)
c3 = Conv(c3, 256, kernel=(3, 3), stride=(2, 2), pad=(0, 0), name='%s_conv4_3*3' %name)
concat = mx.sym.Concat(*[p1, c2, c3], name='%s_concat_1' %name)
return concat
def InceptionB(input, name=None):
p1 = mx.sym.Pooling(input, kernel=(3, 3), pad=(1, 1), pool_type='avg', name='%s_avgpool_1' %name)
c1 = Conv(p1, 128, kernel=(1, 1), pad=(0, 0), name='%s_conv1_1*1' %name)
c2 = Conv(input, 384, kernel=(1, 1), pad=(0, 0), name='%s_conv2_1*1' %name)
c3 = Conv(input, 192, kernel=(1, 1), pad=(0, 0), name='%s_conv3_1*1' %name)
c3 = Conv(c3, 224, kernel=(1, 7), pad=(0, 3), name='%s_conv4_1*7' %name)
#paper wrong
c3 = Conv(c3, 256, kernel=(7, 1), pad=(3, 0), name='%s_conv5_1*7' %name)
c4 = Conv(input, 192, kernel=(1, 1), pad=(0, 0), name='%s_conv6_1*1' %name)
c4 = Conv(c4, 192, kernel=(1, 7), pad=(0, 3), name='%s_conv7_1*7' %name)
c4 = Conv(c4, 224, kernel=(7, 1), pad=(3, 0), name='%s_conv8_7*1' %name)
c4 = Conv(c4, 224, kernel=(1, 7), pad=(0, 3), name='%s_conv9_1*7' %name)
c4 = Conv(c4, 256, kernel=(7, 1), pad=(3, 0), name='%s_conv10_7*1' %name)
concat = mx.sym.Concat(*[c1, c2, c3, c4], name='%s_concat_1' %name)
return concat
def ReductionB(input,name=None):
p1 = mx.sym.Pooling(input, kernel=(3, 3), stride=(2, 2), pool_type='max', name='%s_maxpool_1' %name)
c2 = Conv(input, 192, kernel=(1, 1), pad=(0, 0), name='%s_conv1_1*1' %name)
c2 = Conv(c2, 192, kernel=(3, 3), stride=(2, 2), name='%s_conv2_3*3' %name)
c3 = Conv(input, 256, kernel=(1, 1), pad=(0, 0), name='%s_conv3_1*1' %name)
c3 = Conv(c3, 256, kernel=(1, 7), pad=(0, 3), name='%s_conv4_1*7' %name)
c3 = Conv(c3, 320, kernel=(7, 1), pad=(3, 0), name='%s_conv5_7*1' %name)
c3 = Conv(c3, 320, kernel=(3, 3), stride=(2, 2), name='%s_conv6_3*3' %name)
concat = mx.sym.Concat(*[p1, c2, c3], name='%s_concat_1' %name)
return concat
def InceptionC(input, name=None):
p1 = mx.sym.Pooling(input, kernel=(3, 3), pad=(1, 1), pool_type='avg', name='%s_avgpool_1' %name)
c1 = Conv(p1, 256, kernel=(1, 1), pad=(0, 0), name='%s_conv1_1*1' %name)
c2 = Conv(input, 256, kernel=(1, 1), pad=(0, 0), name='%s_conv2_1*1' %name)
c3 = Conv(input, 384, kernel=(1, 1), pad=(0, 0), name='%s_conv3_1*1' %name)
c3_1 = Conv(c3, 256, kernel=(1, 3), pad=(0, 1), name='%s_conv4_3*1' %name)
c3_2 = Conv(c3, 256, kernel=(3, 1), pad=(1, 0), name='%s_conv5_1*3' %name)
c4 = Conv(input, 384, kernel=(1, 1), pad=(0, 0), name='%s_conv6_1*1' %name)
c4 = Conv(c4, 448, kernel=(1, 3), pad=(0, 1), name='%s_conv7_1*3' %name)
c4 = Conv(c4, 512, kernel=(3, 1), pad=(1, 0), name='%s_conv8_3*1' %name)
c4_1 = Conv(c4, 256, kernel=(3, 1), pad=(1, 0), name='%s_conv9_1*3' %name)
c4_2 = Conv(c4, 256, kernel=(1, 3), pad=(0, 1), name='%s_conv10_3*1' %name)
concat = mx.sym.Concat(*[c1, c2, c3_1, c3_2, c4_1, c4_2], name='%s_concat' %name)
return concat
def get_symbol(num_classes=1000, dtype='float32', **kwargs):
data = mx.sym.Variable(name="data")
if dtype == 'float32':
data = mx.sym.identity(data=data, name='id')
else:
if dtype == 'float16':
data = mx.sym.Cast(data=data, dtype=np.float16)
x = Inception_stem(data, name='in_stem')
#4 * InceptionA
# x = InceptionA(x, name='in1A')
# x = InceptionA(x, name='in2A')
# x = InceptionA(x, name='in3A')
# x = InceptionA(x, name='in4A')
for i in range(4):
x = InceptionA(x, name='in%dA' %(i+1))
#Reduction A
x = ReductionA(x, name='re1A')
#7 * InceptionB
# x = InceptionB(x, name='in1B')
# x = InceptionB(x, name='in2B')
# x = InceptionB(x, name='in3B')
# x = InceptionB(x, name='in4B')
# x = InceptionB(x, name='in5B')
# x = InceptionB(x, name='in6B')
# x = InceptionB(x, name='in7B')
for i in range(7):
x = InceptionB(x, name='in%dB' %(i+1))
#ReductionB
x = ReductionB(x, name='re1B')
#3 * InceptionC
# x = InceptionC(x, name='in1C')
# x = InceptionC(x, name='in2C')
# x = InceptionC(x, name='in3C')
for i in range(3):
x = InceptionC(x, name='in%dC' %(i+1))
#Average Pooling
x = mx.sym.Pooling(x, kernel=(8, 8), pad=(1, 1), pool_type='avg', name='global_avgpool')
#Dropout
x = mx.sym.Dropout(x, p=0.2)
flatten = mx.sym.Flatten(x, name='flatten')
fc1 = mx.sym.FullyConnected(flatten, num_hidden=num_classes, name='fc1')
if dtype == 'float16':
fc1 = mx.sym.Cast(data=fc1, dtype=np.float32)
softmax = mx.sym.SoftmaxOutput(fc1, name='softmax')
return softmax
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/inception-v4.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
'''
Adapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py
(Original author Wei Wu) by Antti-Pekka Hynninen
Implementing the original resnet ILSVRC 2015 winning network from:
Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. "Deep Residual Learning for Image Recognition"
'''
import mxnet as mx
import numpy as np
def residual_unit(data, num_filter, stride, dim_match, name, bottle_neck=True, bn_mom=0.9, workspace=256, memonger=False):
"""Return ResNet Unit symbol for building ResNet
Parameters
----------
data : str
Input data
num_filter : int
Number of output channels
bnf : int
Bottle neck channels factor with regard to num_filter
stride : tuple
Stride used in convolution
dim_match : Boolean
True means channel number between input and output is the same, otherwise means differ
name : str
Base name of the operators
workspace : int
Workspace used in convolution operator
"""
if bottle_neck:
conv1 = mx.sym.Convolution(data=data, num_filter=int(num_filter*0.25), kernel=(1,1), stride=stride, pad=(0,0),
no_bias=True, workspace=workspace, name=name + '_conv1')
bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn1')
act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1')
conv2 = mx.sym.Convolution(data=act1, num_filter=int(num_filter*0.25), kernel=(3,3), stride=(1,1), pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2')
bn2 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn2')
act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2')
conv3 = mx.sym.Convolution(data=act2, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True,
workspace=workspace, name=name + '_conv3')
bn3 = mx.sym.BatchNorm(data=conv3, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn3')
if dim_match:
shortcut = data
else:
conv1sc = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_conv1sc')
shortcut = mx.sym.BatchNorm(data=conv1sc, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_sc')
if memonger:
shortcut._set_attr(mirror_stage='True')
return mx.sym.Activation(data=bn3 + shortcut, act_type='relu', name=name + '_relu3')
else:
conv1 = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(3,3), stride=stride, pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv1')
bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn1')
act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1')
conv2 = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(3,3), stride=(1,1), pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2')
bn2 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn2')
if dim_match:
shortcut = data
else:
conv1sc = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_conv1sc')
shortcut = mx.sym.BatchNorm(data=conv1sc, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_sc')
if memonger:
shortcut._set_attr(mirror_stage='True')
return mx.sym.Activation(data=bn2 + shortcut, act_type='relu', name=name + '_relu3')
def resnet(units, num_stages, filter_list, num_classes, image_shape, bottle_neck=True, bn_mom=0.9, workspace=256, dtype='float32', memonger=False):
"""Return ResNet symbol of
Parameters
----------
units : list
Number of units in each stage
num_stages : int
Number of stage
filter_list : list
Channel size of each stage
num_classes : int
Ouput size of symbol
dataset : str
Dataset type, only cifar10 and imagenet supports
workspace : int
Workspace used in convolution operator
dtype : str
Precision (float32 or float16)
"""
num_unit = len(units)
assert(num_unit == num_stages)
data = mx.sym.Variable(name='data')
if dtype == 'float32':
data = mx.sym.identity(data=data, name='id')
else:
if dtype == 'float16':
data = mx.sym.Cast(data=data, dtype=np.float16)
(nchannel, height, width) = image_shape
if height <= 32: # such as cifar10
body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(3, 3), stride=(1,1), pad=(1, 1),
no_bias=True, name="conv0", workspace=workspace)
# Is this BatchNorm supposed to be here?
body = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name='bn0')
else: # often expected to be 224 such as imagenet
body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(7, 7), stride=(2,2), pad=(3, 3),
no_bias=True, name="conv0", workspace=workspace)
body = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name='bn0')
body = mx.sym.Activation(data=body, act_type='relu', name='relu0')
body = mx.sym.Pooling(data=body, kernel=(3, 3), stride=(2,2), pad=(1,1), pool_type='max')
for i in range(num_stages):
body = residual_unit(body, filter_list[i+1], (1 if i==0 else 2, 1 if i==0 else 2), False,
name='stage%d_unit%d' % (i + 1, 1), bottle_neck=bottle_neck, workspace=workspace,
memonger=memonger)
for j in range(units[i]-1):
body = residual_unit(body, filter_list[i+1], (1,1), True, name='stage%d_unit%d' % (i + 1, j + 2),
bottle_neck=bottle_neck, workspace=workspace, memonger=memonger)
# bn1 = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name='bn1')
# relu1 = mx.sym.Activation(data=bn1, act_type='relu', name='relu1')
# Although kernel is not used here when global_pool=True, we should put one
pool1 = mx.sym.Pooling(data=body, global_pool=True, kernel=(7, 7), pool_type='avg', name='pool1')
flat = mx.sym.Flatten(data=pool1)
fc1 = mx.sym.FullyConnected(data=flat, num_hidden=num_classes, name='fc1')
if dtype == 'float16':
fc1 = mx.sym.Cast(data=fc1, dtype=np.float32)
return mx.sym.SoftmaxOutput(data=fc1, name='softmax')
def get_symbol(num_classes, num_layers, image_shape, conv_workspace=256, dtype='float32', **kwargs):
"""
Adapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py
(Original author Wei Wu) by Antti-Pekka Hynninen
Implementing the original resnet ILSVRC 2015 winning network from:
Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. "Deep Residual Learning for Image Recognition"
"""
image_shape = [int(l) for l in image_shape.split(',')]
(nchannel, height, width) = image_shape
if height <= 28:
num_stages = 3
if (num_layers-2) % 9 == 0 and num_layers >= 164:
per_unit = [(num_layers-2)//9]
filter_list = [16, 64, 128, 256]
bottle_neck = True
elif (num_layers-2) % 6 == 0 and num_layers < 164:
per_unit = [(num_layers-2)//6]
filter_list = [16, 16, 32, 64]
bottle_neck = False
else:
raise ValueError("no experiments done on num_layers {}, you can do it yourself".format(num_layers))
units = per_unit * num_stages
else:
if num_layers >= 50:
filter_list = [64, 256, 512, 1024, 2048]
bottle_neck = True
else:
filter_list = [64, 64, 128, 256, 512]
bottle_neck = False
num_stages = 4
if num_layers == 18:
units = [2, 2, 2, 2]
elif num_layers == 34:
units = [3, 4, 6, 3]
elif num_layers == 50:
units = [3, 4, 6, 3]
elif num_layers == 101:
units = [3, 4, 23, 3]
elif num_layers == 152:
units = [3, 8, 36, 3]
elif num_layers == 200:
units = [3, 24, 36, 3]
elif num_layers == 269:
units = [3, 30, 48, 8]
else:
raise ValueError("no experiments done on num_layers {}, you can do it yourself".format(num_layers))
return resnet(units = units,
num_stages = num_stages,
filter_list = filter_list,
num_classes = num_classes,
image_shape = image_shape,
bottle_neck = bottle_neck,
workspace = conv_workspace,
dtype = dtype)
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/resnet-v1.py
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/__init__.py
|
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""
a simple multilayer perceptron
"""
import mxnet as mx
def get_symbol(num_classes=10, **kwargs):
data = mx.symbol.Variable('data')
data = mx.sym.Flatten(data=data)
fc1 = mx.symbol.FullyConnected(data = data, name='fc1', num_hidden=128)
act1 = mx.symbol.Activation(data = fc1, name='relu1', act_type="relu")
fc2 = mx.symbol.FullyConnected(data = act1, name = 'fc2', num_hidden = 64)
act2 = mx.symbol.Activation(data = fc2, name='relu2', act_type="relu")
fc3 = mx.symbol.FullyConnected(data = act2, name='fc3', num_hidden=num_classes)
mlp = mx.symbol.SoftmaxOutput(data = fc3, name = 'softmax')
return mlp
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/mlp.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
'''
Adapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py
Original author Wei Wu
Implemented the following paper:
Saining Xie, Ross Girshick, Piotr Dollar, Zhuowen Tu, Kaiming He. "Aggregated Residual Transformations for Deep Neural Network"
'''
import mxnet as mx
import numpy as np
def residual_unit(data, num_filter, stride, dim_match, name, bottle_neck=True, num_group=32, bn_mom=0.9, workspace=256, memonger=False):
"""Return ResNet Unit symbol for building ResNet
Parameters
----------
data : str
Input data
num_filter : int
Number of output channels
bnf : int
Bottle neck channels factor with regard to num_filter
stride : tuple
Stride used in convolution
dim_match : Boolean
True means channel number between input and output is the same, otherwise means differ
name : str
Base name of the operators
workspace : int
Workspace used in convolution operator
"""
if bottle_neck:
# the same as https://github.com/facebook/fb.resnet.torch#notes, a bit difference with origin paper
conv1 = mx.sym.Convolution(data=data, num_filter=int(num_filter*0.5), kernel=(1,1), stride=(1,1), pad=(0,0),
no_bias=True, workspace=workspace, name=name + '_conv1')
bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn1')
act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1')
conv2 = mx.sym.Convolution(data=act1, num_filter=int(num_filter*0.5), num_group=num_group, kernel=(3,3), stride=stride, pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2')
bn2 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn2')
act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2')
conv3 = mx.sym.Convolution(data=act2, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True,
workspace=workspace, name=name + '_conv3')
bn3 = mx.sym.BatchNorm(data=conv3, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn3')
if dim_match:
shortcut = data
else:
shortcut_conv = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_sc')
shortcut = mx.sym.BatchNorm(data=shortcut_conv, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_sc_bn')
if memonger:
shortcut._set_attr(mirror_stage='True')
eltwise = bn3 + shortcut
return mx.sym.Activation(data=eltwise, act_type='relu', name=name + '_relu')
else:
conv1 = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(3,3), stride=stride, pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv1')
bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn1')
act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1')
conv2 = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(3,3), stride=(1,1), pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2')
bn2 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn2')
if dim_match:
shortcut = data
else:
shortcut_conv = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_sc')
shortcut = mx.sym.BatchNorm(data=shortcut_conv, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_sc_bn')
if memonger:
shortcut._set_attr(mirror_stage='True')
eltwise = bn2 + shortcut
return mx.sym.Activation(data=eltwise, act_type='relu', name=name + '_relu')
def resnext(units, num_stages, filter_list, num_classes, num_group, image_shape, bottle_neck=True, bn_mom=0.9, workspace=256, dtype='float32', memonger=False):
"""Return ResNeXt symbol of
Parameters
----------
units : list
Number of units in each stage
num_stages : int
Number of stage
filter_list : list
Channel size of each stage
num_classes : int
Ouput size of symbol
num_groupes: int
Number of conv groups
dataset : str
Dataset type, only cifar10 and imagenet supports
workspace : int
Workspace used in convolution operator
dtype : str
Precision (float32 or float16)
"""
num_unit = len(units)
assert(num_unit == num_stages)
data = mx.sym.Variable(name='data')
if dtype == 'float32':
data = mx.sym.identity(data=data, name='id')
else:
if dtype == 'float16':
data = mx.sym.Cast(data=data, dtype=np.float16)
data = mx.sym.BatchNorm(data=data, fix_gamma=True, eps=2e-5, momentum=bn_mom, name='bn_data')
(nchannel, height, width) = image_shape
if height <= 32: # such as cifar10
body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(3, 3), stride=(1,1), pad=(1, 1),
no_bias=True, name="conv0", workspace=workspace)
else: # often expected to be 224 such as imagenet
body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(7, 7), stride=(2,2), pad=(3, 3),
no_bias=True, name="conv0", workspace=workspace)
body = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name='bn0')
body = mx.sym.Activation(data=body, act_type='relu', name='relu0')
body = mx.sym.Pooling(data=body, kernel=(3, 3), stride=(2,2), pad=(1,1), pool_type='max')
for i in range(num_stages):
body = residual_unit(body, filter_list[i+1], (1 if i==0 else 2, 1 if i==0 else 2), False,
name='stage%d_unit%d' % (i + 1, 1), bottle_neck=bottle_neck, num_group=num_group,
bn_mom=bn_mom, workspace=workspace, memonger=memonger)
for j in range(units[i]-1):
body = residual_unit(body, filter_list[i+1], (1,1), True, name='stage%d_unit%d' % (i + 1, j + 2),
bottle_neck=bottle_neck, num_group=num_group, bn_mom=bn_mom, workspace=workspace, memonger=memonger)
pool1 = mx.sym.Pooling(data=body, global_pool=True, kernel=(7, 7), pool_type='avg', name='pool1')
flat = mx.sym.Flatten(data=pool1)
fc1 = mx.sym.FullyConnected(data=flat, num_hidden=num_classes, name='fc1')
if dtype == 'float16':
fc1 = mx.sym.Cast(data=fc1, dtype=np.float32)
return mx.sym.SoftmaxOutput(data=fc1, name='softmax')
def get_symbol(num_classes, num_layers, image_shape, num_group=32, conv_workspace=256, dtype='float32', **kwargs):
"""
Adapted from https://github.com/tornadomeet/ResNet/blob/master/train_resnet.py
Original author Wei Wu
"""
image_shape = [int(l) for l in image_shape.split(',')]
(nchannel, height, width) = image_shape
if height <= 32:
num_stages = 3
if (num_layers-2) % 9 == 0 and num_layers >= 164:
per_unit = [(num_layers-2)//9]
filter_list = [16, 64, 128, 256]
bottle_neck = True
elif (num_layers-2) % 6 == 0 and num_layers < 164:
per_unit = [(num_layers-2)//6]
filter_list = [16, 16, 32, 64]
bottle_neck = False
else:
raise ValueError("no experiments done on num_layers {}, you can do it yourself".format(num_layers))
units = per_unit * num_stages
else:
if num_layers >= 50:
filter_list = [64, 256, 512, 1024, 2048]
bottle_neck = True
else:
filter_list = [64, 64, 128, 256, 512]
bottle_neck = False
num_stages = 4
if num_layers == 18:
units = [2, 2, 2, 2]
elif num_layers == 34:
units = [3, 4, 6, 3]
elif num_layers == 50:
units = [3, 4, 6, 3]
elif num_layers == 101:
units = [3, 4, 23, 3]
elif num_layers == 152:
units = [3, 8, 36, 3]
elif num_layers == 200:
units = [3, 24, 36, 3]
elif num_layers == 269:
units = [3, 30, 48, 8]
else:
raise ValueError("no experiments done on num_layers {}, you can do it yourself".format(num_layers))
return resnext(units = units,
num_stages = num_stages,
filter_list = filter_list,
num_classes = num_classes,
num_group = num_group,
image_shape = image_shape,
bottle_neck = bottle_neck,
workspace = conv_workspace,
dtype = dtype)
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/resnext.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""
Contains the definition of the Inception Resnet V2 architecture.
As described in http://arxiv.org/abs/1602.07261.
Inception-v4, Inception-ResNet and the Impact of Residual Connections
on Learning
Christian Szegedy, Sergey Ioffe, Vincent Vanhoucke, Alex Alemi
"""
import mxnet as mx
def ConvFactory(data, num_filter, kernel, stride=(1, 1), pad=(0, 0), act_type="relu", mirror_attr={}, with_act=True):
conv = mx.symbol.Convolution(
data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad)
bn = mx.symbol.BatchNorm(data=conv)
if with_act:
act = mx.symbol.Activation(
data=bn, act_type=act_type, attr=mirror_attr)
return act
else:
return bn
def block35(net, input_num_channels, scale=1.0, with_act=True, act_type='relu', mirror_attr={}):
tower_conv = ConvFactory(net, 32, (1, 1))
tower_conv1_0 = ConvFactory(net, 32, (1, 1))
tower_conv1_1 = ConvFactory(tower_conv1_0, 32, (3, 3), pad=(1, 1))
tower_conv2_0 = ConvFactory(net, 32, (1, 1))
tower_conv2_1 = ConvFactory(tower_conv2_0, 48, (3, 3), pad=(1, 1))
tower_conv2_2 = ConvFactory(tower_conv2_1, 64, (3, 3), pad=(1, 1))
tower_mixed = mx.symbol.Concat(*[tower_conv, tower_conv1_1, tower_conv2_2])
tower_out = ConvFactory(
tower_mixed, input_num_channels, (1, 1), with_act=False)
net += scale * tower_out
if with_act:
act = mx.symbol.Activation(
data=net, act_type=act_type, attr=mirror_attr)
return act
else:
return net
def block17(net, input_num_channels, scale=1.0, with_act=True, act_type='relu', mirror_attr={}):
tower_conv = ConvFactory(net, 192, (1, 1))
tower_conv1_0 = ConvFactory(net, 129, (1, 1))
tower_conv1_1 = ConvFactory(tower_conv1_0, 160, (1, 7), pad=(1, 2))
tower_conv1_2 = ConvFactory(tower_conv1_1, 192, (7, 1), pad=(2, 1))
tower_mixed = mx.symbol.Concat(*[tower_conv, tower_conv1_2])
tower_out = ConvFactory(
tower_mixed, input_num_channels, (1, 1), with_act=False)
net += scale * tower_out
if with_act:
act = mx.symbol.Activation(
data=net, act_type=act_type, attr=mirror_attr)
return act
else:
return net
def block8(net, input_num_channels, scale=1.0, with_act=True, act_type='relu', mirror_attr={}):
tower_conv = ConvFactory(net, 192, (1, 1))
tower_conv1_0 = ConvFactory(net, 192, (1, 1))
tower_conv1_1 = ConvFactory(tower_conv1_0, 224, (1, 3), pad=(0, 1))
tower_conv1_2 = ConvFactory(tower_conv1_1, 256, (3, 1), pad=(1, 0))
tower_mixed = mx.symbol.Concat(*[tower_conv, tower_conv1_2])
tower_out = ConvFactory(
tower_mixed, input_num_channels, (1, 1), with_act=False)
net += scale * tower_out
if with_act:
act = mx.symbol.Activation(
data=net, act_type=act_type, attr=mirror_attr)
return act
else:
return net
def repeat(inputs, repetitions, layer, *args, **kwargs):
outputs = inputs
for i in range(repetitions):
outputs = layer(outputs, *args, **kwargs)
return outputs
def get_symbol(num_classes=1000, **kwargs):
data = mx.symbol.Variable(name='data')
conv1a_3_3 = ConvFactory(data=data, num_filter=32,
kernel=(3, 3), stride=(2, 2))
conv2a_3_3 = ConvFactory(conv1a_3_3, 32, (3, 3))
conv2b_3_3 = ConvFactory(conv2a_3_3, 64, (3, 3), pad=(1, 1))
maxpool3a_3_3 = mx.symbol.Pooling(
data=conv2b_3_3, kernel=(3, 3), stride=(2, 2), pool_type='max')
conv3b_1_1 = ConvFactory(maxpool3a_3_3, 80, (1, 1))
conv4a_3_3 = ConvFactory(conv3b_1_1, 192, (3, 3))
maxpool5a_3_3 = mx.symbol.Pooling(
data=conv4a_3_3, kernel=(3, 3), stride=(2, 2), pool_type='max')
tower_conv = ConvFactory(maxpool5a_3_3, 96, (1, 1))
tower_conv1_0 = ConvFactory(maxpool5a_3_3, 48, (1, 1))
tower_conv1_1 = ConvFactory(tower_conv1_0, 64, (5, 5), pad=(2, 2))
tower_conv2_0 = ConvFactory(maxpool5a_3_3, 64, (1, 1))
tower_conv2_1 = ConvFactory(tower_conv2_0, 96, (3, 3), pad=(1, 1))
tower_conv2_2 = ConvFactory(tower_conv2_1, 96, (3, 3), pad=(1, 1))
tower_pool3_0 = mx.symbol.Pooling(data=maxpool5a_3_3, kernel=(
3, 3), stride=(1, 1), pad=(1, 1), pool_type='avg')
tower_conv3_1 = ConvFactory(tower_pool3_0, 64, (1, 1))
tower_5b_out = mx.symbol.Concat(
*[tower_conv, tower_conv1_1, tower_conv2_2, tower_conv3_1])
net = repeat(tower_5b_out, 10, block35, scale=0.17, input_num_channels=320)
tower_conv = ConvFactory(net, 384, (3, 3), stride=(2, 2))
tower_conv1_0 = ConvFactory(net, 256, (1, 1))
tower_conv1_1 = ConvFactory(tower_conv1_0, 256, (3, 3), pad=(1, 1))
tower_conv1_2 = ConvFactory(tower_conv1_1, 384, (3, 3), stride=(2, 2))
tower_pool = mx.symbol.Pooling(net, kernel=(
3, 3), stride=(2, 2), pool_type='max')
net = mx.symbol.Concat(*[tower_conv, tower_conv1_2, tower_pool])
net = repeat(net, 20, block17, scale=0.1, input_num_channels=1088)
tower_conv = ConvFactory(net, 256, (1, 1))
tower_conv0_1 = ConvFactory(tower_conv, 384, (3, 3), stride=(2, 2))
tower_conv1 = ConvFactory(net, 256, (1, 1))
tower_conv1_1 = ConvFactory(tower_conv1, 288, (3, 3), stride=(2, 2))
tower_conv2 = ConvFactory(net, 256, (1, 1))
tower_conv2_1 = ConvFactory(tower_conv2, 288, (3, 3), pad=(1, 1))
tower_conv2_2 = ConvFactory(tower_conv2_1, 320, (3, 3), stride=(2, 2))
tower_pool = mx.symbol.Pooling(net, kernel=(
3, 3), stride=(2, 2), pool_type='max')
net = mx.symbol.Concat(
*[tower_conv0_1, tower_conv1_1, tower_conv2_2, tower_pool])
net = repeat(net, 9, block8, scale=0.2, input_num_channels=2080)
net = block8(net, with_act=False, input_num_channels=2080)
net = ConvFactory(net, 1536, (1, 1))
net = mx.symbol.Pooling(net, kernel=(
1, 1), global_pool=True, stride=(2, 2), pool_type='avg')
net = mx.symbol.Flatten(net)
net = mx.symbol.Dropout(data=net, p=0.2)
net = mx.symbol.FullyConnected(data=net, num_hidden=num_classes)
softmax = mx.symbol.SoftmaxOutput(data=net, name='softmax')
return softmax
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/inception-resnet-v2.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""
LeCun, Yann, Leon Bottou, Yoshua Bengio, and Patrick Haffner.
Gradient-based learning applied to document recognition.
Proceedings of the IEEE (1998)
"""
import mxnet as mx
def get_loc(data, attr={'lr_mult':'0.01'}):
"""
the localisation network in lenet-stn, it will increase acc about more than 1%,
when num-epoch >=15
"""
loc = mx.symbol.Convolution(data=data, num_filter=30, kernel=(5, 5), stride=(2,2))
loc = mx.symbol.Activation(data = loc, act_type='relu')
loc = mx.symbol.Pooling(data=loc, kernel=(2, 2), stride=(2, 2), pool_type='max')
loc = mx.symbol.Convolution(data=loc, num_filter=60, kernel=(3, 3), stride=(1,1), pad=(1, 1))
loc = mx.symbol.Activation(data = loc, act_type='relu')
loc = mx.symbol.Pooling(data=loc, global_pool=True, kernel=(2, 2), pool_type='avg')
loc = mx.symbol.Flatten(data=loc)
loc = mx.symbol.FullyConnected(data=loc, num_hidden=6, name="stn_loc", attr=attr)
return loc
def get_symbol(num_classes=10, add_stn=False, **kwargs):
data = mx.symbol.Variable('data')
if add_stn:
data = mx.sym.SpatialTransformer(data=data, loc=get_loc(data), target_shape = (28,28),
transform_type="affine", sampler_type="bilinear")
# first conv
conv1 = mx.symbol.Convolution(data=data, kernel=(5,5), num_filter=20)
tanh1 = mx.symbol.Activation(data=conv1, act_type="tanh")
pool1 = mx.symbol.Pooling(data=tanh1, pool_type="max",
kernel=(2,2), stride=(2,2))
# second conv
conv2 = mx.symbol.Convolution(data=pool1, kernel=(5,5), num_filter=50)
tanh2 = mx.symbol.Activation(data=conv2, act_type="tanh")
pool2 = mx.symbol.Pooling(data=tanh2, pool_type="max",
kernel=(2,2), stride=(2,2))
# first fullc
flatten = mx.symbol.Flatten(data=pool2)
fc1 = mx.symbol.FullyConnected(data=flatten, num_hidden=500)
tanh3 = mx.symbol.Activation(data=fc1, act_type="tanh")
# second fullc
fc2 = mx.symbol.FullyConnected(data=tanh3, num_hidden=num_classes)
# loss
lenet = mx.symbol.SoftmaxOutput(data=fc2, name='softmax')
return lenet
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/lenet.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# -*- coding:utf-8 -*-
'''
mobilenet
Suittable for image with around resolution x resolution, resolution is multiple of 32.
Reference:
MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications
https://arxiv.org/abs/1704.04861
'''
__author__ = 'qingzhouzhen'
__date__ = '17/8/5'
__modify__ = 'dwSun'
__modified_date__ = '17/11/30'
import mxnet as mx
alpha_values = [0.25, 0.50, 0.75, 1.0]
def Conv(data, num_filter=1, kernel=(1, 1), stride=(1, 1), pad=(0, 0), num_group=1, name='', suffix=''):
conv = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=kernel, num_group=num_group, stride=stride, pad=pad, no_bias=True, name='%s%s_conv2d' % (name, suffix))
bn = mx.sym.BatchNorm(data=conv, name='%s%s_batchnorm' % (name, suffix), fix_gamma=True)
act = mx.sym.Activation(data=bn, act_type='relu', name='%s%s_relu' % (name, suffix))
return act
def Conv_DPW(data, depth=1, stride=(1, 1), name='', idx=0, suffix=''):
conv_dw = Conv(data, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=stride, name="conv_%d_dw" % (idx), suffix=suffix)
conv = Conv(conv_dw, num_filter=depth * stride[0], kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_%d" % (idx), suffix=suffix)
return conv
def get_symbol_compact(num_classes, alpha=1, resolution=224, **kwargs):
assert alpha in alpha_values, 'Invalid alpha={0}, must be one of {1}'.format(alpha, alpha_values)
assert resolution % 32 == 0, 'resolution must be multiple of 32'
base = int(32 * alpha)
data = mx.symbol.Variable(name="data") # 224
conv_1 = Conv(data, num_filter=base, kernel=(3, 3), pad=(1, 1), stride=(2, 2), name="conv_1") # 32*alpha, 224/112
conv_2_dw = Conv(conv_1, num_group=base, num_filter=base, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name="conv_2_dw") # 112/112
conv_2 = Conv(conv_2_dw, num_filter=base * 2, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_2") # 32*alpha, 112/112
conv_3_dpw = Conv_DPW(conv_2, depth=base * 2, stride=(2, 2), idx=3) # 64*alpha, 112/56 => 56/56
conv_4_dpw = Conv_DPW(conv_3_dpw, depth=base * 4, stride=(1, 1), idx=4) # 128*alpha, 56/56 =>56/56
conv_5_dpw = Conv_DPW(conv_4_dpw, depth=base * 4, stride=(2, 2), idx=5) # 128*alpha, 56/28 => 28/28
conv_6_dpw = Conv_DPW(conv_5_dpw, depth=base * 8, stride=(1, 1), idx=6) # 256*alpha, 28/28 => 28/28
conv_7_dpw = Conv_DPW(conv_6_dpw, depth=base * 8, stride=(2, 2), idx=7) # 256*alpha, 28/14 => 14/14
conv_dpw = conv_7_dpw
for idx in range(8, 13):
conv_dpw = Conv_DPW(conv_dpw, depth=base * 16, stride=(1, 1), idx=idx) # 512*alpha, 14/14
conv_12_dpw = conv_dpw
conv_13_dpw = Conv_DPW(conv_12_dpw, depth=base * 16, stride=(2, 2), idx=13) # 512*alpha, 14/7 => 7/7
conv_14_dpw = Conv_DPW(conv_13_dpw, depth=base * 32, stride=(1, 1), idx=14) # 1024*alpha, 7/7 => 7/7
pool_size = int(resolution / 32)
pool = mx.sym.Pooling(data=conv_14_dpw, kernel=(pool_size, pool_size), stride=(1, 1), pool_type="avg", name="global_pool")
flatten = mx.sym.Flatten(data=pool, name="flatten")
fc = mx.symbol.FullyConnected(data=flatten, num_hidden=num_classes, name='fc')
softmax = mx.symbol.SoftmaxOutput(data=fc, name='softmax')
return softmax
def get_symbol(num_classes, alpha=1, resolution=224, **kwargs):
assert alpha in alpha_values, 'Invalid alpha=[{0}], must be one of [{1}]'.format(alpha, alpha_values)
assert resolution % 32 == 0, 'resolution must be multpile of 32'
base = int(32 * alpha)
data = mx.symbol.Variable(name="data") # 224
depth = base # 32*alpha
conv_1 = Conv(data, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(2, 2), name="conv_1") # 224/112
depth = base # 32*alpha
conv_2_dw = Conv(conv_1, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name="conv_2_dw") # 112/112
conv_2 = Conv(conv_2_dw, num_filter=depth * 2, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_2") # 112/112
depth = base * 2 # 64*alpha
conv_3_dw = Conv(conv_2, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(2, 2), name="conv_3_dw") # 112/56
conv_3 = Conv(conv_3_dw, num_filter=depth * 2, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_3") # 56/56
depth = base * 4 # 128*alpha
conv_4_dw = Conv(conv_3, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name="conv_4_dw") # 56/56
conv_4 = Conv(conv_4_dw, num_filter=depth, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_4") # 56/56
depth = base * 4 # 128*alpha
conv_5_dw = Conv(conv_4, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(2, 2), name="conv_5_dw") # 56/28
conv_5 = Conv(conv_5_dw, num_filter=depth * 2, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_5") # 28/28
depth = base * 8 # 256*alpha
conv_6_dw = Conv(conv_5, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name="conv_6_dw") # 28/28
conv_6 = Conv(conv_6_dw, num_filter=depth, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_6") # 28/28
depth = base * 8 # 256*alpha
conv_7_dw = Conv(conv_6, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(2, 2), name="conv_7_dw") # 28/14
conv_7 = Conv(conv_7_dw, num_filter=depth * 2, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_7") # 14/14
depth = base * 16 # 512*alpha
conv_8_dw = Conv(conv_7, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name="conv_8_dw") # 14/14
conv_8 = Conv(conv_8_dw, num_filter=depth, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_8") # 14/14
conv_9_dw = Conv(conv_8, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name="conv_9_dw") # 14/14
conv_9 = Conv(conv_9_dw, num_filter=depth, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_9") # 14/14
conv_10_dw = Conv(conv_9, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name="conv_10_dw") # 14/14
conv_10 = Conv(conv_10_dw, num_filter=depth, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_10") # 14/14
conv_11_dw = Conv(conv_10, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name="conv_11_dw") # 14/14
conv_11 = Conv(conv_11_dw, num_filter=depth, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_11") # 14/14
conv_12_dw = Conv(conv_11, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name="conv_12_dw") # 14/14
conv_12 = Conv(conv_12_dw, num_filter=depth, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_12") # 14/14
depth = base * 16 # 512*alpha
conv_13_dw = Conv(conv_12, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(2, 2), name="conv_13_dw") # 14/7
conv_13 = Conv(conv_13_dw, num_filter=depth * 2, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_13") # 7/7
depth = base * 32 # 1024*alpha
conv_14_dw = Conv(conv_13, num_group=depth, num_filter=depth, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name="conv_14_dw") # 7/7
conv_14 = Conv(conv_14_dw, num_filter=depth, kernel=(1, 1), pad=(0, 0), stride=(1, 1), name="conv_14") # 7/7
pool_size = int(resolution / 32)
pool = mx.sym.Pooling(data=conv_14, kernel=(pool_size, pool_size), stride=(1, 1), pool_type="avg", name="global_pool")
flatten = mx.sym.Flatten(data=pool, name="flatten")
fc = mx.symbol.FullyConnected(data=flatten, num_hidden=num_classes, name='fc')
softmax = mx.symbol.SoftmaxOutput(data=fc, name='softmax')
return softmax
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/mobilenet.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""
Inception + BN, suitable for images with around 224 x 224
Reference:
Sergey Ioffe and Christian Szegedy. Batch normalization: Accelerating deep
network training by reducing internal covariate shift. arXiv preprint
arXiv:1502.03167, 2015.
"""
import mxnet as mx
eps = 1e-10 + 1e-5
bn_mom = 0.9
fix_gamma = False
def ConvFactory(data, num_filter, kernel, stride=(1,1), pad=(0, 0), name=None, suffix='', attr={}):
conv = mx.symbol.Convolution(data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, name='conv_%s%s' %(name, suffix))
bn = mx.symbol.BatchNorm(data=conv, fix_gamma=fix_gamma, eps=eps, momentum=bn_mom, name='bn_%s%s' %(name, suffix))
act = mx.symbol.Activation(data=bn, act_type='relu', name='relu_%s%s' %(name, suffix), attr=attr)
return act
def InceptionFactoryA(data, num_1x1, num_3x3red, num_3x3, num_d3x3red, num_d3x3, pool, proj, name):
# 1x1
c1x1 = ConvFactory(data=data, num_filter=num_1x1, kernel=(1, 1), name=('%s_1x1' % name))
# 3x3 reduce + 3x3
c3x3r = ConvFactory(data=data, num_filter=num_3x3red, kernel=(1, 1), name=('%s_3x3' % name), suffix='_reduce')
c3x3 = ConvFactory(data=c3x3r, num_filter=num_3x3, kernel=(3, 3), pad=(1, 1), name=('%s_3x3' % name))
# double 3x3 reduce + double 3x3
cd3x3r = ConvFactory(data=data, num_filter=num_d3x3red, kernel=(1, 1), name=('%s_double_3x3' % name), suffix='_reduce')
cd3x3 = ConvFactory(data=cd3x3r, num_filter=num_d3x3, kernel=(3, 3), pad=(1, 1), name=('%s_double_3x3_0' % name))
cd3x3 = ConvFactory(data=cd3x3, num_filter=num_d3x3, kernel=(3, 3), pad=(1, 1), name=('%s_double_3x3_1' % name))
# pool + proj
pooling = mx.symbol.Pooling(data=data, kernel=(3, 3), stride=(1, 1), pad=(1, 1), pool_type=pool, name=('%s_pool_%s_pool' % (pool, name)))
cproj = ConvFactory(data=pooling, num_filter=proj, kernel=(1, 1), name=('%s_proj' % name))
# concat
concat = mx.symbol.Concat(*[c1x1, c3x3, cd3x3, cproj], name='ch_concat_%s_chconcat' % name)
return concat
def InceptionFactoryB(data, num_3x3red, num_3x3, num_d3x3red, num_d3x3, name):
# 3x3 reduce + 3x3
c3x3r = ConvFactory(data=data, num_filter=num_3x3red, kernel=(1, 1), name=('%s_3x3' % name), suffix='_reduce')
c3x3 = ConvFactory(data=c3x3r, num_filter=num_3x3, kernel=(3, 3), pad=(1, 1), stride=(2, 2), name=('%s_3x3' % name))
# double 3x3 reduce + double 3x3
cd3x3r = ConvFactory(data=data, num_filter=num_d3x3red, kernel=(1, 1), name=('%s_double_3x3' % name), suffix='_reduce')
cd3x3 = ConvFactory(data=cd3x3r, num_filter=num_d3x3, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name=('%s_double_3x3_0' % name))
cd3x3 = ConvFactory(data=cd3x3, num_filter=num_d3x3, kernel=(3, 3), pad=(1, 1), stride=(2, 2), name=('%s_double_3x3_1' % name))
# pool + proj
pooling = mx.symbol.Pooling(data=data, kernel=(3, 3), stride=(2, 2), pad=(1, 1), pool_type="max", name=('max_pool_%s_pool' % name))
# concat
concat = mx.symbol.Concat(*[c3x3, cd3x3, pooling], name='ch_concat_%s_chconcat' % name)
return concat
# A Simple Downsampling Factory
def DownsampleFactory(data, ch_3x3, name, attr):
# conv 3x3
conv = ConvFactory(data=data, name=name+'_conv',kernel=(3, 3), stride=(2, 2), num_filter=ch_3x3, pad=(1, 1), attr=attr)
# pool
pool = mx.symbol.Pooling(data=data, name=name+'_pool',kernel=(3, 3), stride=(2, 2), pad=(1, 1), pool_type='max', attr=attr)
# concat
concat = mx.symbol.Concat(*[conv, pool], name=name+'_ch_concat')
return concat
# A Simple module
def SimpleFactory(data, ch_1x1, ch_3x3, name, attr):
# 1x1
conv1x1 = ConvFactory(data=data, name=name+'_1x1', kernel=(1, 1), pad=(0, 0), num_filter=ch_1x1, attr=attr)
# 3x3
conv3x3 = ConvFactory(data=data, name=name+'_3x3', kernel=(3, 3), pad=(1, 1), num_filter=ch_3x3, attr=attr)
#concat
concat = mx.symbol.Concat(*[conv1x1, conv3x3], name=name+'_ch_concat')
return concat
def get_symbol(num_classes, image_shape, **kwargs):
image_shape = [int(l) for l in image_shape.split(',')]
(nchannel, height, width) = image_shape
# attr = {'force_mirroring': 'true'}
attr = {}
# data
data = mx.symbol.Variable(name="data")
if height <= 28:
# a simper version
conv1 = ConvFactory(data=data, kernel=(3,3), pad=(1,1), name="1", num_filter=96, attr=attr)
in3a = SimpleFactory(conv1, 32, 32, 'in3a', attr)
in3b = SimpleFactory(in3a, 32, 48, 'in3b', attr)
in3c = DownsampleFactory(in3b, 80, 'in3c', attr)
in4a = SimpleFactory(in3c, 112, 48, 'in4a', attr)
in4b = SimpleFactory(in4a, 96, 64, 'in4b', attr)
in4c = SimpleFactory(in4b, 80, 80, 'in4c', attr)
in4d = SimpleFactory(in4c, 48, 96, 'in4d', attr)
in4e = DownsampleFactory(in4d, 96, 'in4e', attr)
in5a = SimpleFactory(in4e, 176, 160, 'in5a', attr)
in5b = SimpleFactory(in5a, 176, 160, 'in5b', attr)
pool = mx.symbol.Pooling(data=in5b, pool_type="avg", kernel=(7,7), name="global_pool", attr=attr)
else:
# stage 1
conv1 = ConvFactory(data=data, num_filter=64, kernel=(7, 7), stride=(2, 2), pad=(3, 3), name='1')
pool1 = mx.symbol.Pooling(data=conv1, kernel=(3, 3), stride=(2, 2), name='pool_1', pool_type='max')
# stage 2
conv2red = ConvFactory(data=pool1, num_filter=64, kernel=(1, 1), stride=(1, 1), name='2_red')
conv2 = ConvFactory(data=conv2red, num_filter=192, kernel=(3, 3), stride=(1, 1), pad=(1, 1), name='2')
pool2 = mx.symbol.Pooling(data=conv2, kernel=(3, 3), stride=(2, 2), name='pool_2', pool_type='max')
# stage 2
in3a = InceptionFactoryA(pool2, 64, 64, 64, 64, 96, "avg", 32, '3a')
in3b = InceptionFactoryA(in3a, 64, 64, 96, 64, 96, "avg", 64, '3b')
in3c = InceptionFactoryB(in3b, 128, 160, 64, 96, '3c')
# stage 3
in4a = InceptionFactoryA(in3c, 224, 64, 96, 96, 128, "avg", 128, '4a')
in4b = InceptionFactoryA(in4a, 192, 96, 128, 96, 128, "avg", 128, '4b')
in4c = InceptionFactoryA(in4b, 160, 128, 160, 128, 160, "avg", 128, '4c')
in4d = InceptionFactoryA(in4c, 96, 128, 192, 160, 192, "avg", 128, '4d')
in4e = InceptionFactoryB(in4d, 128, 192, 192, 256, '4e')
# stage 4
in5a = InceptionFactoryA(in4e, 352, 192, 320, 160, 224, "avg", 128, '5a')
in5b = InceptionFactoryA(in5a, 352, 192, 320, 192, 224, "max", 128, '5b')
# global avg pooling
pool = mx.symbol.Pooling(data=in5b, kernel=(7, 7), stride=(1, 1), name="global_pool", pool_type='avg')
# linear classifier
flatten = mx.symbol.Flatten(data=pool)
fc1 = mx.symbol.FullyConnected(data=flatten, num_hidden=num_classes)
softmax = mx.symbol.SoftmaxOutput(data=fc1, name='softmax')
return softmax
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/inception-bn.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
'''
Adapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py
Original author Wei Wu
Implemented the following paper:
Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. "Identity Mappings in Deep Residual Networks"
'''
import mxnet as mx
import numpy as np
def residual_unit(data, num_filter, stride, dim_match, name, bottle_neck=True, bn_mom=0.9, workspace=256, memonger=False):
"""Return ResNet Unit symbol for building ResNet
Parameters
----------
data : str
Input data
num_filter : int
Number of output channels
bnf : int
Bottle neck channels factor with regard to num_filter
stride : tuple
Stride used in convolution
dim_match : Boolean
True means channel number between input and output is the same, otherwise means differ
name : str
Base name of the operators
workspace : int
Workspace used in convolution operator
"""
if bottle_neck:
# the same as https://github.com/facebook/fb.resnet.torch#notes, a bit difference with origin paper
bn1 = mx.sym.BatchNorm(data=data, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn1')
act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1')
conv1 = mx.sym.Convolution(data=act1, num_filter=int(num_filter*0.25), kernel=(1,1), stride=(1,1), pad=(0,0),
no_bias=True, workspace=workspace, name=name + '_conv1')
bn2 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn2')
act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2')
conv2 = mx.sym.Convolution(data=act2, num_filter=int(num_filter*0.25), kernel=(3,3), stride=stride, pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2')
bn3 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn3')
act3 = mx.sym.Activation(data=bn3, act_type='relu', name=name + '_relu3')
conv3 = mx.sym.Convolution(data=act3, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True,
workspace=workspace, name=name + '_conv3')
if dim_match:
shortcut = data
else:
shortcut = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_sc')
if memonger:
shortcut._set_attr(mirror_stage='True')
return conv3 + shortcut
else:
bn1 = mx.sym.BatchNorm(data=data, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn1')
act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1')
conv1 = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(3,3), stride=stride, pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv1')
bn2 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn2')
act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2')
conv2 = mx.sym.Convolution(data=act2, num_filter=num_filter, kernel=(3,3), stride=(1,1), pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2')
if dim_match:
shortcut = data
else:
shortcut = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_sc')
if memonger:
shortcut._set_attr(mirror_stage='True')
return conv2 + shortcut
def resnet(units, num_stages, filter_list, num_classes, image_shape, bottle_neck=True, bn_mom=0.9, workspace=256, dtype='float32', memonger=False):
"""Return ResNet symbol of
Parameters
----------
units : list
Number of units in each stage
num_stages : int
Number of stage
filter_list : list
Channel size of each stage
num_classes : int
Ouput size of symbol
dataset : str
Dataset type, only cifar10 and imagenet supports
workspace : int
Workspace used in convolution operator
dtype : str
Precision (float32 or float16)
"""
num_unit = len(units)
assert(num_unit == num_stages)
data = mx.sym.Variable(name='data')
if dtype == 'float32':
data = mx.sym.identity(data=data, name='id')
else:
if dtype == 'float16':
data = mx.sym.Cast(data=data, dtype=np.float16)
data = mx.sym.BatchNorm(data=data, fix_gamma=True, eps=2e-5, momentum=bn_mom, name='bn_data')
(nchannel, height, width) = image_shape
if height <= 32: # such as cifar10
body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(3, 3), stride=(1,1), pad=(1, 1),
no_bias=True, name="conv0", workspace=workspace)
else: # often expected to be 224 such as imagenet
body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(7, 7), stride=(2,2), pad=(3, 3),
no_bias=True, name="conv0", workspace=workspace)
body = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name='bn0')
body = mx.sym.Activation(data=body, act_type='relu', name='relu0')
body = mx.sym.Pooling(data=body, kernel=(3, 3), stride=(2,2), pad=(1,1), pool_type='max')
for i in range(num_stages):
body = residual_unit(body, filter_list[i+1], (1 if i==0 else 2, 1 if i==0 else 2), False,
name='stage%d_unit%d' % (i + 1, 1), bottle_neck=bottle_neck, workspace=workspace,
memonger=memonger)
for j in range(units[i]-1):
body = residual_unit(body, filter_list[i+1], (1,1), True, name='stage%d_unit%d' % (i + 1, j + 2),
bottle_neck=bottle_neck, workspace=workspace, memonger=memonger)
bn1 = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name='bn1')
relu1 = mx.sym.Activation(data=bn1, act_type='relu', name='relu1')
# Although kernel is not used here when global_pool=True, we should put one
pool1 = mx.sym.Pooling(data=relu1, global_pool=True, kernel=(7, 7), pool_type='avg', name='pool1')
flat = mx.sym.Flatten(data=pool1)
fc1 = mx.sym.FullyConnected(data=flat, num_hidden=num_classes, name='fc1')
if dtype == 'float16':
fc1 = mx.sym.Cast(data=fc1, dtype=np.float32)
return mx.sym.SoftmaxOutput(data=fc1, name='softmax')
def get_symbol(num_classes, num_layers, image_shape, conv_workspace=256, dtype='float32', **kwargs):
"""
Adapted from https://github.com/tornadomeet/ResNet/blob/master/train_resnet.py
Original author Wei Wu
"""
image_shape = [int(l) for l in image_shape.split(',')]
(nchannel, height, width) = image_shape
if height <= 28:
num_stages = 3
if (num_layers-2) % 9 == 0 and num_layers >= 164:
per_unit = [(num_layers-2)//9]
filter_list = [16, 64, 128, 256]
bottle_neck = True
elif (num_layers-2) % 6 == 0 and num_layers < 164:
per_unit = [(num_layers-2)//6]
filter_list = [16, 16, 32, 64]
bottle_neck = False
else:
raise ValueError("no experiments done on num_layers {}, you can do it yourself".format(num_layers))
units = per_unit * num_stages
else:
if num_layers >= 50:
filter_list = [64, 256, 512, 1024, 2048]
bottle_neck = True
else:
filter_list = [64, 64, 128, 256, 512]
bottle_neck = False
num_stages = 4
if num_layers == 18:
units = [2, 2, 2, 2]
elif num_layers == 34:
units = [3, 4, 6, 3]
elif num_layers == 50:
units = [3, 4, 6, 3]
elif num_layers == 101:
units = [3, 4, 23, 3]
elif num_layers == 152:
units = [3, 8, 36, 3]
elif num_layers == 200:
units = [3, 24, 36, 3]
elif num_layers == 269:
units = [3, 30, 48, 8]
else:
raise ValueError("no experiments done on num_layers {}, you can do it yourself".format(num_layers))
return resnet(units = units,
num_stages = num_stages,
filter_list = filter_list,
num_classes = num_classes,
image_shape = image_shape,
bottle_neck = bottle_neck,
workspace = conv_workspace,
dtype = dtype)
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/resnet.py
|
"""References:
Simonyan, Karen, and Andrew Zisserman. "Very deep convolutional networks for
large-scale image recognition." arXiv preprint arXiv:1409.1556 (2014).
This implements Variant D from the paper.
"""
import mxnet as mx
def get_symbol(num_classes, **kwargs):
## define alexnet
data = mx.symbol.Variable(name="data")
# group 1
conv1_1 = mx.symbol.Convolution(data=data, kernel=(3, 3), pad=(1, 1), num_filter=64, name="conv1_1")
relu1_1 = mx.symbol.Activation(data=conv1_1, act_type="relu", name="relu1_1")
conv1_2 = mx.symbol.Convolution(data=relu1_1, kernel=(3, 3), pad=(1, 1), num_filter=64, name="conv1_2")
relu1_2 = mx.symbol.Activation(data=conv1_2, act_type="relu", name="relu1_2")
pool1 = mx.symbol.Pooling(
data=relu1_2, pool_type="max", kernel=(2, 2), stride=(2,2), name="pool1")
# group 2
conv2_1 = mx.symbol.Convolution(
data=pool1, kernel=(3, 3), pad=(1, 1), num_filter=128, name="conv2_1")
relu2_1 = mx.symbol.Activation(data=conv2_1, act_type="relu", name="relu2_1")
conv2_2 = mx.symbol.Convolution(
data=relu2_1, kernel=(3, 3), pad=(1, 1), num_filter=128, name="conv2_2")
relu2_2 = mx.symbol.Activation(data=conv2_2, act_type="relu", name="relu2_2")
pool2 = mx.symbol.Pooling(
data=relu2_2, pool_type="max", kernel=(2, 2), stride=(2,2), name="pool2")
# group 3
conv3_1 = mx.symbol.Convolution(
data=pool2, kernel=(3, 3), pad=(1, 1), num_filter=256, name="conv3_1")
relu3_1 = mx.symbol.Activation(data=conv3_1, act_type="relu", name="relu3_1")
conv3_2 = mx.symbol.Convolution(
data=relu3_1, kernel=(3, 3), pad=(1, 1), num_filter=256, name="conv3_2")
relu3_2 = mx.symbol.Activation(data=conv3_2, act_type="relu", name="relu3_2")
conv3_3 = mx.symbol.Convolution(
data=relu3_2, kernel=(3, 3), pad=(1, 1), num_filter=256, name="conv3_3")
relu3_3 = mx.symbol.Activation(data=conv3_3, act_type="relu", name="relu3_3")
pool3 = mx.symbol.Pooling(
data=relu3_3, pool_type="max", kernel=(2, 2), stride=(2,2), name="pool3")
# group 4
conv4_1 = mx.symbol.Convolution(
data=pool3, kernel=(3, 3), pad=(1, 1), num_filter=512, name="conv4_1")
relu4_1 = mx.symbol.Activation(data=conv4_1, act_type="relu", name="relu4_1")
conv4_2 = mx.symbol.Convolution(
data=relu4_1, kernel=(3, 3), pad=(1, 1), num_filter=512, name="conv4_2")
relu4_2 = mx.symbol.Activation(data=conv4_2, act_type="relu", name="relu4_2")
conv4_3 = mx.symbol.Convolution(
data=relu4_2, kernel=(3, 3), pad=(1, 1), num_filter=512, name="conv4_3")
relu4_3 = mx.symbol.Activation(data=conv4_3, act_type="relu", name="relu4_3")
pool4 = mx.symbol.Pooling(
data=relu4_3, pool_type="max", kernel=(2, 2), stride=(2,2), name="pool4")
# group 5
conv5_1 = mx.symbol.Convolution(
data=pool4, kernel=(3, 3), pad=(1, 1), num_filter=512, name="conv5_1")
relu5_1 = mx.symbol.Activation(data=conv5_1, act_type="relu", name="relu5_1")
conv5_2 = mx.symbol.Convolution(
data=relu5_1, kernel=(3, 3), pad=(1, 1), num_filter=512, name="conv5_2")
relu5_2 = mx.symbol.Activation(data=conv5_2, act_type="relu", name="relu5_2")
conv5_3 = mx.symbol.Convolution(
data=relu5_2, kernel=(3, 3), pad=(1, 1), num_filter=512, name="conv5_3")
relu5_3 = mx.symbol.Activation(data=conv5_3, act_type="relu", name="relu5_3")
pool5 = mx.symbol.Pooling(
data=relu5_3, pool_type="max", kernel=(2, 2), stride=(2,2), name="pool5")
# group 6
flatten = mx.symbol.Flatten(data=pool5, name="flatten")
fc6 = mx.symbol.FullyConnected(data=flatten, num_hidden=4096, name="fc6")
relu6 = mx.symbol.Activation(data=fc6, act_type="relu", name="relu6")
drop6 = mx.symbol.Dropout(data=relu6, p=0.5, name="drop6")
# group 7
fc7 = mx.symbol.FullyConnected(data=drop6, num_hidden=4096, name="fc7")
relu7 = mx.symbol.Activation(data=fc7, act_type="relu", name="relu7")
drop7 = mx.symbol.Dropout(data=relu7, p=0.5, name="drop7")
# output
fc8 = mx.symbol.FullyConnected(data=drop7, num_hidden=num_classes, name="fc8")
softmax = mx.symbol.SoftmaxOutput(data=fc8, name='softmax')
return softmax
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/vgg16.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""
Inception V3, suitable for images with around 299 x 299
Reference:
Szegedy, Christian, et al. "Rethinking the Inception Architecture for Computer Vision." arXiv preprint arXiv:1512.00567 (2015).
"""
import mxnet as mx
import numpy as np
def Conv(data, num_filter, kernel=(1, 1), stride=(1, 1), pad=(0, 0), name=None, suffix=''):
conv = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, no_bias=True, name='%s%s_conv2d' %(name, suffix))
bn = mx.sym.BatchNorm(data=conv, name='%s%s_batchnorm' %(name, suffix), fix_gamma=True)
act = mx.sym.Activation(data=bn, act_type='relu', name='%s%s_relu' %(name, suffix))
return act
def Inception7A(data,
num_1x1,
num_3x3_red, num_3x3_1, num_3x3_2,
num_5x5_red, num_5x5,
pool, proj,
name):
tower_1x1 = Conv(data, num_1x1, name=('%s_conv' % name))
tower_5x5 = Conv(data, num_5x5_red, name=('%s_tower' % name), suffix='_conv')
tower_5x5 = Conv(tower_5x5, num_5x5, kernel=(5, 5), pad=(2, 2), name=('%s_tower' % name), suffix='_conv_1')
tower_3x3 = Conv(data, num_3x3_red, name=('%s_tower_1' % name), suffix='_conv')
tower_3x3 = Conv(tower_3x3, num_3x3_1, kernel=(3, 3), pad=(1, 1), name=('%s_tower_1' % name), suffix='_conv_1')
tower_3x3 = Conv(tower_3x3, num_3x3_2, kernel=(3, 3), pad=(1, 1), name=('%s_tower_1' % name), suffix='_conv_2')
pooling = mx.sym.Pooling(data=data, kernel=(3, 3), stride=(1, 1), pad=(1, 1), pool_type=pool, name=('%s_pool_%s_pool' % (pool, name)))
cproj = Conv(pooling, proj, name=('%s_tower_2' % name), suffix='_conv')
concat = mx.sym.Concat(*[tower_1x1, tower_5x5, tower_3x3, cproj], name='ch_concat_%s_chconcat' % name)
return concat
# First Downsample
def Inception7B(data,
num_3x3,
num_d3x3_red, num_d3x3_1, num_d3x3_2,
pool,
name):
tower_3x3 = Conv(data, num_3x3, kernel=(3, 3), pad=(0, 0), stride=(2, 2), name=('%s_conv' % name))
tower_d3x3 = Conv(data, num_d3x3_red, name=('%s_tower' % name), suffix='_conv')
tower_d3x3 = Conv(tower_d3x3, num_d3x3_1, kernel=(3, 3), pad=(1, 1), stride=(1, 1), name=('%s_tower' % name), suffix='_conv_1')
tower_d3x3 = Conv(tower_d3x3, num_d3x3_2, kernel=(3, 3), pad=(0, 0), stride=(2, 2), name=('%s_tower' % name), suffix='_conv_2')
pooling = mx.sym.Pooling(data=data, kernel=(3, 3), stride=(2, 2), pad=(0,0), pool_type="max", name=('max_pool_%s_pool' % name))
concat = mx.sym.Concat(*[tower_3x3, tower_d3x3, pooling], name='ch_concat_%s_chconcat' % name)
return concat
def Inception7C(data,
num_1x1,
num_d7_red, num_d7_1, num_d7_2,
num_q7_red, num_q7_1, num_q7_2, num_q7_3, num_q7_4,
pool, proj,
name):
tower_1x1 = Conv(data=data, num_filter=num_1x1, kernel=(1, 1), name=('%s_conv' % name))
tower_d7 = Conv(data=data, num_filter=num_d7_red, name=('%s_tower' % name), suffix='_conv')
tower_d7 = Conv(data=tower_d7, num_filter=num_d7_1, kernel=(1, 7), pad=(0, 3), name=('%s_tower' % name), suffix='_conv_1')
tower_d7 = Conv(data=tower_d7, num_filter=num_d7_2, kernel=(7, 1), pad=(3, 0), name=('%s_tower' % name), suffix='_conv_2')
tower_q7 = Conv(data=data, num_filter=num_q7_red, name=('%s_tower_1' % name), suffix='_conv')
tower_q7 = Conv(data=tower_q7, num_filter=num_q7_1, kernel=(7, 1), pad=(3, 0), name=('%s_tower_1' % name), suffix='_conv_1')
tower_q7 = Conv(data=tower_q7, num_filter=num_q7_2, kernel=(1, 7), pad=(0, 3), name=('%s_tower_1' % name), suffix='_conv_2')
tower_q7 = Conv(data=tower_q7, num_filter=num_q7_3, kernel=(7, 1), pad=(3, 0), name=('%s_tower_1' % name), suffix='_conv_3')
tower_q7 = Conv(data=tower_q7, num_filter=num_q7_4, kernel=(1, 7), pad=(0, 3), name=('%s_tower_1' % name), suffix='_conv_4')
pooling = mx.sym.Pooling(data=data, kernel=(3, 3), stride=(1, 1), pad=(1, 1), pool_type=pool, name=('%s_pool_%s_pool' % (pool, name)))
cproj = Conv(data=pooling, num_filter=proj, kernel=(1, 1), name=('%s_tower_2' % name), suffix='_conv')
# concat
concat = mx.sym.Concat(*[tower_1x1, tower_d7, tower_q7, cproj], name='ch_concat_%s_chconcat' % name)
return concat
def Inception7D(data,
num_3x3_red, num_3x3,
num_d7_3x3_red, num_d7_1, num_d7_2, num_d7_3x3,
pool,
name):
tower_3x3 = Conv(data=data, num_filter=num_3x3_red, name=('%s_tower' % name), suffix='_conv')
tower_3x3 = Conv(data=tower_3x3, num_filter=num_3x3, kernel=(3, 3), pad=(0,0), stride=(2, 2), name=('%s_tower' % name), suffix='_conv_1')
tower_d7_3x3 = Conv(data=data, num_filter=num_d7_3x3_red, name=('%s_tower_1' % name), suffix='_conv')
tower_d7_3x3 = Conv(data=tower_d7_3x3, num_filter=num_d7_1, kernel=(1, 7), pad=(0, 3), name=('%s_tower_1' % name), suffix='_conv_1')
tower_d7_3x3 = Conv(data=tower_d7_3x3, num_filter=num_d7_2, kernel=(7, 1), pad=(3, 0), name=('%s_tower_1' % name), suffix='_conv_2')
tower_d7_3x3 = Conv(data=tower_d7_3x3, num_filter=num_d7_3x3, kernel=(3, 3), stride=(2, 2), name=('%s_tower_1' % name), suffix='_conv_3')
pooling = mx.sym.Pooling(data=data, kernel=(3, 3), stride=(2, 2), pool_type=pool, name=('%s_pool_%s_pool' % (pool, name)))
# concat
concat = mx.sym.Concat(*[tower_3x3, tower_d7_3x3, pooling], name='ch_concat_%s_chconcat' % name)
return concat
def Inception7E(data,
num_1x1,
num_d3_red, num_d3_1, num_d3_2,
num_3x3_d3_red, num_3x3, num_3x3_d3_1, num_3x3_d3_2,
pool, proj,
name):
tower_1x1 = Conv(data=data, num_filter=num_1x1, kernel=(1, 1), name=('%s_conv' % name))
tower_d3 = Conv(data=data, num_filter=num_d3_red, name=('%s_tower' % name), suffix='_conv')
tower_d3_a = Conv(data=tower_d3, num_filter=num_d3_1, kernel=(1, 3), pad=(0, 1), name=('%s_tower' % name), suffix='_mixed_conv')
tower_d3_b = Conv(data=tower_d3, num_filter=num_d3_2, kernel=(3, 1), pad=(1, 0), name=('%s_tower' % name), suffix='_mixed_conv_1')
tower_3x3_d3 = Conv(data=data, num_filter=num_3x3_d3_red, name=('%s_tower_1' % name), suffix='_conv')
tower_3x3_d3 = Conv(data=tower_3x3_d3, num_filter=num_3x3, kernel=(3, 3), pad=(1, 1), name=('%s_tower_1' % name), suffix='_conv_1')
tower_3x3_d3_a = Conv(data=tower_3x3_d3, num_filter=num_3x3_d3_1, kernel=(1, 3), pad=(0, 1), name=('%s_tower_1' % name), suffix='_mixed_conv')
tower_3x3_d3_b = Conv(data=tower_3x3_d3, num_filter=num_3x3_d3_2, kernel=(3, 1), pad=(1, 0), name=('%s_tower_1' % name), suffix='_mixed_conv_1')
pooling = mx.sym.Pooling(data=data, kernel=(3, 3), stride=(1, 1), pad=(1, 1), pool_type=pool, name=('%s_pool_%s_pool' % (pool, name)))
cproj = Conv(data=pooling, num_filter=proj, kernel=(1, 1), name=('%s_tower_2' % name), suffix='_conv')
# concat
concat = mx.sym.Concat(*[tower_1x1, tower_d3_a, tower_d3_b, tower_3x3_d3_a, tower_3x3_d3_b, cproj], name='ch_concat_%s_chconcat' % name)
return concat
# In[49]:
def get_symbol(num_classes=1000, dtype='float32', **kwargs):
data = mx.sym.Variable(name="data")
if dtype == 'float32':
data = mx.sym.identity(data=data, name='id')
else:
if dtype == 'float16':
data = mx.sym.Cast(data=data, dtype=np.float16)
# stage 1
conv = Conv(data, 32, kernel=(3, 3), stride=(2, 2), name="conv")
conv_1 = Conv(conv, 32, kernel=(3, 3), name="conv_1")
conv_2 = Conv(conv_1, 64, kernel=(3, 3), pad=(1, 1), name="conv_2")
pool = mx.sym.Pooling(data=conv_2, kernel=(3, 3), stride=(2, 2), pool_type="max", name="pool")
# stage 2
conv_3 = Conv(pool, 80, kernel=(1, 1), name="conv_3")
conv_4 = Conv(conv_3, 192, kernel=(3, 3), name="conv_4")
pool1 = mx.sym.Pooling(data=conv_4, kernel=(3, 3), stride=(2, 2), pool_type="max", name="pool1")
# stage 3
in3a = Inception7A(pool1, 64,
64, 96, 96,
48, 64,
"avg", 32, "mixed")
in3b = Inception7A(in3a, 64,
64, 96, 96,
48, 64,
"avg", 64, "mixed_1")
in3c = Inception7A(in3b, 64,
64, 96, 96,
48, 64,
"avg", 64, "mixed_2")
in3d = Inception7B(in3c, 384,
64, 96, 96,
"max", "mixed_3")
# stage 4
in4a = Inception7C(in3d, 192,
128, 128, 192,
128, 128, 128, 128, 192,
"avg", 192, "mixed_4")
in4b = Inception7C(in4a, 192,
160, 160, 192,
160, 160, 160, 160, 192,
"avg", 192, "mixed_5")
in4c = Inception7C(in4b, 192,
160, 160, 192,
160, 160, 160, 160, 192,
"avg", 192, "mixed_6")
in4d = Inception7C(in4c, 192,
192, 192, 192,
192, 192, 192, 192, 192,
"avg", 192, "mixed_7")
in4e = Inception7D(in4d, 192, 320,
192, 192, 192, 192,
"max", "mixed_8")
# stage 5
in5a = Inception7E(in4e, 320,
384, 384, 384,
448, 384, 384, 384,
"avg", 192, "mixed_9")
in5b = Inception7E(in5a, 320,
384, 384, 384,
448, 384, 384, 384,
"max", 192, "mixed_10")
# pool
pool = mx.sym.Pooling(data=in5b, kernel=(8, 8), stride=(1, 1), pool_type="avg", name="global_pool")
flatten = mx.sym.Flatten(data=pool, name="flatten")
fc1 = mx.sym.FullyConnected(data=flatten, num_hidden=num_classes, name='fc1')
if dtype == 'float16':
fc1 = mx.sym.Cast(data=fc1, dtype=np.float32)
softmax = mx.sym.SoftmaxOutput(data=fc1, name='softmax')
return softmax
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/inception-v3.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""
Reference:
Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. "Imagenet classification with deep convolutional neural networks." Advances in neural information processing systems. 2012.
"""
import mxnet as mx
import numpy as np
def get_symbol(num_classes, dtype='float32', **kwargs):
input_data = mx.sym.Variable(name="data")
if dtype == 'float16':
input_data = mx.sym.Cast(data=input_data, dtype=np.float16)
# stage 1
conv1 = mx.sym.Convolution(name='conv1',
data=input_data, kernel=(11, 11), stride=(4, 4), num_filter=96)
relu1 = mx.sym.Activation(data=conv1, act_type="relu")
lrn1 = mx.sym.LRN(data=relu1, alpha=0.0001, beta=0.75, knorm=2, nsize=5)
pool1 = mx.sym.Pooling(
data=lrn1, pool_type="max", kernel=(3, 3), stride=(2,2))
# stage 2
conv2 = mx.sym.Convolution(name='conv2',
data=pool1, kernel=(5, 5), pad=(2, 2), num_filter=256)
relu2 = mx.sym.Activation(data=conv2, act_type="relu")
lrn2 = mx.sym.LRN(data=relu2, alpha=0.0001, beta=0.75, knorm=2, nsize=5)
pool2 = mx.sym.Pooling(data=lrn2, kernel=(3, 3), stride=(2, 2), pool_type="max")
# stage 3
conv3 = mx.sym.Convolution(name='conv3',
data=pool2, kernel=(3, 3), pad=(1, 1), num_filter=384)
relu3 = mx.sym.Activation(data=conv3, act_type="relu")
conv4 = mx.sym.Convolution(name='conv4',
data=relu3, kernel=(3, 3), pad=(1, 1), num_filter=384)
relu4 = mx.sym.Activation(data=conv4, act_type="relu")
conv5 = mx.sym.Convolution(name='conv5',
data=relu4, kernel=(3, 3), pad=(1, 1), num_filter=256)
relu5 = mx.sym.Activation(data=conv5, act_type="relu")
pool3 = mx.sym.Pooling(data=relu5, kernel=(3, 3), stride=(2, 2), pool_type="max")
# stage 4
flatten = mx.sym.Flatten(data=pool3)
fc1 = mx.sym.FullyConnected(name='fc1', data=flatten, num_hidden=4096)
relu6 = mx.sym.Activation(data=fc1, act_type="relu")
dropout1 = mx.sym.Dropout(data=relu6, p=0.5)
# stage 5
fc2 = mx.sym.FullyConnected(name='fc2', data=dropout1, num_hidden=4096)
relu7 = mx.sym.Activation(data=fc2, act_type="relu")
dropout2 = mx.sym.Dropout(data=relu7, p=0.5)
# stage 6
fc3 = mx.sym.FullyConnected(name='fc3', data=dropout2, num_hidden=num_classes)
if dtype == 'float16':
fc3 = mx.sym.Cast(data=fc3, dtype=np.float32)
softmax = mx.sym.SoftmaxOutput(data=fc3, name='softmax')
return softmax
|
DALI-main
|
docs/examples/frameworks/mxnet/demo/symbols/alexnet.py
|
# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. 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
from jax import jit, grad, lax, pmap
from functools import partial
import jax.numpy as jnp
from jax.scipy.special import logsumexp
import numpy.random as npr
layers = [784, 1024, 1024, 10]
def init_model(layers=layers, rng=npr.RandomState(0)):
model = []
for in_size, out_size, in zip(layers[:-1], layers[1:]):
new_w = 0.1 * rng.randn(in_size, out_size)
new_b = 0.1 * rng.randn(out_size)
new_layer = (new_w, new_b)
model.append(new_layer)
return model
def predict(model, images):
input = images
for w, b in model[:-1]:
output = jnp.dot(input, w) + b
input = jnp.tanh(output)
last_w, last_b = model[-1]
last_output = jnp.dot(input, last_w) + last_b
return last_output - logsumexp(last_output, axis=1, keepdims=True)
def loss(model, batch):
predicted_labels = predict(model, batch['images'])
return -jnp.mean(jnp.sum(predicted_labels * batch['labels'], axis=1))
def accuracy(model, iterator):
correct_predictions_num = 0
for batch in iterator:
images = batch['images']
labels = batch['labels']
predicted_class = jnp.argmax(predict(model, images), axis=1)
correct_predictions_num = correct_predictions_num + \
jnp.sum(predicted_class == labels.ravel())
return correct_predictions_num / iterator.size
@jit
def update(model, batch, learning_rate=0.001):
grads = grad(loss)(model, batch)
updated_model = []
for model, updates in zip(model, grads):
w, b = model
dw, db = updates
new_w = w - learning_rate * dw
new_b = b - learning_rate * db
updated_model.append((new_w, new_b))
return updated_model
@partial(pmap, axis_name='data')
def update_parallel(model, batch, learning_rate=0.001):
grads = grad(loss)(model, batch)
grads = lax.pmean(grads, axis_name='data')
updated_model = []
for model, updates in zip(model, grads):
w, b = model
dw, db = updates
new_w = w - learning_rate * dw
new_b = b - learning_rate * db
updated_model.append((new_w, new_b))
return updated_model
|
DALI-main
|
docs/examples/frameworks/jax/model.py
|
doc(title="Image Processing",
underline_char="=",
entries=[
doc_entry(
"augmentation_gallery.ipynb",
[
op_reference("fn.erase", "Augmentation gallery"),
op_reference("fn.water", "Augmentation gallery"),
op_reference("fn.sphere", "Augmentation gallery"),
op_reference("fn.warp_affine", "Augmentation gallery"),
op_reference("fn.jpeg_compression_distortion", "Augmentation gallery"),
op_reference("fn.paste", "Augmentation gallery"),
op_reference("fn.flip", "Augmentation gallery"),
op_reference("fn.rotate", "Augmentation gallery"),
op_reference("fn.hsv", "Augmentation gallery"),
op_reference("fn.brightness_contrast", "Augmentation gallery")
]
),
doc_entry(
"brightness_contrast_example.ipynb",
op_reference("fn.brightness_contrast", "BrightnessContrast example", 0),
),
doc_entry(
"color_space_conversion.ipynb",
op_reference("fn.color_space_conversion", "Color space conversion tutorial", 0),
),
doc_entry(
"decoder_examples.ipynb",
[
op_reference("fn.decoders.image", "Image decoder examples", 0),
op_reference("fn.decoders.image_random_crop", "Image decoder examples", 0),
op_reference("fn.decoders.image_crop", "Image decoder examples", 0),
op_reference("fn.decoders.image_slice", "Image decoder examples", 0)
]
),
doc_entry(
"hsv_example.ipynb",
op_reference("fn.hsv", "HSV example", 0),
),
doc_entry(
"interp_types.ipynb",
op_reference("fn.resize", "Interpolation methods", 1)
),
doc_entry(
"resize.ipynb",
op_reference("fn.resize", "Resize operator tutorial", 0)
),
doc_entry(
"warp.ipynb",
op_reference("fn.warp_affine", "WarpAffine example", 0)
),
doc_entry(
"3d_transforms.ipynb",
[
op_reference("fn.resize", "3D transforms", 3),
op_reference("fn.warp_affine", "3D transforms"),
op_reference("fn.rotate", "3D transforms")
]
)
])
|
DALI-main
|
docs/examples/image_processing/index.py
|
imagenet_synsets = {0: 'tench, Tinca tinca',
1: 'goldfish, Carassius auratus',
2: 'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias',
3: 'tiger shark, Galeocerdo cuvieri',
4: 'hammerhead, hammerhead shark',
5: 'electric ray, crampfish, numbfish, torpedo',
6: 'stingray',
7: 'cock',
8: 'hen',
9: 'ostrich, Struthio camelus',
10: 'brambling, Fringilla montifringilla',
11: 'goldfinch, Carduelis carduelis',
12: 'house finch, linnet, Carpodacus mexicanus',
13: 'junco, snowbird',
14: 'indigo bunting, indigo finch, indigo bird, Passerina cyanea',
15: 'robin, American robin, Turdus migratorius',
16: 'bulbul',
17: 'jay',
18: 'magpie',
19: 'chickadee',
20: 'water ouzel, dipper',
21: 'kite',
22: 'bald eagle, American eagle, Haliaeetus leucocephalus',
23: 'vulture',
24: 'great grey owl, great gray owl, Strix nebulosa',
25: 'European fire salamander, Salamandra salamandra',
26: 'common newt, Triturus vulgaris',
27: 'eft',
28: 'spotted salamander, Ambystoma maculatum',
29: 'axolotl, mud puppy, Ambystoma mexicanum',
30: 'bullfrog, Rana catesbeiana',
31: 'tree frog, tree-frog',
32: 'tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui',
33: 'loggerhead, loggerhead turtle, Caretta caretta',
34: 'leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea',
35: 'mud turtle',
36: 'terrapin',
37: 'box turtle, box tortoise',
38: 'banded gecko',
39: 'common iguana, iguana, Iguana iguana',
40: 'American chameleon, anole, Anolis carolinensis',
41: 'whiptail, whiptail lizard',
42: 'agama',
43: 'frilled lizard, Chlamydosaurus kingi',
44: 'alligator lizard',
45: 'Gila monster, Heloderma suspectum',
46: 'green lizard, Lacerta viridis',
47: 'African chameleon, Chamaeleo chamaeleon',
48: 'Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis',
49: 'African crocodile, Nile crocodile, Crocodylus niloticus',
50: 'American alligator, Alligator mississipiensis',
51: 'triceratops',
52: 'thunder snake, worm snake, Carphophis amoenus',
53: 'ringneck snake, ring-necked snake, ring snake',
54: 'hognose snake, puff adder, sand viper',
55: 'green snake, grass snake',
56: 'king snake, kingsnake',
57: 'garter snake, grass snake',
58: 'water snake',
59: 'vine snake',
60: 'night snake, Hypsiglena torquata',
61: 'boa constrictor, Constrictor constrictor',
62: 'rock python, rock snake, Python sebae',
63: 'Indian cobra, Naja naja',
64: 'green mamba',
65: 'sea snake',
66: 'horned viper, cerastes, sand viper, horned asp, Cerastes cornutus',
67: 'diamondback, diamondback rattlesnake, Crotalus adamanteus',
68: 'sidewinder, horned rattlesnake, Crotalus cerastes',
69: 'trilobite',
70: 'harvestman, daddy longlegs, Phalangium opilio',
71: 'scorpion',
72: 'black and gold garden spider, Argiope aurantia',
73: 'barn spider, Araneus cavaticus',
74: 'garden spider, Aranea diademata',
75: 'black widow, Latrodectus mactans',
76: 'tarantula',
77: 'wolf spider, hunting spider',
78: 'tick',
79: 'centipede',
80: 'black grouse',
81: 'ptarmigan',
82: 'ruffed grouse, partridge, Bonasa umbellus',
83: 'prairie chicken, prairie grouse, prairie fowl',
84: 'peacock',
85: 'quail',
86: 'partridge',
87: 'African grey, African gray, Psittacus erithacus',
88: 'macaw',
89: 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',
90: 'lorikeet',
91: 'coucal',
92: 'bee eater',
93: 'hornbill',
94: 'hummingbird',
95: 'jacamar',
96: 'toucan',
97: 'drake',
98: 'red-breasted merganser, Mergus serrator',
99: 'goose',
100: 'black swan, Cygnus atratus',
101: 'tusker',
102: 'echidna, spiny anteater, anteater',
103: 'platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus',
104: 'wallaby, brush kangaroo',
105: 'koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus',
106: 'wombat',
107: 'jellyfish',
108: 'sea anemone, anemone',
109: 'brain coral',
110: 'flatworm, platyhelminth',
111: 'nematode, nematode worm, roundworm',
112: 'conch',
113: 'snail',
114: 'slug',
115: 'sea slug, nudibranch',
116: 'chiton, coat-of-mail shell, sea cradle, polyplacophore',
117: 'chambered nautilus, pearly nautilus, nautilus',
118: 'Dungeness crab, Cancer magister',
119: 'rock crab, Cancer irroratus',
120: 'fiddler crab',
121: 'king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica',
122: 'American lobster, Northern lobster, Maine lobster, Homarus americanus',
123: 'spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish',
124: 'crayfish, crawfish, crawdad, crawdaddy',
125: 'hermit crab',
126: 'isopod',
127: 'white stork, Ciconia ciconia',
128: 'black stork, Ciconia nigra',
129: 'spoonbill',
130: 'flamingo',
131: 'little blue heron, Egretta caerulea',
132: 'American egret, great white heron, Egretta albus',
133: 'bittern',
134: 'crane',
135: 'limpkin, Aramus pictus',
136: 'European gallinule, Porphyrio porphyrio',
137: 'American coot, marsh hen, mud hen, water hen, Fulica americana',
138: 'bustard',
139: 'ruddy turnstone, Arenaria interpres',
140: 'red-backed sandpiper, dunlin, Erolia alpina',
141: 'redshank, Tringa totanus',
142: 'dowitcher',
143: 'oystercatcher, oyster catcher',
144: 'pelican',
145: 'king penguin, Aptenodytes patagonica',
146: 'albatross, mollymawk',
147: 'grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus',
148: 'killer whale, killer, orca, grampus, sea wolf, Orcinus orca',
149: 'dugong, Dugong dugon',
150: 'sea lion',
151: 'Chihuahua',
152: 'Japanese spaniel',
153: 'Maltese dog, Maltese terrier, Maltese',
154: 'Pekinese, Pekingese, Peke',
155: 'Shih-Tzu',
156: 'Blenheim spaniel',
157: 'papillon',
158: 'toy terrier',
159: 'Rhodesian ridgeback',
160: 'Afghan hound, Afghan',
161: 'basset, basset hound',
162: 'beagle',
163: 'bloodhound, sleuthhound',
164: 'bluetick',
165: 'black-and-tan coonhound',
166: 'Walker hound, Walker foxhound',
167: 'English foxhound',
168: 'redbone',
169: 'borzoi, Russian wolfhound',
170: 'Irish wolfhound',
171: 'Italian greyhound',
172: 'whippet',
173: 'Ibizan hound, Ibizan Podenco',
174: 'Norwegian elkhound, elkhound',
175: 'otterhound, otter hound',
176: 'Saluki, gazelle hound',
177: 'Scottish deerhound, deerhound',
178: 'Weimaraner',
179: 'Staffordshire bullterrier, Staffordshire bull terrier',
180: 'American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier',
181: 'Bedlington terrier',
182: 'Border terrier',
183: 'Kerry blue terrier',
184: 'Irish terrier',
185: 'Norfolk terrier',
186: 'Norwich terrier',
187: 'Yorkshire terrier',
188: 'wire-haired fox terrier',
189: 'Lakeland terrier',
190: 'Sealyham terrier, Sealyham',
191: 'Airedale, Airedale terrier',
192: 'cairn, cairn terrier',
193: 'Australian terrier',
194: 'Dandie Dinmont, Dandie Dinmont terrier',
195: 'Boston bull, Boston terrier',
196: 'miniature schnauzer',
197: 'giant schnauzer',
198: 'standard schnauzer',
199: 'Scotch terrier, Scottish terrier, Scottie',
200: 'Tibetan terrier, chrysanthemum dog',
201: 'silky terrier, Sydney silky',
202: 'soft-coated wheaten terrier',
203: 'West Highland white terrier',
204: 'Lhasa, Lhasa apso',
205: 'flat-coated retriever',
206: 'curly-coated retriever',
207: 'golden retriever',
208: 'Labrador retriever',
209: 'Chesapeake Bay retriever',
210: 'German short-haired pointer',
211: 'vizsla, Hungarian pointer',
212: 'English setter',
213: 'Irish setter, red setter',
214: 'Gordon setter',
215: 'Brittany spaniel',
216: 'clumber, clumber spaniel',
217: 'English springer, English springer spaniel',
218: 'Welsh springer spaniel',
219: 'cocker spaniel, English cocker spaniel, cocker',
220: 'Sussex spaniel',
221: 'Irish water spaniel',
222: 'kuvasz',
223: 'schipperke',
224: 'groenendael',
225: 'malinois',
226: 'briard',
227: 'kelpie',
228: 'komondor',
229: 'Old English sheepdog, bobtail',
230: 'Shetland sheepdog, Shetland sheep dog, Shetland',
231: 'collie',
232: 'Border collie',
233: 'Bouvier des Flandres, Bouviers des Flandres',
234: 'Rottweiler',
235: 'German shepherd, German shepherd dog, German police dog, alsatian',
236: 'Doberman, Doberman pinscher',
237: 'miniature pinscher',
238: 'Greater Swiss Mountain dog',
239: 'Bernese mountain dog',
240: 'Appenzeller',
241: 'EntleBucher',
242: 'boxer',
243: 'bull mastiff',
244: 'Tibetan mastiff',
245: 'French bulldog',
246: 'Great Dane',
247: 'Saint Bernard, St Bernard',
248: 'Eskimo dog, husky',
249: 'malamute, malemute, Alaskan malamute',
250: 'Siberian husky',
251: 'dalmatian, coach dog, carriage dog',
252: 'affenpinscher, monkey pinscher, monkey dog',
253: 'basenji',
254: 'pug, pug-dog',
255: 'Leonberg',
256: 'Newfoundland, Newfoundland dog',
257: 'Great Pyrenees',
258: 'Samoyed, Samoyede',
259: 'Pomeranian',
260: 'chow, chow chow',
261: 'keeshond',
262: 'Brabancon griffon',
263: 'Pembroke, Pembroke Welsh corgi',
264: 'Cardigan, Cardigan Welsh corgi',
265: 'toy poodle',
266: 'miniature poodle',
267: 'standard poodle',
268: 'Mexican hairless',
269: 'timber wolf, grey wolf, gray wolf, Canis lupus',
270: 'white wolf, Arctic wolf, Canis lupus tundrarum',
271: 'red wolf, maned wolf, Canis rufus, Canis niger',
272: 'coyote, prairie wolf, brush wolf, Canis latrans',
273: 'dingo, warrigal, warragal, Canis dingo',
274: 'dhole, Cuon alpinus',
275: 'African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus',
276: 'hyena, hyaena',
277: 'red fox, Vulpes vulpes',
278: 'kit fox, Vulpes macrotis',
279: 'Arctic fox, white fox, Alopex lagopus',
280: 'grey fox, gray fox, Urocyon cinereoargenteus',
281: 'tabby, tabby cat',
282: 'tiger cat',
283: 'Persian cat',
284: 'Siamese cat, Siamese',
285: 'Egyptian cat',
286: 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor',
287: 'lynx, catamount',
288: 'leopard, Panthera pardus',
289: 'snow leopard, ounce, Panthera uncia',
290: 'jaguar, panther, Panthera onca, Felis onca',
291: 'lion, king of beasts, Panthera leo',
292: 'tiger, Panthera tigris',
293: 'cheetah, chetah, Acinonyx jubatus',
294: 'brown bear, bruin, Ursus arctos',
295: 'American black bear, black bear, Ursus americanus, Euarctos americanus',
296: 'ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus',
297: 'sloth bear, Melursus ursinus, Ursus ursinus',
298: 'mongoose',
299: 'meerkat, mierkat',
300: 'tiger beetle',
301: 'ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle',
302: 'ground beetle, carabid beetle',
303: 'long-horned beetle, longicorn, longicorn beetle',
304: 'leaf beetle, chrysomelid',
305: 'dung beetle',
306: 'rhinoceros beetle',
307: 'weevil',
308: 'fly',
309: 'bee',
310: 'ant, emmet, pismire',
311: 'grasshopper, hopper',
312: 'cricket',
313: 'walking stick, walkingstick, stick insect',
314: 'cockroach, roach',
315: 'mantis, mantid',
316: 'cicada, cicala',
317: 'leafhopper',
318: 'lacewing, lacewing fly',
319: "dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
320: 'damselfly',
321: 'admiral',
322: 'ringlet, ringlet butterfly',
323: 'monarch, monarch butterfly, milkweed butterfly, Danaus plexippus',
324: 'cabbage butterfly',
325: 'sulphur butterfly, sulfur butterfly',
326: 'lycaenid, lycaenid butterfly',
327: 'starfish, sea star',
328: 'sea urchin',
329: 'sea cucumber, holothurian',
330: 'wood rabbit, cottontail, cottontail rabbit',
331: 'hare',
332: 'Angora, Angora rabbit',
333: 'hamster',
334: 'porcupine, hedgehog',
335: 'fox squirrel, eastern fox squirrel, Sciurus niger',
336: 'marmot',
337: 'beaver',
338: 'guinea pig, Cavia cobaya',
339: 'sorrel',
340: 'zebra',
341: 'hog, pig, grunter, squealer, Sus scrofa',
342: 'wild boar, boar, Sus scrofa',
343: 'warthog',
344: 'hippopotamus, hippo, river horse, Hippopotamus amphibius',
345: 'ox',
346: 'water buffalo, water ox, Asiatic buffalo, Bubalus bubalis',
347: 'bison',
348: 'ram, tup',
349: 'bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis',
350: 'ibex, Capra ibex',
351: 'hartebeest',
352: 'impala, Aepyceros melampus',
353: 'gazelle',
354: 'Arabian camel, dromedary, Camelus dromedarius',
355: 'llama',
356: 'weasel',
357: 'mink',
358: 'polecat, fitch, foulmart, foumart, Mustela putorius',
359: 'black-footed ferret, ferret, Mustela nigripes',
360: 'otter',
361: 'skunk, polecat, wood pussy',
362: 'badger',
363: 'armadillo',
364: 'three-toed sloth, ai, Bradypus tridactylus',
365: 'orangutan, orang, orangutang, Pongo pygmaeus',
366: 'gorilla, Gorilla gorilla',
367: 'chimpanzee, chimp, Pan troglodytes',
368: 'gibbon, Hylobates lar',
369: 'siamang, Hylobates syndactylus, Symphalangus syndactylus',
370: 'guenon, guenon monkey',
371: 'patas, hussar monkey, Erythrocebus patas',
372: 'baboon',
373: 'macaque',
374: 'langur',
375: 'colobus, colobus monkey',
376: 'proboscis monkey, Nasalis larvatus',
377: 'marmoset',
378: 'capuchin, ringtail, Cebus capucinus',
379: 'howler monkey, howler',
380: 'titi, titi monkey',
381: 'spider monkey, Ateles geoffroyi',
382: 'squirrel monkey, Saimiri sciureus',
383: 'Madagascar cat, ring-tailed lemur, Lemur catta',
384: 'indri, indris, Indri indri, Indri brevicaudatus',
385: 'Indian elephant, Elephas maximus',
386: 'African elephant, Loxodonta africana',
387: 'lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens',
388: 'giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca',
389: 'barracouta, snoek',
390: 'eel',
391: 'coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch',
392: 'rock beauty, Holocanthus tricolor',
393: 'anemone fish',
394: 'sturgeon',
395: 'gar, garfish, garpike, billfish, Lepisosteus osseus',
396: 'lionfish',
397: 'puffer, pufferfish, blowfish, globefish',
398: 'abacus',
399: 'abaya',
400: "academic gown, academic robe, judge's robe",
401: 'accordion, piano accordion, squeeze box',
402: 'acoustic guitar',
403: 'aircraft carrier, carrier, flattop, attack aircraft carrier',
404: 'airliner',
405: 'airship, dirigible',
406: 'altar',
407: 'ambulance',
408: 'amphibian, amphibious vehicle',
409: 'analog clock',
410: 'apiary, bee house',
411: 'apron',
412: 'ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin',
413: 'assault rifle, assault gun',
414: 'backpack, back pack, knapsack, packsack, rucksack, haversack',
415: 'bakery, bakeshop, bakehouse',
416: 'balance beam, beam',
417: 'balloon',
418: 'ballpoint, ballpoint pen, ballpen, Biro',
419: 'Band Aid',
420: 'banjo',
421: 'bannister, banister, balustrade, balusters, handrail',
422: 'barbell',
423: 'barber chair',
424: 'barbershop',
425: 'barn',
426: 'barometer',
427: 'barrel, cask',
428: 'barrow, garden cart, lawn cart, wheelbarrow',
429: 'baseball',
430: 'basketball',
431: 'bassinet',
432: 'bassoon',
433: 'bathing cap, swimming cap',
434: 'bath towel',
435: 'bathtub, bathing tub, bath, tub',
436: 'beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon',
437: 'beacon, lighthouse, beacon light, pharos',
438: 'beaker',
439: 'bearskin, busby, shako',
440: 'beer bottle',
441: 'beer glass',
442: 'bell cote, bell cot',
443: 'bib',
444: 'bicycle-built-for-two, tandem bicycle, tandem',
445: 'bikini, two-piece',
446: 'binder, ring-binder',
447: 'binoculars, field glasses, opera glasses',
448: 'birdhouse',
449: 'boathouse',
450: 'bobsled, bobsleigh, bob',
451: 'bolo tie, bolo, bola tie, bola',
452: 'bonnet, poke bonnet',
453: 'bookcase',
454: 'bookshop, bookstore, bookstall',
455: 'bottlecap',
456: 'bow',
457: 'bow tie, bow-tie, bowtie',
458: 'brass, memorial tablet, plaque',
459: 'brassiere, bra, bandeau',
460: 'breakwater, groin, groyne, mole, bulwark, seawall, jetty',
461: 'breastplate, aegis, egis',
462: 'broom',
463: 'bucket, pail',
464: 'buckle',
465: 'bulletproof vest',
466: 'bullet train, bullet',
467: 'butcher shop, meat market',
468: 'cab, hack, taxi, taxicab',
469: 'caldron, cauldron',
470: 'candle, taper, wax light',
471: 'cannon',
472: 'canoe',
473: 'can opener, tin opener',
474: 'cardigan',
475: 'car mirror',
476: 'carousel, carrousel, merry-go-round, roundabout, whirligig',
477: "carpenter's kit, tool kit",
478: 'carton',
479: 'car wheel',
480: 'cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM',
481: 'cassette',
482: 'cassette player',
483: 'castle',
484: 'catamaran',
485: 'CD player',
486: 'cello, violoncello',
487: 'cellular telephone, cellular phone, cellphone, cell, mobile phone',
488: 'chain',
489: 'chainlink fence',
490: 'chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour',
491: 'chain saw, chainsaw',
492: 'chest',
493: 'chiffonier, commode',
494: 'chime, bell, gong',
495: 'china cabinet, china closet',
496: 'Christmas stocking',
497: 'church, church building',
498: 'cinema, movie theater, movie theatre, movie house, picture palace',
499: 'cleaver, meat cleaver, chopper',
500: 'cliff dwelling',
501: 'cloak',
502: 'clog, geta, patten, sabot',
503: 'cocktail shaker',
504: 'coffee mug',
505: 'coffeepot',
506: 'coil, spiral, volute, whorl, helix',
507: 'combination lock',
508: 'computer keyboard, keypad',
509: 'confectionery, confectionary, candy store',
510: 'container ship, containership, container vessel',
511: 'convertible',
512: 'corkscrew, bottle screw',
513: 'cornet, horn, trumpet, trump',
514: 'cowboy boot',
515: 'cowboy hat, ten-gallon hat',
516: 'cradle',
517: 'crane',
518: 'crash helmet',
519: 'crate',
520: 'crib, cot',
521: 'Crock Pot',
522: 'croquet ball',
523: 'crutch',
524: 'cuirass',
525: 'dam, dike, dyke',
526: 'desk',
527: 'desktop computer',
528: 'dial telephone, dial phone',
529: 'diaper, nappy, napkin',
530: 'digital clock',
531: 'digital watch',
532: 'dining table, board',
533: 'dishrag, dishcloth',
534: 'dishwasher, dish washer, dishwashing machine',
535: 'disk brake, disc brake',
536: 'dock, dockage, docking facility',
537: 'dogsled, dog sled, dog sleigh',
538: 'dome',
539: 'doormat, welcome mat',
540: 'drilling platform, offshore rig',
541: 'drum, membranophone, tympan',
542: 'drumstick',
543: 'dumbbell',
544: 'Dutch oven',
545: 'electric fan, blower',
546: 'electric guitar',
547: 'electric locomotive',
548: 'entertainment center',
549: 'envelope',
550: 'espresso maker',
551: 'face powder',
552: 'feather boa, boa',
553: 'file, file cabinet, filing cabinet',
554: 'fireboat',
555: 'fire engine, fire truck',
556: 'fire screen, fireguard',
557: 'flagpole, flagstaff',
558: 'flute, transverse flute',
559: 'folding chair',
560: 'football helmet',
561: 'forklift',
562: 'fountain',
563: 'fountain pen',
564: 'four-poster',
565: 'freight car',
566: 'French horn, horn',
567: 'frying pan, frypan, skillet',
568: 'fur coat',
569: 'garbage truck, dustcart',
570: 'gasmask, respirator, gas helmet',
571: 'gas pump, gasoline pump, petrol pump, island dispenser',
572: 'goblet',
573: 'go-kart',
574: 'golf ball',
575: 'golfcart, golf cart',
576: 'gondola',
577: 'gong, tam-tam',
578: 'gown',
579: 'grand piano, grand',
580: 'greenhouse, nursery, glasshouse',
581: 'grille, radiator grille',
582: 'grocery store, grocery, food market, market',
583: 'guillotine',
584: 'hair slide',
585: 'hair spray',
586: 'half track',
587: 'hammer',
588: 'hamper',
589: 'hand blower, blow dryer, blow drier, hair dryer, hair drier',
590: 'hand-held computer, hand-held microcomputer',
591: 'handkerchief, hankie, hanky, hankey',
592: 'hard disc, hard disk, fixed disk',
593: 'harmonica, mouth organ, harp, mouth harp',
594: 'harp',
595: 'harvester, reaper',
596: 'hatchet',
597: 'holster',
598: 'home theater, home theatre',
599: 'honeycomb',
600: 'hook, claw',
601: 'hoopskirt, crinoline',
602: 'horizontal bar, high bar',
603: 'horse cart, horse-cart',
604: 'hourglass',
605: 'iPod',
606: 'iron, smoothing iron',
607: "jack-o'-lantern",
608: 'jean, blue jean, denim',
609: 'jeep, landrover',
610: 'jersey, T-shirt, tee shirt',
611: 'jigsaw puzzle',
612: 'jinrikisha, ricksha, rickshaw',
613: 'joystick',
614: 'kimono',
615: 'knee pad',
616: 'knot',
617: 'lab coat, laboratory coat',
618: 'ladle',
619: 'lampshade, lamp shade',
620: 'laptop, laptop computer',
621: 'lawn mower, mower',
622: 'lens cap, lens cover',
623: 'letter opener, paper knife, paperknife',
624: 'library',
625: 'lifeboat',
626: 'lighter, light, igniter, ignitor',
627: 'limousine, limo',
628: 'liner, ocean liner',
629: 'lipstick, lip rouge',
630: 'Loafer',
631: 'lotion',
632: 'loudspeaker, speaker, speaker unit, loudspeaker system, speaker system',
633: "loupe, jeweler's loupe",
634: 'lumbermill, sawmill',
635: 'magnetic compass',
636: 'mailbag, postbag',
637: 'mailbox, letter box',
638: 'maillot',
639: 'maillot, tank suit',
640: 'manhole cover',
641: 'maraca',
642: 'marimba, xylophone',
643: 'mask',
644: 'matchstick',
645: 'maypole',
646: 'maze, labyrinth',
647: 'measuring cup',
648: 'medicine chest, medicine cabinet',
649: 'megalith, megalithic structure',
650: 'microphone, mike',
651: 'microwave, microwave oven',
652: 'military uniform',
653: 'milk can',
654: 'minibus',
655: 'miniskirt, mini',
656: 'minivan',
657: 'missile',
658: 'mitten',
659: 'mixing bowl',
660: 'mobile home, manufactured home',
661: 'Model T',
662: 'modem',
663: 'monastery',
664: 'monitor',
665: 'moped',
666: 'mortar',
667: 'mortarboard',
668: 'mosque',
669: 'mosquito net',
670: 'motor scooter, scooter',
671: 'mountain bike, all-terrain bike, off-roader',
672: 'mountain tent',
673: 'mouse, computer mouse',
674: 'mousetrap',
675: 'moving van',
676: 'muzzle',
677: 'nail',
678: 'neck brace',
679: 'necklace',
680: 'nipple',
681: 'notebook, notebook computer',
682: 'obelisk',
683: 'oboe, hautboy, hautbois',
684: 'ocarina, sweet potato',
685: 'odometer, hodometer, mileometer, milometer',
686: 'oil filter',
687: 'organ, pipe organ',
688: 'oscilloscope, scope, cathode-ray oscilloscope, CRO',
689: 'overskirt',
690: 'oxcart',
691: 'oxygen mask',
692: 'packet',
693: 'paddle, boat paddle',
694: 'paddlewheel, paddle wheel',
695: 'padlock',
696: 'paintbrush',
697: "pajama, pyjama, pj's, jammies",
698: 'palace',
699: 'panpipe, pandean pipe, syrinx',
700: 'paper towel',
701: 'parachute, chute',
702: 'parallel bars, bars',
703: 'park bench',
704: 'parking meter',
705: 'passenger car, coach, carriage',
706: 'patio, terrace',
707: 'pay-phone, pay-station',
708: 'pedestal, plinth, footstall',
709: 'pencil box, pencil case',
710: 'pencil sharpener',
711: 'perfume, essence',
712: 'Petri dish',
713: 'photocopier',
714: 'pick, plectrum, plectron',
715: 'pickelhaube',
716: 'picket fence, paling',
717: 'pickup, pickup truck',
718: 'pier',
719: 'piggy bank, penny bank',
720: 'pill bottle',
721: 'pillow',
722: 'ping-pong ball',
723: 'pinwheel',
724: 'pirate, pirate ship',
725: 'pitcher, ewer',
726: "plane, carpenter's plane, woodworking plane",
727: 'planetarium',
728: 'plastic bag',
729: 'plate rack',
730: 'plow, plough',
731: "plunger, plumber's helper",
732: 'Polaroid camera, Polaroid Land camera',
733: 'pole',
734: 'police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria',
735: 'poncho',
736: 'pool table, billiard table, snooker table',
737: 'pop bottle, soda bottle',
738: 'pot, flowerpot',
739: "potter's wheel",
740: 'power drill',
741: 'prayer rug, prayer mat',
742: 'printer',
743: 'prison, prison house',
744: 'projectile, missile',
745: 'projector',
746: 'puck, hockey puck',
747: 'punching bag, punch bag, punching ball, punchball',
748: 'purse',
749: 'quill, quill pen',
750: 'quilt, comforter, comfort, puff',
751: 'racer, race car, racing car',
752: 'racket, racquet',
753: 'radiator',
754: 'radio, wireless',
755: 'radio telescope, radio reflector',
756: 'rain barrel',
757: 'recreational vehicle, RV, R.V.',
758: 'reel',
759: 'reflex camera',
760: 'refrigerator, icebox',
761: 'remote control, remote',
762: 'restaurant, eating house, eating place, eatery',
763: 'revolver, six-gun, six-shooter',
764: 'rifle',
765: 'rocking chair, rocker',
766: 'rotisserie',
767: 'rubber eraser, rubber, pencil eraser',
768: 'rugby ball',
769: 'rule, ruler',
770: 'running shoe',
771: 'safe',
772: 'safety pin',
773: 'saltshaker, salt shaker',
774: 'sandal',
775: 'sarong',
776: 'sax, saxophone',
777: 'scabbard',
778: 'scale, weighing machine',
779: 'school bus',
780: 'schooner',
781: 'scoreboard',
782: 'screen, CRT screen',
783: 'screw',
784: 'screwdriver',
785: 'seat belt, seatbelt',
786: 'sewing machine',
787: 'shield, buckler',
788: 'shoe shop, shoe-shop, shoe store',
789: 'shoji',
790: 'shopping basket',
791: 'shopping cart',
792: 'shovel',
793: 'shower cap',
794: 'shower curtain',
795: 'ski',
796: 'ski mask',
797: 'sleeping bag',
798: 'slide rule, slipstick',
799: 'sliding door',
800: 'slot, one-armed bandit',
801: 'snorkel',
802: 'snowmobile',
803: 'snowplow, snowplough',
804: 'soap dispenser',
805: 'soccer ball',
806: 'sock',
807: 'solar dish, solar collector, solar furnace',
808: 'sombrero',
809: 'soup bowl',
810: 'space bar',
811: 'space heater',
812: 'space shuttle',
813: 'spatula',
814: 'speedboat',
815: "spider web, spider's web",
816: 'spindle',
817: 'sports car, sport car',
818: 'spotlight, spot',
819: 'stage',
820: 'steam locomotive',
821: 'steel arch bridge',
822: 'steel drum',
823: 'stethoscope',
824: 'stole',
825: 'stone wall',
826: 'stopwatch, stop watch',
827: 'stove',
828: 'strainer',
829: 'streetcar, tram, tramcar, trolley, trolley car',
830: 'stretcher',
831: 'studio couch, day bed',
832: 'stupa, tope',
833: 'submarine, pigboat, sub, U-boat',
834: 'suit, suit of clothes',
835: 'sundial',
836: 'sunglass',
837: 'sunglasses, dark glasses, shades',
838: 'sunscreen, sunblock, sun blocker',
839: 'suspension bridge',
840: 'swab, swob, mop',
841: 'sweatshirt',
842: 'swimming trunks, bathing trunks',
843: 'swing',
844: 'switch, electric switch, electrical switch',
845: 'syringe',
846: 'table lamp',
847: 'tank, army tank, armored combat vehicle, armoured combat vehicle',
848: 'tape player',
849: 'teapot',
850: 'teddy, teddy bear',
851: 'television, television system',
852: 'tennis ball',
853: 'thatch, thatched roof',
854: 'theater curtain, theatre curtain',
855: 'thimble',
856: 'thresher, thrasher, threshing machine',
857: 'throne',
858: 'tile roof',
859: 'toaster',
860: 'tobacco shop, tobacconist shop, tobacconist',
861: 'toilet seat',
862: 'torch',
863: 'totem pole',
864: 'tow truck, tow car, wrecker',
865: 'toyshop',
866: 'tractor',
867: 'trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi',
868: 'tray',
869: 'trench coat',
870: 'tricycle, trike, velocipede',
871: 'trimaran',
872: 'tripod',
873: 'triumphal arch',
874: 'trolleybus, trolley coach, trackless trolley',
875: 'trombone',
876: 'tub, vat',
877: 'turnstile',
878: 'typewriter keyboard',
879: 'umbrella',
880: 'unicycle, monocycle',
881: 'upright, upright piano',
882: 'vacuum, vacuum cleaner',
883: 'vase',
884: 'vault',
885: 'velvet',
886: 'vending machine',
887: 'vestment',
888: 'viaduct',
889: 'violin, fiddle',
890: 'volleyball',
891: 'waffle iron',
892: 'wall clock',
893: 'wallet, billfold, notecase, pocketbook',
894: 'wardrobe, closet, press',
895: 'warplane, military plane',
896: 'washbasin, handbasin, washbowl, lavabo, wash-hand basin',
897: 'washer, automatic washer, washing machine',
898: 'water bottle',
899: 'water jug',
900: 'water tower',
901: 'whiskey jug',
902: 'whistle',
903: 'wig',
904: 'window screen',
905: 'window shade',
906: 'Windsor tie',
907: 'wine bottle',
908: 'wing',
909: 'wok',
910: 'wooden spoon',
911: 'wool, woolen, woollen',
912: 'worm fence, snake fence, snake-rail fence, Virginia fence',
913: 'wreck',
914: 'yawl',
915: 'yurt',
916: 'web site, website, internet site, site',
917: 'comic book',
918: 'crossword puzzle, crossword',
919: 'street sign',
920: 'traffic light, traffic signal, stoplight',
921: 'book jacket, dust cover, dust jacket, dust wrapper',
922: 'menu',
923: 'plate',
924: 'guacamole',
925: 'consomme',
926: 'hot pot, hotpot',
927: 'trifle',
928: 'ice cream, icecream',
929: 'ice lolly, lolly, lollipop, popsicle',
930: 'French loaf',
931: 'bagel, beigel',
932: 'pretzel',
933: 'cheeseburger',
934: 'hotdog, hot dog, red hot',
935: 'mashed potato',
936: 'head cabbage',
937: 'broccoli',
938: 'cauliflower',
939: 'zucchini, courgette',
940: 'spaghetti squash',
941: 'acorn squash',
942: 'butternut squash',
943: 'cucumber, cuke',
944: 'artichoke, globe artichoke',
945: 'bell pepper',
946: 'cardoon',
947: 'mushroom',
948: 'Granny Smith',
949: 'strawberry',
950: 'orange',
951: 'lemon',
952: 'fig',
953: 'pineapple, ananas',
954: 'banana',
955: 'jackfruit, jak, jack',
956: 'custard apple',
957: 'pomegranate',
958: 'hay',
959: 'carbonara',
960: 'chocolate sauce, chocolate syrup',
961: 'dough',
962: 'meat loaf, meatloaf',
963: 'pizza, pizza pie',
964: 'potpie',
965: 'burrito',
966: 'red wine',
967: 'espresso',
968: 'cup',
969: 'eggnog',
970: 'alp',
971: 'bubble',
972: 'cliff, drop, drop-off',
973: 'coral reef',
974: 'geyser',
975: 'lakeside, lakeshore',
976: 'promontory, headland, head, foreland',
977: 'sandbar, sand bar',
978: 'seashore, coast, seacoast, sea-coast',
979: 'valley, vale',
980: 'volcano',
981: 'ballplayer, baseball player',
982: 'groom, bridegroom',
983: 'scuba diver',
984: 'rapeseed',
985: 'daisy',
986: "yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
987: 'corn',
988: 'acorn',
989: 'hip, rose hip, rosehip',
990: 'buckeye, horse chestnut, conker',
991: 'coral fungus',
992: 'agaric',
993: 'gyromitra',
994: 'stinkhorn, carrion fungus',
995: 'earthstar',
996: 'hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa',
997: 'bolete',
998: 'ear, spike, capitulum',
999: 'toilet tissue, toilet paper, bathroom tissue'}
|
DALI-main
|
docs/examples/image_processing/synsets.py
|
#!/usr/bin/env python
#
# Copyright (c) 2009 Google Inc. All rights reserved.
# Copyright (c) 2017-2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Does google-lint on c++ files.
The goal of this script is to identify places in the code that *may*
be in non-compliance with google style. It does not attempt to fix
up these problems -- the point is to educate. It does also not
attempt to find all problems, or to ensure that everything it does
find is legitimately a problem.
In particular, we can get very confused by /* and // inside strings!
We do a small hack, which is to ignore //'s with "'s after them on the
same line, but it is far from perfect (in either direction).
"""
import codecs
import copy
import getopt
import math # for log
import os
import re
import sre_compile
import string
import sys
import unicodedata
python2_version = False
if sys.version_info[0] < 3:
python2_version = True
_USAGE = """
Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
[--counting=total|toplevel|detailed] [--root=subdir]
[--linelength=digits] [--headers=x,y,...]
[--quiet]
<file> [file] ...
The style guidelines this tries to follow are those in
https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
Every problem is given a confidence score from 1-5, with 5 meaning we are
certain of the problem, and 1 meaning it could be a legitimate construct.
This will miss some errors, and is not a substitute for a code review.
To suppress false-positive errors of a certain category, add a
'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)
suppresses errors of all categories on that line.
The files passed in will be linted; at least one file must be provided.
Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the
extensions with the --extensions flag.
Flags:
output=vs7
By default, the output is formatted to ease emacs parsing. Visual Studio
compatible output (vs7) may also be used. Other formats are unsupported.
verbose=#
Specify a number 0-5 to restrict errors to certain verbosity levels.
quiet
Don't print anything if no errors are found.
filter=-x,+y,...
Specify a comma-separated list of category-filters to apply: only
error messages whose category names pass the filters will be printed.
(Category names are printed with the message and look like
"[whitespace/indent]".) Filters are evaluated left to right.
"-FOO" and "FOO" means "do not print categories that start with FOO".
"+FOO" means "do print categories that start with FOO".
Examples: --filter=-whitespace,+whitespace/braces
--filter=whitespace,runtime/printf,+runtime/printf_format
--filter=-,+build/include_what_you_use
To see a list of all the categories used in cpplint, pass no arg:
--filter=
counting=total|toplevel|detailed
The total number of errors found is always printed. If
'toplevel' is provided, then the count of errors in each of
the top-level categories like 'build' and 'whitespace' will
also be printed. If 'detailed' is provided, then a count
is provided for each category like 'build/class'.
root=subdir
The root directory used for deriving header guard CPP variable.
By default, the header guard CPP variable is calculated as the relative
path to the directory that contains .git, .hg, or .svn. When this flag
is specified, the relative path is calculated from the specified
directory. If the specified directory does not exist, this flag is
ignored.
Examples:
Assuming that top/src/.git exists (and cwd=top/src), the header guard
CPP variables for top/src/chrome/browser/ui/browser.h are:
No flag => CHROME_BROWSER_UI_BROWSER_H_
--root=chrome => BROWSER_UI_BROWSER_H_
--root=chrome/browser => UI_BROWSER_H_
--root=.. => SRC_CHROME_BROWSER_UI_BROWSER_H_
linelength=digits
This is the allowed line length for the project. The default value is
80 characters.
Examples:
--linelength=120
extensions=extension,extension,...
The allowed file extensions that cpplint will check
Examples:
--extensions=hpp,cpp
headers=x,y,...
The header extensions that cpplint will treat as .h in checks. Values are
automatically added to --extensions list.
Examples:
--headers=hpp,hxx
--headers=hpp
cpplint.py supports per-directory configurations specified in CPPLINT.cfg
files. CPPLINT.cfg file can contain a number of key=value pairs.
Currently the following options are supported:
set noparent
filter=+filter1,-filter2,...
exclude_files=regex
linelength=80
root=subdir
headers=x,y,...
"set noparent" option prevents cpplint from traversing directory tree
upwards looking for more .cfg files in parent directories. This option
is usually placed in the top-level project directory.
The "filter" option is similar in function to --filter flag. It specifies
message filters in addition to the |_DEFAULT_FILTERS| and those specified
through --filter command-line flag.
"exclude_files" allows to specify a regular expression to be matched against
a file name. If the expression matches, the file is skipped and not run
through liner.
"linelength" allows to specify the allowed line length for the project.
The "root" option is similar in function to the --root flag (see example
above). Paths are relative to the directory of the CPPLINT.cfg.
The "headers" option is similar in function to the --headers flag
(see example above).
CPPLINT.cfg has an effect on files in the same directory and all
sub-directories, unless overridden by a nested configuration file.
Example file:
filter=-build/include_order,+build/include_alpha
exclude_files=.*\.cc
The above example disables build/include_order warning and enables
build/include_alpha as well as excludes all .cc from being
processed by linter, in the current directory (where the .cfg
file is located) and all sub-directories.
"""
# We categorize each error message we print. Here are the categories.
# We want an explicit list so we can list them all in cpplint --filter=.
# If you add a new error message with a new category, add it to the list
# here! cpplint_unittest.py should tell you if you forget to do this.
_ERROR_CATEGORIES = [
'build/class',
'build/c++11',
'build/c++14',
'build/c++tr1',
'build/deprecated',
'build/endif_comment',
'build/explicit_make_pair',
'build/forward_decl',
'build/header_guard',
'build/include',
'build/include_alpha',
'build/include_order',
'build/include_what_you_use',
'build/namespaces',
'build/printf_format',
'build/storage_class',
'legal/copyright',
'readability/alt_tokens',
'readability/braces',
'readability/casting',
'readability/check',
'readability/constructors',
'readability/fn_size',
'readability/inheritance',
'readability/multiline_comment',
'readability/multiline_string',
'readability/namespace',
'readability/nolint',
'readability/nul',
'readability/strings',
'readability/todo',
'readability/utf8',
'runtime/arrays',
'runtime/casting',
'runtime/explicit',
'runtime/int',
'runtime/init',
'runtime/invalid_increment',
'runtime/member_string_references',
'runtime/memset',
'runtime/indentation_namespace',
'runtime/operator',
'runtime/printf',
'runtime/printf_format',
'runtime/references',
'runtime/string',
'runtime/threadsafe_fn',
'runtime/vlog',
'whitespace/blank_line',
'whitespace/braces',
'whitespace/comma',
'whitespace/comments',
'whitespace/empty_conditional_body',
'whitespace/empty_if_body',
'whitespace/empty_loop_body',
'whitespace/end_of_line',
'whitespace/ending_newline',
'whitespace/forcolon',
'whitespace/indent',
'whitespace/line_length',
'whitespace/newline',
'whitespace/operators',
'whitespace/parens',
'whitespace/semicolon',
'whitespace/tab',
'whitespace/todo',
]
# These error categories are no longer enforced by cpplint, but for backwards-
# compatibility they may still appear in NOLINT comments.
_LEGACY_ERROR_CATEGORIES = [
'readability/streams',
'readability/function',
]
# The default state of the category filter. This is overridden by the --filter=
# flag. By default all errors are on, so only add here categories that should be
# off by default (i.e., categories that must be enabled by the --filter= flags).
# All entries here should start with a '-' or '+', as in the --filter= flag.
_DEFAULT_FILTERS = ['-build/include_alpha']
# The default list of categories suppressed for C (not C++) files.
_DEFAULT_C_SUPPRESSED_CATEGORIES = [
'readability/casting',
]
# The default list of categories suppressed for Linux Kernel files.
_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [
'whitespace/tab',
]
# We used to check for high-bit characters, but after much discussion we
# decided those were OK, as long as they were in UTF-8 and didn't represent
# hard-coded international strings, which belong in a separate i18n file.
# C++ headers
_CPP_HEADERS = frozenset([
# Legacy
'algobase.h',
'algo.h',
'alloc.h',
'builtinbuf.h',
'bvector.h',
'complex.h',
'defalloc.h',
'deque.h',
'editbuf.h',
'fstream.h',
'function.h',
'hash_map',
'hash_map.h',
'hash_set',
'hash_set.h',
'hashtable.h',
'heap.h',
'indstream.h',
'iomanip.h',
'iostream.h',
'istream.h',
'iterator.h',
'list.h',
'map.h',
'multimap.h',
'multiset.h',
'ostream.h',
'pair.h',
'parsestream.h',
'pfstream.h',
'procbuf.h',
'pthread_alloc',
'pthread_alloc.h',
'rope',
'rope.h',
'ropeimpl.h',
'set.h',
'slist',
'slist.h',
'stack.h',
'stdiostream.h',
'stl_alloc.h',
'stl_relops.h',
'streambuf.h',
'stream.h',
'strfile.h',
'strstream.h',
'tempbuf.h',
'tree.h',
'type_traits.h',
'vector.h',
# 17.6.1.2 C++ library headers
'algorithm',
'array',
'atomic',
'bitset',
'chrono',
'codecvt',
'complex',
'condition_variable',
'deque',
'exception',
'forward_list',
'fstream',
'functional',
'future',
'initializer_list',
'iomanip',
'ios',
'iosfwd',
'iostream',
'istream',
'iterator',
'limits',
'list',
'locale',
'map',
'memory',
'mutex',
'new',
'numeric',
'ostream',
'queue',
'random',
'ratio',
'regex',
'scoped_allocator',
'set',
'sstream',
'stack',
'stdexcept',
'streambuf',
'string',
'strstream',
'system_error',
'thread',
'tuple',
'typeindex',
'typeinfo',
'type_traits',
'unordered_map',
'unordered_set',
'utility',
'valarray',
'vector',
# 17.6.1.2 C++ headers for C library facilities
'cassert',
'ccomplex',
'cctype',
'cerrno',
'cfenv',
'cfloat',
'cinttypes',
'ciso646',
'climits',
'clocale',
'cmath',
'csetjmp',
'csignal',
'cstdalign',
'cstdarg',
'cstdbool',
'cstddef',
'cstdint',
'cstdio',
'cstdlib',
'cstring',
'ctgmath',
'ctime',
'cuchar',
'cwchar',
'cwctype',
])
# Type names
_TYPES = re.compile(
r'^(?:'
# [dcl.type.simple]
r'(char(16_t|32_t)?)|wchar_t|'
r'bool|short|int|long|signed|unsigned|float|double|'
# [support.types]
r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'
# [cstdint.syn]
r'(u?int(_fast|_least)?(8|16|32|64)_t)|'
r'(u?int(max|ptr)_t)|'
r')$')
# These headers are excluded from [build/include] and [build/include_order]
# checks:
# - Anything not following google file name conventions (containing an
# uppercase character, such as Python.h or nsStringAPI.h, for example).
# - Lua headers.
_THIRD_PARTY_HEADERS_PATTERN = re.compile(
r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
# Pattern for matching FileInfo.BaseName() against test file name
_TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'
# Pattern that matches only complete whitespace, possibly across multiple lines.
_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)
# Assertion macros. These are defined in base/logging.h and
# testing/base/public/gunit.h.
_CHECK_MACROS = [
'DCHECK', 'CHECK',
'EXPECT_TRUE', 'ASSERT_TRUE',
'EXPECT_FALSE', 'ASSERT_FALSE',
]
# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
('>=', 'GE'), ('>', 'GT'),
('<=', 'LE'), ('<', 'LT')]:
_CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
_CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
_CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
_CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
('>=', 'LT'), ('>', 'LE'),
('<=', 'GT'), ('<', 'GE')]:
_CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
_CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
# Alternative tokens and their replacements. For full list, see section 2.5
# Alternative tokens [lex.digraph] in the C++ standard.
#
# Digraphs (such as '%:') are not included here since it's a mess to
# match those on a word boundary.
_ALT_TOKEN_REPLACEMENT = {
'and': '&&',
'bitor': '|',
'or': '||',
'xor': '^',
'compl': '~',
'bitand': '&',
'and_eq': '&=',
'or_eq': '|=',
'xor_eq': '^=',
'not': '!',
'not_eq': '!='
}
# Compile regular expression that matches all the above keywords. The "[ =()]"
# bit is meant to avoid matching these keywords outside of boolean expressions.
#
# False positives include C-style multi-line comments and multi-line strings
# but those have always been troublesome for cpplint.
_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
# These constants define types of headers for use with
# _IncludeState.CheckNextIncludeOrder().
_C_SYS_HEADER = 1
_CPP_SYS_HEADER = 2
_LIKELY_MY_HEADER = 3
_POSSIBLE_MY_HEADER = 4
_OTHER_HEADER = 5
# These constants define the current inline assembly state
_NO_ASM = 0 # Outside of inline assembly block
_INSIDE_ASM = 1 # Inside inline assembly block
_END_ASM = 2 # Last line of inline assembly block
_BLOCK_ASM = 3 # The whole block is an inline assembly block
# Match start of assembly blocks
_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
r'(?:\s+(volatile|__volatile__))?'
r'\s*[{(]')
# Match strings that indicate we're working on a C (not C++) file.
_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'
r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')
# Match string that indicates we're working on a Linux Kernel file.
_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')
_regexp_compile_cache = {}
# {str, set(int)}: a map from error categories to sets of linenumbers
# on which those errors are expected and should be suppressed.
_error_suppressions = {}
# The root directory used for deriving header guard CPP variable.
# This is set by --root flag.
_root = None
_root_debug = False
# The allowed line length of files.
# This is set by --linelength flag.
_line_length = 80
# The allowed extensions for file names
# This is set by --extensions flag.
_valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
# Treat all headers starting with 'h' equally: .h, .hpp, .hxx etc.
# This is set by --headers flag.
_hpp_headers = set(['h'])
# {str, bool}: a map from error categories to booleans which indicate if the
# category should be suppressed for every line.
_global_error_suppressions = {}
def ProcessHppHeadersOption(val):
global _hpp_headers
try:
_hpp_headers = set(val.split(','))
# Automatically append to extensions list so it does not have to be set 2 times
_valid_extensions.update(_hpp_headers)
except ValueError:
PrintUsage('Header extensions must be comma seperated list.')
def IsHeaderExtension(file_extension):
return file_extension in _hpp_headers
def ParseNolintSuppressions(filename, raw_line, linenum, error):
"""Updates the global list of line error-suppressions.
Parses any NOLINT comments on the current line, updating the global
error_suppressions store. Reports an error if the NOLINT comment
was malformed.
Args:
filename: str, the name of the input file.
raw_line: str, the line of input text, with comments.
linenum: int, the number of the current line.
error: function, an error handler.
"""
matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
if matched:
if matched.group(1):
suppressed_line = linenum + 1
else:
suppressed_line = linenum
category = matched.group(2)
if category in (None, '(*)'): # => "suppress all"
_error_suppressions.setdefault(None, set()).add(suppressed_line)
else:
if category.startswith('(') and category.endswith(')'):
category = category[1:-1]
if category in _ERROR_CATEGORIES:
_error_suppressions.setdefault(category, set()).add(suppressed_line)
elif category not in _LEGACY_ERROR_CATEGORIES:
error(filename, linenum, 'readability/nolint', 5,
'Unknown NOLINT error category: %s' % category)
def ProcessGlobalSuppresions(lines):
"""Updates the list of global error suppressions.
Parses any lint directives in the file that have global effect.
Args:
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
"""
for line in lines:
if _SEARCH_C_FILE.search(line):
for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
_global_error_suppressions[category] = True
if _SEARCH_KERNEL_FILE.search(line):
for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
_global_error_suppressions[category] = True
def ResetNolintSuppressions():
"""Resets the set of NOLINT suppressions to empty."""
_error_suppressions.clear()
_global_error_suppressions.clear()
def IsErrorSuppressedByNolint(category, linenum):
"""Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment or
global suppression.
"""
return (_global_error_suppressions.get(category, False) or
linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set()))
def Match(pattern, s):
"""Matches the string with the pattern, caching the compiled regexp."""
# The regexp compilation caching is inlined in both Match and Search for
# performance reasons; factoring it out into a separate function turns out
# to be noticeably expensive.
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].match(s)
def ReplaceAll(pattern, rep, s):
"""Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements)
"""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].sub(rep, s)
def Search(pattern, s):
"""Searches the string for the pattern, caching the compiled regexp."""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].search(s)
def _IsSourceExtension(s):
"""File extension (excluding dot) matches a source file extension."""
return s in ('c', 'cc', 'cpp', 'cxx')
class _IncludeState(object):
"""Tracks line numbers for includes, and the order in which includes appear.
include_list contains list of lists of (header, line number) pairs.
It's a lists of lists rather than just one flat list to make it
easier to update across preprocessor boundaries.
Call CheckNextIncludeOrder() once for each header in the file, passing
in the type constants defined above. Calls in an illegal order will
raise an _IncludeError with an appropriate error message.
"""
# self._section will move monotonically through this set. If it ever
# needs to move backwards, CheckNextIncludeOrder will raise an error.
_INITIAL_SECTION = 0
_MY_H_SECTION = 1
_C_SECTION = 2
_CPP_SECTION = 3
_OTHER_H_SECTION = 4
_TYPE_NAMES = {
_C_SYS_HEADER: 'C system header',
_CPP_SYS_HEADER: 'C++ system header',
_LIKELY_MY_HEADER: 'header this file implements',
_POSSIBLE_MY_HEADER: 'header this file may implement',
_OTHER_HEADER: 'other header',
}
_SECTION_NAMES = {
_INITIAL_SECTION: "... nothing. (This can't be an error.)",
_MY_H_SECTION: 'a header this file implements',
_C_SECTION: 'C system header',
_CPP_SECTION: 'C++ system header',
_OTHER_H_SECTION: 'other header',
}
def __init__(self):
self.include_list = [[]]
self.ResetSection('')
def FindHeader(self, header):
"""Check if a header has already been included.
Args:
header: header to check.
Returns:
Line number of previous occurrence, or -1 if the header has not
been seen before.
"""
for section_list in self.include_list:
for f in section_list:
if f[0] == header:
return f[1]
return -1
def ResetSection(self, directive):
"""Reset section checking for preprocessor directive.
Args:
directive: preprocessor directive (e.g. "if", "else").
"""
# The name of the current section.
self._section = self._INITIAL_SECTION
# The path of last found header.
self._last_header = ''
# Update list of includes. Note that we never pop from the
# include list.
if directive in ('if', 'ifdef', 'ifndef'):
self.include_list.append([])
elif directive in ('else', 'elif'):
self.include_list[-1] = []
def SetLastHeader(self, header_path):
self._last_header = header_path
def CanonicalizeAlphabeticalOrder(self, header_path):
"""Returns a path canonicalized for alphabetical comparison.
- replaces "-" with "_" so they both cmp the same.
- removes '-inl' since we don't require them to be after the main header.
- lowercase everything, just in case.
Args:
header_path: Path to be canonicalized.
Returns:
Canonicalized path.
"""
return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
"""Check if a header is in alphabetical order with the previous header.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
header_path: Canonicalized header to be checked.
Returns:
Returns true if the header is in alphabetical order.
"""
# If previous section is different from current section, _last_header will
# be reset to empty string, so it's always less than current header.
#
# If previous line was a blank line, assume that the headers are
# intentionally sorted the way they are.
if (self._last_header > header_path and
Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
return False
return True
def CheckNextIncludeOrder(self, header_type):
"""Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong.
"""
error_message = ('Found %s after %s' %
(self._TYPE_NAMES[header_type],
self._SECTION_NAMES[self._section]))
last_section = self._section
if header_type == _C_SYS_HEADER:
if self._section <= self._C_SECTION:
self._section = self._C_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _CPP_SYS_HEADER:
if self._section <= self._CPP_SECTION:
self._section = self._CPP_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _LIKELY_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
self._section = self._OTHER_H_SECTION
elif header_type == _POSSIBLE_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
# This will always be the fallback because we're not sure
# enough that the header is associated with this file.
self._section = self._OTHER_H_SECTION
else:
assert header_type == _OTHER_HEADER
self._section = self._OTHER_H_SECTION
if last_section != self._section:
self._last_header = ''
return ''
class _CppLintState(object):
"""Maintains module-wide state.."""
def __init__(self):
self.verbose_level = 1 # global setting.
self.error_count = 0 # global count of reported errors
# filters to apply when emitting error messages
self.filters = _DEFAULT_FILTERS[:]
# backup of filter list. Used to restore the state after each file.
self._filters_backup = self.filters[:]
self.counting = 'total' # In what way are we counting errors?
self.errors_by_category = {} # string to int dict storing error counts
self.quiet = False # Suppress non-error messagess?
# output format:
# "emacs" - format that emacs can parse (default)
# "vs7" - format that Microsoft Visual Studio 7 can parse
self.output_format = 'emacs'
def SetOutputFormat(self, output_format):
"""Sets the output format for errors."""
self.output_format = output_format
def SetQuiet(self, quiet):
"""Sets the module's quiet settings, and returns the previous setting."""
last_quiet = self.quiet
self.quiet = quiet
return last_quiet
def SetVerboseLevel(self, level):
"""Sets the module's verbosity, and returns the previous setting."""
last_verbose_level = self.verbose_level
self.verbose_level = level
return last_verbose_level
def SetCountingStyle(self, counting_style):
"""Sets the module's counting options."""
self.counting = counting_style
def SetFilters(self, filters):
"""Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
"""
# Default filters always have less priority than the flag ones.
self.filters = _DEFAULT_FILTERS[:]
self.AddFilters(filters)
def AddFilters(self, filters):
""" Adds more filters to the existing list of error-message filters. """
for filt in filters.split(','):
clean_filt = filt.strip()
if clean_filt:
self.filters.append(clean_filt)
for filt in self.filters:
if not (filt.startswith('+') or filt.startswith('-')):
raise ValueError('Every filter in --filters must start with + or -'
' (%s does not)' % filt)
def BackupFilters(self):
""" Saves the current filter list to backup storage."""
self._filters_backup = self.filters[:]
def RestoreFilters(self):
""" Restores filters previously backed up."""
self.filters = self._filters_backup[:]
def ResetErrorCounts(self):
"""Sets the module's error statistic back to zero."""
self.error_count = 0
self.errors_by_category = {}
def IncrementErrorCount(self, category):
"""Bumps the module's error statistic."""
self.error_count += 1
if self.counting in ('toplevel', 'detailed'):
if self.counting != 'detailed':
category = category.split('/')[0]
if category not in self.errors_by_category:
self.errors_by_category[category] = 0
self.errors_by_category[category] += 1
def PrintErrorCounts(self):
"""Print a summary of errors by category, and the total."""
for _, category, count in self.errors_by_category.items():
sys.stderr.write('Category \'%s\' errors found: %d\n' %
(category, count))
sys.stdout.write('Total errors found: %d\n' % self.error_count)
_cpplint_state = _CppLintState()
def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format
def _SetOutputFormat(output_format):
"""Sets the module's output format."""
_cpplint_state.SetOutputFormat(output_format)
def _Quiet():
"""Return's the module's quiet setting."""
return _cpplint_state.quiet
def _SetQuiet(quiet):
"""Set the module's quiet status, and return previous setting."""
return _cpplint_state.SetQuiet(quiet)
def _VerboseLevel():
"""Returns the module's verbosity setting."""
return _cpplint_state.verbose_level
def _SetVerboseLevel(level):
"""Sets the module's verbosity, and returns the previous setting."""
return _cpplint_state.SetVerboseLevel(level)
def _SetCountingStyle(level):
"""Sets the module's counting options."""
_cpplint_state.SetCountingStyle(level)
def _Filters():
"""Returns the module's list of output filters, as a list."""
return _cpplint_state.filters
def _SetFilters(filters):
"""Sets the module's error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die.
"""
_cpplint_state.SetFilters(filters)
def _AddFilters(filters):
"""Adds more filter overrides.
Unlike _SetFilters, this function does not reset the current list of filters
available.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die.
"""
_cpplint_state.AddFilters(filters)
def _BackupFilters():
""" Saves the current filter list to backup storage."""
_cpplint_state.BackupFilters()
def _RestoreFilters():
""" Restores filters previously backed up."""
_cpplint_state.RestoreFilters()
class _FunctionState(object):
"""Tracks current function name and the number of lines in its body."""
_NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
_TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
def __init__(self):
self.in_a_function = False
self.lines_in_function = 0
self.current_function = ''
def Begin(self, function_name):
"""Start analyzing function body.
Args:
function_name: The name of the function being tracked.
"""
self.in_a_function = True
self.lines_in_function = 0
self.current_function = function_name
def Count(self):
"""Count line in current function body."""
if self.in_a_function:
self.lines_in_function += 1
def Check(self, error, filename, linenum):
"""Report if too many lines in function body.
Args:
error: The function to call with any errors found.
filename: The name of the current file.
linenum: The number of the line to check.
"""
if not self.in_a_function:
return
if Match(r'T(EST|est)', self.current_function):
base_trigger = self._TEST_TRIGGER
else:
base_trigger = self._NORMAL_TRIGGER
trigger = base_trigger * 2**_VerboseLevel()
if self.lines_in_function > trigger:
error_level = int(math.log(self.lines_in_function / base_trigger, 2))
# 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
if error_level > 5:
error_level = 5
error(filename, linenum, 'readability/fn_size', error_level,
'Small and focused functions are preferred:'
' %s has %d non-comment lines'
' (error triggered by exceeding %d lines).' % (
self.current_function, self.lines_in_function, trigger))
def End(self):
"""Stop analyzing function body."""
self.in_a_function = False
class _IncludeError(Exception):
"""Indicates a problem with the include order in a file."""
pass
class FileInfo(object):
"""Provides utility functions for filenames.
FileInfo provides easy access to the components of a file's path
relative to the project root.
"""
def __init__(self, filename):
self._filename = filename
def FullName(self):
"""Make Windows paths like Unix."""
return os.path.abspath(self._filename).replace('\\', '/')
def RepositoryName(self):
"""FullName after removing the local path to the repository.
If we have a real absolute path name here we can try to do something smart:
detecting the root of the checkout and truncating /path/to/checkout from
the name so that we get header guards that don't include things like
"C:\Documents and Settings\..." or "/home/username/..." in them and thus
people on different computers who have checked the source out to different
locations won't see bogus errors.
"""
fullname = self.FullName()
if os.path.exists(fullname):
project_dir = os.path.dirname(fullname)
if os.path.exists(os.path.join(project_dir, ".svn")):
# If there's a .svn file in the current directory, we recursively look
# up the directory tree for the top of the SVN checkout
root_dir = project_dir
one_up_dir = os.path.dirname(root_dir)
while os.path.exists(os.path.join(one_up_dir, ".svn")):
root_dir = os.path.dirname(root_dir)
one_up_dir = os.path.dirname(one_up_dir)
prefix = os.path.commonprefix([root_dir, project_dir])
return fullname[len(prefix) + 1:]
# Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
# searching up from the current path.
root_dir = current_dir = os.path.dirname(fullname)
while current_dir != os.path.dirname(current_dir):
if (os.path.exists(os.path.join(current_dir, ".git")) or
os.path.exists(os.path.join(current_dir, ".hg")) or
os.path.exists(os.path.join(current_dir, ".svn"))):
root_dir = current_dir
current_dir = os.path.dirname(current_dir)
if (os.path.exists(os.path.join(root_dir, ".git")) or
os.path.exists(os.path.join(root_dir, ".hg")) or
os.path.exists(os.path.join(root_dir, ".svn"))):
prefix = os.path.commonprefix([root_dir, project_dir])
return fullname[len(prefix) + 1:]
# Don't know what to do; header guard warnings may be wrong...
return fullname
def Split(self):
"""Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
"""
googlename = self.RepositoryName()
project, rest = os.path.split(googlename)
return (project,) + os.path.splitext(rest)
def BaseName(self):
"""File base name - text after the final slash, before the final period."""
return self.Split()[1]
def Extension(self):
"""File extension - text following the final period."""
return self.Split()[2]
def NoExtension(self):
"""File has no source file extension."""
return '/'.join(self.Split()[0:2])
def IsSource(self):
"""File has a source file extension."""
return _IsSourceExtension(self.Extension()[1:])
def _ShouldPrintError(category, confidence, linenum):
"""If confidence >= verbose, category passes filter and is not suppressed."""
# There are three ways we might decide not to print an error message:
# a "NOLINT(category)" comment appears in the source,
# the verbosity level isn't high enough, or the filters filter it out.
if IsErrorSuppressedByNolint(category, linenum):
return False
if confidence < _cpplint_state.verbose_level:
return False
is_filtered = False
for one_filter in _Filters():
if one_filter.startswith('-'):
if category.startswith(one_filter[1:]):
is_filtered = True
elif one_filter.startswith('+'):
if category.startswith(one_filter[1:]):
is_filtered = False
else:
assert False # should have been checked for in SetFilter.
if is_filtered:
return False
return True
def Error(filename, linenum, category, confidence, message):
"""Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
False positives can be suppressed by the use of
"cpplint(category)" comments on the offending line. These are
parsed into _error_suppressions.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message.
"""
if _ShouldPrintError(category, confidence, linenum):
_cpplint_state.IncrementErrorCount(category)
if _cpplint_state.output_format == 'vs7':
sys.stderr.write('%s(%s): error cpplint: [%s] %s [%d]\n' % (
filename, linenum, category, message, confidence))
elif _cpplint_state.output_format == 'eclipse':
sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
else:
sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
# Match a single C style comment on the same line.
_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'
# Matches multi-line C style comments.
# This RE is a little bit more complicated than one might expect, because we
# have to take care of space removals tools so we can handle comments inside
# statements better.
# The current rule is: We only clear spaces from both sides when we're at the
# end of the line. Otherwise, we try to remove spaces from the right side,
# if this doesn't work we try on left side but only if there's a non-character
# on the right.
_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +
_RE_PATTERN_C_COMMENTS + r'\s+|' +
r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +
_RE_PATTERN_C_COMMENTS + r')')
def IsCppString(line):
"""Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant.
"""
line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
def CleanseRawStrings(raw_lines):
"""Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw strings replaced by empty strings.
"""
delimiter = None
lines_without_raw_strings = []
for line in raw_lines:
if delimiter:
# Inside a raw string, look for the end
end = line.find(delimiter)
if end >= 0:
# Found the end of the string, match leading space for this
# line and resume copying the original lines, and also insert
# a "" on the last line.
leading_space = Match(r'^(\s*)\S', line)
line = leading_space.group(1) + '""' + line[end + len(delimiter):]
delimiter = None
else:
# Haven't found the end yet, append a blank line.
line = '""'
# Look for beginning of a raw string, and replace them with
# empty strings. This is done in a loop to handle multiple raw
# strings on the same line.
while delimiter is None:
# Look for beginning of a raw string.
# See 2.14.15 [lex.string] for syntax.
#
# Once we have matched a raw string, we check the prefix of the
# line to make sure that the line is not part of a single line
# comment. It's done this way because we remove raw strings
# before removing comments as opposed to removing comments
# before removing raw strings. This is because there are some
# cpplint checks that requires the comments to be preserved, but
# we don't want to check comments that are inside raw strings.
matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
if (matched and
not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
matched.group(1))):
delimiter = ')' + matched.group(2) + '"'
end = matched.group(3).find(delimiter)
if end >= 0:
# Raw string ended on same line
line = (matched.group(1) + '""' +
matched.group(3)[end + len(delimiter):])
delimiter = None
else:
# Start of a multi-line raw string
line = matched.group(1) + '""'
else:
break
lines_without_raw_strings.append(line)
# TODO(unknown): if delimiter is not None here, we might want to
# emit a warning for unterminated string.
return lines_without_raw_strings
def FindNextMultiLineCommentStart(lines, lineix):
"""Find the beginning marker for a multiline comment."""
while lineix < len(lines):
if lines[lineix].strip().startswith('/*'):
# Only return this marker if the comment goes beyond this line
if lines[lineix].strip().find('*/', 2) < 0:
return lineix
lineix += 1
return len(lines)
def FindNextMultiLineCommentEnd(lines, lineix):
"""We are inside a comment, find the end marker."""
while lineix < len(lines):
if lines[lineix].strip().endswith('*/'):
return lineix
lineix += 1
return len(lines)
def RemoveMultiLineCommentsFromRange(lines, begin, end):
"""Clears a range of lines for multi-line comments."""
# Having // dummy comments makes the lines non-empty, so we will not get
# unnecessary blank line warnings later in the code.
for i in range(begin, end):
lines[i] = '/**/'
def RemoveMultiLineComments(filename, lines, error):
"""Removes multiline (c-style) comments from lines."""
lineix = 0
while lineix < len(lines):
lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
if lineix_begin >= len(lines):
return
lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
if lineix_end >= len(lines):
error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
'Could not find end of multi-line comment')
return
RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
lineix = lineix_end + 1
def CleanseComments(line):
"""Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
"""
commentpos = line.find('//')
if commentpos != -1 and not IsCppString(line[:commentpos]):
line = line[:commentpos].rstrip()
# get rid of /* ... */
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
class CleansedLines(object):
"""Holds 4 copies of all lines with different preprocessing applied to them.
1) elided member contains lines without strings and comments.
2) lines member contains lines without comments.
3) raw_lines member contains all the lines without processing.
4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
strings removed.
All these members are of <type 'list'>, and of the same length.
"""
def __init__(self, lines):
self.elided = []
self.lines = []
self.raw_lines = lines
self.num_lines = len(lines)
self.lines_without_raw_strings = CleanseRawStrings(lines)
for linenum in range(len(self.lines_without_raw_strings)):
self.lines.append(CleanseComments(
self.lines_without_raw_strings[linenum]))
elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
self.elided.append(CleanseComments(elided))
def NumLines(self):
"""Returns the number of lines represented."""
return self.num_lines
@staticmethod
def _CollapseStrings(elided):
"""Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings.
"""
if _RE_PATTERN_INCLUDE.match(elided):
return elided
# Remove escaped characters first to make quote/single quote collapsing
# basic. Things that look like escaped characters shouldn't occur
# outside of strings and chars.
elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
# Replace quoted strings and digit separators. Both single quotes
# and double quotes are processed in the same loop, otherwise
# nested quotes wouldn't work.
collapsed = ''
while True:
# Find the first quote character
match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
if not match:
collapsed += elided
break
head, quote, tail = match.groups()
if quote == '"':
# Collapse double quoted strings
second_quote = tail.find('"')
if second_quote >= 0:
collapsed += head + '""'
elided = tail[second_quote + 1:]
else:
# Unmatched double quote, don't bother processing the rest
# of the line since this is probably a multiline string.
collapsed += elided
break
else:
# Found single quote, check nearby text to eliminate digit separators.
#
# There is no special handling for floating point here, because
# the integer/fractional/exponent parts would all be parsed
# correctly as long as there are digits on both sides of the
# separator. So we are fine as long as we don't see something
# like "0.'3" (gcc 4.9.0 will not allow this literal).
if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
collapsed += head + match_literal.group(1).replace("'", '')
elided = match_literal.group(2)
else:
second_quote = tail.find('\'')
if second_quote >= 0:
collapsed += head + "''"
elided = tail[second_quote + 1:]
else:
# Unmatched single quote
collapsed += elided
break
return collapsed
def FindEndOfExpressionInLine(line, startpos, stack):
"""Find the position just after the end of current parenthesized expression.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
stack: nesting stack at startpos.
Returns:
On finding matching end: (index just after matching end, None)
On finding an unclosed expression: (-1, None)
Otherwise: (-1, new stack at end of this line)
"""
for i in range(startpos, len(line)):
char = line[i]
if char in '([{':
# Found start of parenthesized expression, push to expression stack
stack.append(char)
elif char == '<':
# Found potential start of template argument list
if i > 0 and line[i - 1] == '<':
# Left shift operator
if stack and stack[-1] == '<':
stack.pop()
if not stack:
return (-1, None)
elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
# operator<, don't add to stack
continue
else:
# Tentative start of template argument list
stack.append('<')
elif char in ')]}':
# Found end of parenthesized expression.
#
# If we are currently expecting a matching '>', the pending '<'
# must have been an operator. Remove them from expression stack.
while stack and stack[-1] == '<':
stack.pop()
if not stack:
return (-1, None)
if ((stack[-1] == '(' and char == ')') or
(stack[-1] == '[' and char == ']') or
(stack[-1] == '{' and char == '}')):
stack.pop()
if not stack:
return (i + 1, None)
else:
# Mismatched parentheses
return (-1, None)
elif char == '>':
# Found potential end of template argument list.
# Ignore "->" and operator functions
if (i > 0 and
(line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
continue
# Pop the stack if there is a matching '<'. Otherwise, ignore
# this '>' since it must be an operator.
if stack:
if stack[-1] == '<':
stack.pop()
if not stack:
return (i + 1, None)
elif char == ';':
# Found something that look like end of statements. If we are currently
# expecting a '>', the matching '<' must have been an operator, since
# template argument list should not contain statements.
while stack and stack[-1] == '<':
stack.pop()
if not stack:
return (-1, None)
# Did not find end of expression or unbalanced parentheses on this line
return (-1, stack)
def CloseExpression(clean_lines, linenum, pos):
"""If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
TODO(unknown): cpplint spends a fair bit of time matching parentheses.
Ideally we would want to index all opening and closing parentheses once
and have CloseExpression be just a simple lookup, but due to preprocessor
tricks, this is not so easy.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
return (line, clean_lines.NumLines(), -1)
# Check first line
(end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
if end_pos > -1:
return (line, linenum, end_pos)
# Continue scanning forward
while stack and linenum < clean_lines.NumLines() - 1:
linenum += 1
line = clean_lines.elided[linenum]
(end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
if end_pos > -1:
return (line, linenum, end_pos)
# Did not find end of expression before end of file, give up
return (line, clean_lines.NumLines(), -1)
def FindStartOfExpressionInLine(line, endpos, stack):
"""Find position at the matching start of current expression.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
stack: nesting stack at endpos.
Returns:
On finding matching start: (index at matching start, None)
On finding an unclosed expression: (-1, None)
Otherwise: (-1, new stack at beginning of this line)
"""
i = endpos
while i >= 0:
char = line[i]
if char in ')]}':
# Found end of expression, push to expression stack
stack.append(char)
elif char == '>':
# Found potential end of template argument list.
#
# Ignore it if it's a "->" or ">=" or "operator>"
if (i > 0 and
(line[i - 1] == '-' or
Match(r'\s>=\s', line[i - 1:]) or
Search(r'\boperator\s*$', line[0:i]))):
i -= 1
else:
stack.append('>')
elif char == '<':
# Found potential start of template argument list
if i > 0 and line[i - 1] == '<':
# Left shift operator
i -= 1
else:
# If there is a matching '>', we can pop the expression stack.
# Otherwise, ignore this '<' since it must be an operator.
if stack and stack[-1] == '>':
stack.pop()
if not stack:
return (i, None)
elif char in '([{':
# Found start of expression.
#
# If there are any unmatched '>' on the stack, they must be
# operators. Remove those.
while stack and stack[-1] == '>':
stack.pop()
if not stack:
return (-1, None)
if ((char == '(' and stack[-1] == ')') or
(char == '[' and stack[-1] == ']') or
(char == '{' and stack[-1] == '}')):
stack.pop()
if not stack:
return (i, None)
else:
# Mismatched parentheses
return (-1, None)
elif char == ';':
# Found something that look like end of statements. If we are currently
# expecting a '<', the matching '>' must have been an operator, since
# template argument list should not contain statements.
while stack and stack[-1] == '>':
stack.pop()
if not stack:
return (-1, None)
i -= 1
return (-1, stack)
def ReverseCloseExpression(clean_lines, linenum, pos):
"""If input points to ) or } or ] or >, finds the position that opens it.
If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
linenum/pos that correspond to the opening of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *at* the opening brace, or
(line, 0, -1) if we never find the matching opening brace. Note
we ignore strings and comments when matching; and the line we
return is the 'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
if line[pos] not in ')}]>':
return (line, 0, -1)
# Check last line
(start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
if start_pos > -1:
return (line, linenum, start_pos)
# Continue scanning backward
while stack and linenum > 0:
linenum -= 1
line = clean_lines.elided[linenum]
(start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
if start_pos > -1:
return (line, linenum, start_pos)
# Did not find start of expression before beginning of file, give up
return (line, 0, -1)
def CheckForCopyright(filename, lines, error):
"""Logs an error if no Copyright message appears at the top of the file."""
# We'll say it should occur by line 10. Don't forget there's a
# dummy line at the front.
for line in range(1, min(len(lines), 11)):
if re.search(r'Copyright', lines[line], re.I): break
else: # means no copyright line was found
error(filename, 0, 'legal/copyright', 5,
'No copyright message found. '
'You should have a line: "Copyright [year] <Copyright Owner>"')
def GetIndentLevel(line):
"""Return the number of leading spaces in line.
Args:
line: A string to check.
Returns:
An integer count of leading spaces, possibly zero.
"""
indent = Match(r'^( *)\S', line)
if indent:
return len(indent.group(1))
else:
return 0
def PathSplitToList(path):
"""Returns the path split into a list by the separator.
Args:
path: An absolute or relative path (e.g. '/a/b/c/' or '../a')
Returns:
A list of path components (e.g. ['a', 'b', 'c]).
"""
lst = []
while True:
(head, tail) = os.path.split(path)
if head == path: # absolute paths end
lst.append(head)
break
if tail == path: # relative paths end
lst.append(tail)
break
path = head
lst.append(tail)
lst.reverse()
return lst
def GetHeaderGuardCPPVariable(filename):
"""Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file.
"""
# Restores original filename in case that cpplint is invoked from Emacs's
# flymake.
filename = re.sub(r'_flymake\.h$', '.h', filename)
filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
# Replace 'c++' with 'cpp'.
filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
fileinfo = FileInfo(filename)
file_path_from_root = fileinfo.RepositoryName()
def FixupPathFromRoot():
if _root_debug:
sys.stderr.write("\n_root fixup, _root = '%s', repository name = '%s'\n"
%(_root, fileinfo.RepositoryName()))
# Process the file path with the --root flag if it was set.
if not _root:
if _root_debug:
sys.stderr.write("_root unspecified\n")
return file_path_from_root
def StripListPrefix(lst, prefix):
# f(['x', 'y'], ['w, z']) -> None (not a valid prefix)
if lst[:len(prefix)] != prefix:
return None
# f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']
return lst[(len(prefix)):]
# root behavior:
# --root=subdir , lstrips subdir from the header guard
maybe_path = StripListPrefix(PathSplitToList(file_path_from_root),
PathSplitToList(_root))
if _root_debug:
sys.stderr.write("_root lstrip (maybe_path=%s, file_path_from_root=%s," +
" _root=%s)\n" %(maybe_path, file_path_from_root, _root))
if maybe_path:
return os.path.join(*maybe_path)
# --root=.. , will prepend the outer directory to the header guard
full_path = fileinfo.FullName()
root_abspath = os.path.abspath(_root)
maybe_path = StripListPrefix(PathSplitToList(full_path),
PathSplitToList(root_abspath))
if _root_debug:
sys.stderr.write("_root prepend (maybe_path=%s, full_path=%s, " +
"root_abspath=%s)\n" %(maybe_path, full_path, root_abspath))
if maybe_path:
return os.path.join(*maybe_path)
if _root_debug:
sys.stderr.write("_root ignore, returning %s\n" %(file_path_from_root))
# --root=FAKE_DIR is ignored
return file_path_from_root
file_path_from_root = FixupPathFromRoot()
return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
def CheckForHeaderGuard(filename, clean_lines, error):
"""Checks that the file contains a header guard.
Logs an error if no #ifndef header guard is present. For other
headers, checks that the full pathname is used.
Args:
filename: The name of the C++ header file.
clean_lines: A CleansedLines instance containing the file.
error: The function to call with any errors found.
"""
# Don't check for header guards if there are error suppression
# comments somewhere in this file.
#
# Because this is silencing a warning for a nonexistent line, we
# only support the very specific NOLINT(build/header_guard) syntax,
# and not the general NOLINT or NOLINT(*) syntax.
raw_lines = clean_lines.lines_without_raw_strings
for i in raw_lines:
if Search(r'//\s*NOLINT\(build/header_guard\)', i):
return
cppvar = GetHeaderGuardCPPVariable(filename)
ifndef = ''
ifndef_linenum = 0
define = ''
endif = ''
endif_linenum = 0
for linenum, line in enumerate(raw_lines):
linesplit = line.split()
if len(linesplit) >= 2:
# find the first occurrence of #ifndef and #define, save arg
if not ifndef and linesplit[0] == '#ifndef':
# set ifndef to the header guard presented on the #ifndef line.
ifndef = linesplit[1]
ifndef_linenum = linenum
if not define and linesplit[0] == '#define':
define = linesplit[1]
# find the last occurrence of #endif, save entire line
if line.startswith('#endif'):
endif = line
endif_linenum = linenum
if not ifndef or not define or ifndef != define:
error(filename, 0, 'build/header_guard', 5,
'No #ifndef header guard found, suggested CPP variable is: %s' %
cppvar)
return
# The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
# for backward compatibility.
if ifndef != cppvar:
error_level = 0
if ifndef != cppvar + '_':
error_level = 5
ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
error)
error(filename, ifndef_linenum, 'build/header_guard', error_level,
'#ifndef header guard has wrong style, please use: %s' % cppvar)
# Check for "//" comments on endif line.
ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
error)
match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
if match:
if match.group(1) == '_':
# Issue low severity warning for deprecated double trailing underscore
error(filename, endif_linenum, 'build/header_guard', 0,
'#endif line should be "#endif // %s"' % cppvar)
return
# Didn't find the corresponding "//" comment. If this file does not
# contain any "//" comments at all, it could be that the compiler
# only wants "/**/" comments, look for those instead.
no_single_line_comments = True
for i in range(1, len(raw_lines) - 1):
line = raw_lines[i]
if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
no_single_line_comments = False
break
if no_single_line_comments:
match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
if match:
if match.group(1) == '_':
# Low severity warning for double trailing underscore
error(filename, endif_linenum, 'build/header_guard', 0,
'#endif line should be "#endif /* %s */"' % cppvar)
return
# Didn't find anything
error(filename, endif_linenum, 'build/header_guard', 5,
'#endif line should be "#endif // %s"' % cppvar)
def CheckHeaderFileIncluded(filename, include_state, error):
"""Logs an error if a .cc file does not include its header."""
# Do not check test files
fileinfo = FileInfo(filename)
if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
return
headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
if not os.path.exists(headerfile):
return
headername = FileInfo(headerfile).RepositoryName()
first_include = 0
for section_list in include_state.include_list:
for f in section_list:
if headername in f[0] or f[0] in headername:
return
if not first_include:
first_include = f[1]
error(filename, first_include, 'build/include', 5,
'%s should include its header file %s' % (fileinfo.RepositoryName(),
headername))
def CheckForBadCharacters(filename, lines, error):
"""Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
for linenum, line in enumerate(lines):
if u'\ufffd' in line:
error(filename, linenum, 'readability/utf8', 5,
'Line contains invalid UTF-8 (or Unicode replacement character).')
if '\0' in line:
error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
def CheckForNewlineAtEOF(filename, lines, error):
"""Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
# The array lines() was created by adding two newlines to the
# original file (go figure), then splitting on \n.
# To verify that the file ends in \n, we just have to make sure the
# last-but-two element of lines() exists and is empty.
if len(lines) < 3 or lines[-2]:
error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
'Could not find a newline character at the end of the file.')
def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
"""Logs an error if we see /* ... */ or "..." that extend past one line.
/* ... */ comments are legit inside macros, for one line.
Otherwise, we prefer // comments, so it's ok to warn about the
other. Likewise, it's ok for strings to extend across multiple
lines, as long as a line continuation character (backslash)
terminates each line. Although not currently prohibited by the C++
style guide, it's ugly and unnecessary. We don't do well with either
in this lint program, so we warn about both.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Remove all \\ (escaped backslashes) from the line. They are OK, and the
# second (escaped) slash may trigger later \" detection erroneously.
line = line.replace('\\\\', '')
if line.count('/*') > line.count('*/'):
error(filename, linenum, 'readability/multiline_comment', 5,
'Complex multi-line /*...*/-style comment found. '
'Lint may give bogus warnings. '
'Consider replacing these with //-style comments, '
'with #if 0...#endif, '
'or with more clearly structured multi-line comments.')
if (line.count('"') - line.count('\\"')) % 2:
error(filename, linenum, 'readability/multiline_string', 5,
'Multi-line string ("...") found. This lint script doesn\'t '
'do well with such strings, and may give bogus warnings. '
'Use C++11 raw strings or concatenation instead.')
# (non-threadsafe name, thread-safe alternative, validation pattern)
#
# The validation pattern is used to eliminate false positives such as:
# _rand(); // false positive due to substring match.
# ->rand(); // some member function rand().
# ACMRandom rand(seed); // some variable named rand.
# ISAACRandom rand(); // another variable named rand.
#
# Basically we require the return value of these functions to be used
# in some expression context on the same line by matching on some
# operator before the function name. This eliminates constructors and
# member function calls.
_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
_THREADING_LIST = (
('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),
('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),
('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),
('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),
('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),
('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),
('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),
('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),
('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),
('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),
('strtok(', 'strtok_r(',
_UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),
('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),
)
def CheckPosixThreading(filename, clean_lines, linenum, error):
"""Checks for calls to thread-unsafe functions.
Much code has been originally written without consideration of
multi-threading. Also, engineers are relying on their old experience;
they have learned posix before threading extensions were added. These
tests guide the engineers to use thread-safe functions (when using
posix directly).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
# Additional pattern matching check to confirm that this is the
# function we are looking for
if Search(pattern, line):
error(filename, linenum, 'runtime/threadsafe_fn', 2,
'Consider using ' + multithread_safe_func +
'...) instead of ' + single_thread_func +
'...) for improved thread safety.')
def CheckVlogArguments(filename, clean_lines, linenum, error):
"""Checks that VLOG() is only used for defining a logging level.
For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
VLOG(FATAL) are not.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
error(filename, linenum, 'runtime/vlog', 5,
'VLOG() should be used with numeric verbosity level. '
'Use LOG() if you want symbolic severity levels.')
# Matches invalid increment: *count++, which moves pointer instead of
# incrementing a value.
_RE_PATTERN_INVALID_INCREMENT = re.compile(
r'^\s*\*\w+(\+\+|--);')
def CheckInvalidIncrement(filename, clean_lines, linenum, error):
"""Checks for invalid increment *count++.
For example following function:
void increment_counter(int* count) {
*count++;
}
is invalid, because it effectively does count++, moving pointer, and should
be replaced with ++*count, (*count)++ or *count += 1.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
if _RE_PATTERN_INVALID_INCREMENT.match(line):
error(filename, linenum, 'runtime/invalid_increment', 5,
'Changing pointer instead of value (or unused value of operator*).')
def IsMacroDefinition(clean_lines, linenum):
if Search(r'^#define', clean_lines[linenum]):
return True
if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
return True
return False
def IsForwardClassDeclaration(clean_lines, linenum):
return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
class _BlockInfo(object):
"""Stores information about a generic block of code."""
def __init__(self, linenum, seen_open_brace):
self.starting_linenum = linenum
self.seen_open_brace = seen_open_brace
self.open_parentheses = 0
self.inline_asm = _NO_ASM
self.check_namespace_indentation = False
def CheckBegin(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text up to the opening brace.
This is mostly for checking the text after the class identifier
and the "{", usually where the base class is specified. For other
blocks, there isn't much to check, so we always pass.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
pass
def CheckEnd(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
pass
def IsBlockInfo(self):
"""Returns true if this block is a _BlockInfo.
This is convenient for verifying that an object is an instance of
a _BlockInfo, but not an instance of any of the derived classes.
Returns:
True for this class, False for derived classes.
"""
return self.__class__ == _BlockInfo
class _ExternCInfo(_BlockInfo):
"""Stores information about an 'extern "C"' block."""
def __init__(self, linenum):
_BlockInfo.__init__(self, linenum, True)
class _ClassInfo(_BlockInfo):
"""Stores information about a class."""
def __init__(self, name, class_or_struct, clean_lines, linenum):
_BlockInfo.__init__(self, linenum, False)
self.name = name
self.is_derived = False
self.check_namespace_indentation = True
if class_or_struct == 'struct':
self.access = 'public'
self.is_struct = True
else:
self.access = 'private'
self.is_struct = False
# Remember initial indentation level for this class. Using raw_lines here
# instead of elided to account for leading comments.
self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
# Try to find the end of the class. This will be confused by things like:
# class A {
# } *x = { ...
#
# But it's still good enough for CheckSectionSpacing.
self.last_line = 0
depth = 0
for i in range(linenum, clean_lines.NumLines()):
line = clean_lines.elided[i]
depth += line.count('{') - line.count('}')
if not depth:
self.last_line = i
break
def CheckBegin(self, filename, clean_lines, linenum, error):
# Look for a bare ':'
if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
self.is_derived = True
def CheckEnd(self, filename, clean_lines, linenum, error):
# If there is a DISALLOW macro, it should appear near the end of
# the class.
seen_last_thing_in_class = False
for i in range(linenum - 1, self.starting_linenum, -1):
match = Search(
r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +
self.name + r'\)',
clean_lines.elided[i])
if match:
if seen_last_thing_in_class:
error(filename, i, 'readability/constructors', 3,
match.group(1) + ' should be the last thing in the class')
break
if not Match(r'^\s*$', clean_lines.elided[i]):
seen_last_thing_in_class = True
# Check that closing brace is aligned with beginning of the class.
# Only do this if the closing brace is indented by only whitespaces.
# This means we will not check single-line class definitions.
indent = Match(r'^( *)\}', clean_lines.elided[linenum])
if indent and len(indent.group(1)) != self.class_indent:
if self.is_struct:
parent = 'struct ' + self.name
else:
parent = 'class ' + self.name
error(filename, linenum, 'whitespace/indent', 3,
'Closing brace should be aligned with beginning of %s' % parent)
class _NamespaceInfo(_BlockInfo):
"""Stores information about a namespace."""
def __init__(self, name, linenum):
_BlockInfo.__init__(self, linenum, False)
self.name = name or ''
self.check_namespace_indentation = True
def CheckEnd(self, filename, clean_lines, linenum, error):
"""Check end of namespace comments."""
line = clean_lines.raw_lines[linenum]
# Check how many lines is enclosed in this namespace. Don't issue
# warning for missing namespace comments if there aren't enough
# lines. However, do apply checks if there is already an end of
# namespace comment and it's incorrect.
#
# TODO(unknown): We always want to check end of namespace comments
# if a namespace is large, but sometimes we also want to apply the
# check if a short namespace contained nontrivial things (something
# other than forward declarations). There is currently no logic on
# deciding what these nontrivial things are, so this check is
# triggered by namespace size only, which works most of the time.
if (linenum - self.starting_linenum < 10
and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
return
# Look for matching comment at end of namespace.
#
# Note that we accept C style "/* */" comments for terminating
# namespaces, so that code that terminate namespaces inside
# preprocessor macros can be cpplint clean.
#
# We also accept stuff like "// end of namespace <name>." with the
# period at the end.
#
# Besides these, we don't accept anything else, otherwise we might
# get false negatives when existing comment is a substring of the
# expected namespace.
if self.name:
# Named namespace
if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
re.escape(self.name) + r'[\*/\.\\\s]*$'),
line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace %s"' %
self.name)
else:
# Anonymous namespace
if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
# If "// namespace anonymous" or "// anonymous namespace (more text)",
# mention "// anonymous namespace" as an acceptable form
if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
error(filename, linenum, 'readability/namespace', 5,
'Anonymous namespace should be terminated with "// namespace"'
' or "// anonymous namespace"')
else:
error(filename, linenum, 'readability/namespace', 5,
'Anonymous namespace should be terminated with "// namespace"')
class _PreprocessorInfo(object):
"""Stores checkpoints of nesting stacks when #if/#else is seen."""
def __init__(self, stack_before_if):
# The entire nesting stack before #if
self.stack_before_if = stack_before_if
# The entire nesting stack up to #else
self.stack_before_else = []
# Whether we have already seen #else or #elif
self.seen_else = False
class NestingState(object):
"""Holds states related to parsing braces."""
def __init__(self):
# Stack for tracking all braces. An object is pushed whenever we
# see a "{", and popped when we see a "}". Only 3 types of
# objects are possible:
# - _ClassInfo: a class or struct.
# - _NamespaceInfo: a namespace.
# - _BlockInfo: some other type of block.
self.stack = []
# Top of the previous stack before each Update().
#
# Because the nesting_stack is updated at the end of each line, we
# had to do some convoluted checks to find out what is the current
# scope at the beginning of the line. This check is simplified by
# saving the previous top of nesting stack.
#
# We could save the full stack, but we only need the top. Copying
# the full nesting stack would slow down cpplint by ~10%.
self.previous_stack_top = []
# Stack of _PreprocessorInfo objects.
self.pp_stack = []
def SeenOpenBrace(self):
"""Check if we have seen the opening brace for the innermost block.
Returns:
True if we have seen the opening brace, False if the innermost
block is still expecting an opening brace.
"""
return (not self.stack) or self.stack[-1].seen_open_brace
def InNamespaceBody(self):
"""Check if we are currently one level inside a namespace body.
Returns:
True if top of the stack is a namespace block, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
def InExternC(self):
"""Check if we are currently one level inside an 'extern "C"' block.
Returns:
True if top of the stack is an extern block, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _ExternCInfo)
def InClassDeclaration(self):
"""Check if we are currently one level inside a class or struct declaration.
Returns:
True if top of the stack is a class/struct, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _ClassInfo)
def InAsmBlock(self):
"""Check if we are currently one level inside an inline ASM block.
Returns:
True if the top of the stack is a block containing inline ASM.
"""
return self.stack and self.stack[-1].inline_asm != _NO_ASM
def InTemplateArgumentList(self, clean_lines, linenum, pos):
"""Check if current position is inside template argument list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: position just after the suspected template argument.
Returns:
True if (linenum, pos) is inside template arguments.
"""
while linenum < clean_lines.NumLines():
# Find the earliest character that might indicate a template argument
line = clean_lines.elided[linenum]
match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
if not match:
linenum += 1
pos = 0
continue
token = match.group(1)
pos += len(match.group(0))
# These things do not look like template argument list:
# class Suspect {
# class Suspect x; }
if token in ('{', '}', ';'): return False
# These things look like template argument list:
# template <class Suspect>
# template <class Suspect = default_value>
# template <class Suspect[]>
# template <class Suspect...>
if token in ('>', '=', '[', ']', '.'): return True
# Check if token is an unmatched '<'.
# If not, move on to the next character.
if token != '<':
pos += 1
if pos >= len(line):
linenum += 1
pos = 0
continue
# We can't be sure if we just find a single '<', and need to
# find the matching '>'.
(_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
if end_pos < 0:
# Not sure if template argument list or syntax error in file
return False
linenum = end_line
pos = end_pos
return False
def UpdatePreprocessor(self, line):
"""Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check.
"""
if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
# Beginning of #if block, save the nesting stack here. The saved
# stack will allow us to restore the parsing state in the #else case.
self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
elif Match(r'^\s*#\s*(else|elif)\b', line):
# Beginning of #else block
if self.pp_stack:
if not self.pp_stack[-1].seen_else:
# This is the first #else or #elif block. Remember the
# whole nesting stack up to this point. This is what we
# keep after the #endif.
self.pp_stack[-1].seen_else = True
self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
# Restore the stack to how it was before the #if
self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
else:
# TODO(unknown): unexpected #else, issue warning?
pass
elif Match(r'^\s*#\s*endif\b', line):
# End of #if or #else blocks.
if self.pp_stack:
# If we saw an #else, we will need to restore the nesting
# stack to its former state before the #else, otherwise we
# will just continue from where we left off.
if self.pp_stack[-1].seen_else:
# Here we can just use a shallow copy since we are the last
# reference to it.
self.stack = self.pp_stack[-1].stack_before_else
# Drop the corresponding #if
self.pp_stack.pop()
else:
# TODO(unknown): unexpected #endif, issue warning?
pass
# TODO(unknown): Update() is too long, but we will refactor later.
def Update(self, filename, clean_lines, linenum, error):
"""Update nesting state with current line.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Remember top of the previous nesting stack.
#
# The stack is always pushed/popped and not modified in place, so
# we can just do a shallow copy instead of copy.deepcopy. Using
# deepcopy would slow down cpplint by ~28%.
if self.stack:
self.previous_stack_top = self.stack[-1]
else:
self.previous_stack_top = None
# Update pp_stack
self.UpdatePreprocessor(line)
# Count parentheses. This is to avoid adding struct arguments to
# the nesting stack.
if self.stack:
inner_block = self.stack[-1]
depth_change = line.count('(') - line.count(')')
inner_block.open_parentheses += depth_change
# Also check if we are starting or ending an inline assembly block.
if inner_block.inline_asm in (_NO_ASM, _END_ASM):
if (depth_change != 0 and
inner_block.open_parentheses == 1 and
_MATCH_ASM.match(line)):
# Enter assembly block
inner_block.inline_asm = _INSIDE_ASM
else:
# Not entering assembly block. If previous line was _END_ASM,
# we will now shift to _NO_ASM state.
inner_block.inline_asm = _NO_ASM
elif (inner_block.inline_asm == _INSIDE_ASM and
inner_block.open_parentheses == 0):
# Exit assembly block
inner_block.inline_asm = _END_ASM
# Consume namespace declaration at the beginning of the line. Do
# this in a loop so that we catch same line declarations like this:
# namespace proto2 { namespace bridge { class MessageSet; } }
while True:
# Match start of namespace. The "\b\s*" below catches namespace
# declarations even if it weren't followed by a whitespace, this
# is so that we don't confuse our namespace checker. The
# missing spaces will be flagged by CheckSpacing.
namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
if not namespace_decl_match:
break
new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
self.stack.append(new_namespace)
line = namespace_decl_match.group(2)
if line.find('{') != -1:
new_namespace.seen_open_brace = True
line = line[line.find('{') + 1:]
# Look for a class declaration in whatever is left of the line
# after parsing namespaces. The regexp accounts for decorated classes
# such as in:
# class LOCKABLE API Object {
# };
class_decl_match = Match(
r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'
r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))'
r'(.*)$', line)
if (class_decl_match and
(not self.stack or self.stack[-1].open_parentheses == 0)):
# We do not want to accept classes that are actually template arguments:
# template <class Ignore1,
# class Ignore2 = Default<Args>,
# template <Args> class Ignore3>
# void Function() {};
#
# To avoid template argument cases, we scan forward and look for
# an unmatched '>'. If we see one, assume we are inside a
# template argument list.
end_declaration = len(class_decl_match.group(1))
if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
self.stack.append(_ClassInfo(
class_decl_match.group(3), class_decl_match.group(2),
clean_lines, linenum))
line = class_decl_match.group(4)
# If we have not yet seen the opening brace for the innermost block,
# run checks here.
if not self.SeenOpenBrace():
self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
# Update access control if we are inside a class/struct
if self.stack and isinstance(self.stack[-1], _ClassInfo):
classinfo = self.stack[-1]
access_match = Match(
r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
r':(?:[^:]|$)',
line)
if access_match:
classinfo.access = access_match.group(2)
# Check that access keywords are indented +1 space. Skip this
# check if the keywords are not preceded by whitespaces.
indent = access_match.group(1)
if (len(indent) != classinfo.class_indent + 1 and
Match(r'^\s*$', indent)):
if classinfo.is_struct:
parent = 'struct ' + classinfo.name
else:
parent = 'class ' + classinfo.name
slots = ''
if access_match.group(3):
slots = access_match.group(3)
error(filename, linenum, 'whitespace/indent', 3,
'%s%s: should be indented +1 space inside %s' % (
access_match.group(2), slots, parent))
# Consume braces or semicolons from what's left of the line
while True:
# Match first brace, semicolon, or closed parenthesis.
matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
if not matched:
break
token = matched.group(1)
if token == '{':
# If namespace or class hasn't seen a opening brace yet, mark
# namespace/class head as complete. Push a new block onto the
# stack otherwise.
if not self.SeenOpenBrace():
self.stack[-1].seen_open_brace = True
elif Match(r'^extern\s*"[^"]*"\s*\{', line):
self.stack.append(_ExternCInfo(linenum))
else:
self.stack.append(_BlockInfo(linenum, True))
if _MATCH_ASM.match(line):
self.stack[-1].inline_asm = _BLOCK_ASM
elif token == ';' or token == ')':
# If we haven't seen an opening brace yet, but we already saw
# a semicolon, this is probably a forward declaration. Pop
# the stack for these.
#
# Similarly, if we haven't seen an opening brace yet, but we
# already saw a closing parenthesis, then these are probably
# function arguments with extra "class" or "struct" keywords.
# Also pop these stack for these.
if not self.SeenOpenBrace():
self.stack.pop()
else: # token == '}'
# Perform end of block checks and pop the stack.
if self.stack:
self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
self.stack.pop()
line = matched.group(2)
def InnermostClass(self):
"""Get class info on the top of the stack.
Returns:
A _ClassInfo object if we are inside a class, or None otherwise.
"""
for i in range(len(self.stack), 0, -1):
classinfo = self.stack[i - 1]
if isinstance(classinfo, _ClassInfo):
return classinfo
return None
def CheckCompletedBlocks(self, filename, error):
"""Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found.
"""
# Note: This test can result in false positives if #ifdef constructs
# get in the way of brace matching. See the testBuildClass test in
# cpplint_unittest.py for an example of this.
for obj in self.stack:
if isinstance(obj, _ClassInfo):
error(filename, obj.starting_linenum, 'build/class', 5,
'Failed to find complete declaration of class %s' %
obj.name)
elif isinstance(obj, _NamespaceInfo):
error(filename, obj.starting_linenum, 'build/namespaces', 5,
'Failed to find complete declaration of namespace %s' %
obj.name)
def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage-class specifier (static, extern, typedef, etc) should be '
'at the beginning of the declaration.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Everything else in this function operates on class declarations.
# Return early if the top of the nesting stack is not a class, or if
# the class head is not completed yet.
classinfo = nesting_state.InnermostClass()
if not classinfo or not classinfo.seen_open_brace:
return
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
explicit_constructor_match = Match(
r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?'
r'(?:(?:inline|constexpr)\s+)*%s\s*'
r'\(((?:[^()]|\([^()]*\))*)\)'
% re.escape(base_classname),
line)
if explicit_constructor_match:
is_marked_explicit = explicit_constructor_match.group(1)
if not explicit_constructor_match.group(2):
constructor_args = []
else:
constructor_args = explicit_constructor_match.group(2).split(',')
# collapse arguments so that commas in template parameter lists and function
# argument parameter lists don't split arguments in two
i = 0
while i < len(constructor_args):
constructor_arg = constructor_args[i]
while (constructor_arg.count('<') > constructor_arg.count('>') or
constructor_arg.count('(') > constructor_arg.count(')')):
constructor_arg += ',' + constructor_args[i + 1]
del constructor_args[i + 1]
constructor_args[i] = constructor_arg
i += 1
defaulted_args = [arg for arg in constructor_args if '=' in arg]
noarg_constructor = (not constructor_args or # empty arg list
# 'void' arg specifier
(len(constructor_args) == 1 and
constructor_args[0].strip() == 'void'))
onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
not noarg_constructor) or
# all but at most one arg defaulted
(len(constructor_args) >= 1 and
not noarg_constructor and
len(defaulted_args) >= len(constructor_args) - 1))
initializer_list_constructor = bool(
onearg_constructor and
Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
copy_constructor = bool(
onearg_constructor and
Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
% re.escape(base_classname), constructor_args[0].strip()))
if (not is_marked_explicit and
onearg_constructor and
not initializer_list_constructor and
not copy_constructor):
if defaulted_args:
error(filename, linenum, 'runtime/explicit', 5,
'Constructors callable with one argument '
'should be marked explicit.')
else:
error(filename, linenum, 'runtime/explicit', 5,
'Single-parameter constructors should be marked explicit.')
elif is_marked_explicit and not onearg_constructor:
if noarg_constructor:
error(filename, linenum, 'runtime/explicit', 5,
'Zero-parameter constructors should not be marked explicit.')
def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
"""Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Since function calls often occur inside if/for/while/switch
# expressions - which have their own, more liberal conventions - we
# first see if we should be looking inside such an expression for a
# function call, to which we can apply more strict standards.
fncall = line # if there's no control flow construct, look at whole line
for pattern in (r'\bif\s*\((.*)\)\s*{',
r'\bfor\s*\((.*)\)\s*{',
r'\bwhile\s*\((.*)\)\s*[{;]',
r'\bswitch\s*\((.*)\)\s*{'):
match = Search(pattern, line)
if match:
fncall = match.group(1) # look inside the parens for function calls
break
# Except in if/for/while/switch, there should never be space
# immediately inside parens (eg "f( 3, 4 )"). We make an exception
# for nested parens ( (a+b) + c ). Likewise, there should never be
# a space before a ( when it's a function argument. I assume it's a
# function argument when the char before the whitespace is legal in
# a function name (alnum + _) and we're not starting a macro. Also ignore
# pointers and references to arrays and functions coz they're too tricky:
# we use a very simple way to recognize these:
# " (something)(maybe-something)" or
# " (something)(maybe-something," or
# " (something)[something]"
# Note that we assume the contents of [] to be short enough that
# they'll never need to wrap.
if ( # Ignore control structures.
not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof|elif)\b',
fncall) and
# Ignore pointers/references to functions.
not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
# Ignore pointers/references to arrays.
not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
error(filename, linenum, 'whitespace/parens', 4,
'Extra space after ( in function call')
elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Extra space after (')
if (Search(r'\w\s+\(', fncall) and
not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and
not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
not Search(r'\bcase\s+\(', fncall)):
# TODO(unknown): Space after an operator function seem to be a common
# error, silence those for now by restricting them to highest verbosity.
if Search(r'\boperator_*\b', line):
error(filename, linenum, 'whitespace/parens', 0,
'Extra space before ( in function call')
else:
error(filename, linenum, 'whitespace/parens', 4,
'Extra space before ( in function call')
# If the ) is followed only by a newline or a { + newline, assume it's
# part of a control statement (if/while/etc), and don't complain
if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
# If the closing parenthesis is preceded by only whitespaces,
# try to give a more descriptive error message.
if Search(r'^\s+\)', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Closing ) should be moved to the previous line')
else:
error(filename, linenum, 'whitespace/parens', 2,
'Extra space before )')
def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace()
def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
error):
is_namespace_indent_item = (
len(nesting_state.stack) > 1 and
nesting_state.stack[-1].check_namespace_indentation and
isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
nesting_state.previous_stack_top == nesting_state.stack[-2])
if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
clean_lines.elided, line):
CheckItemIndentationInNamespace(filename, clean_lines.elided,
line, error)
def CheckForFunctionLengths(filename, clean_lines, linenum,
function_state, error):
"""Reports for long function bodies.
For an overview why this is done, see:
https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
Uses a simplistic algorithm assuming other style guidelines
(especially spacing) are followed.
Only checks unindented functions, so class members are unchecked.
Trivial bodies are unchecked, so constructors with huge initializer lists
may be missed.
Blank/comment lines are not counted so as to avoid encouraging the removal
of vertical space and comments just to get through a lint check.
NOLINT *on the last line of a function* disables this check.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
function_state: Current function name and lines in body so far.
error: The function to call with any errors found.
"""
lines = clean_lines.lines
line = lines[linenum]
joined_line = ''
starting_func = False
regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
match_result = Match(regexp, line)
if match_result:
# If the name is all caps and underscores, figure it's a macro and
# ignore it, unless it's TEST or TEST_F.
function_name = match_result.group(1).split()[-1]
if function_name == 'TEST' or function_name == 'TEST_F' or (
not Match(r'[A-Z_]+$', function_name)):
starting_func = True
if starting_func:
body_found = False
for start_linenum in range(linenum, clean_lines.NumLines()):
start_line = lines[start_linenum]
joined_line += ' ' + start_line.lstrip()
if Search(r'(;|})', start_line): # Declarations and trivial functions
body_found = True
break # ... ignore
elif Search(r'{', start_line):
body_found = True
function = Search(r'((\w|:)*)\(', line).group(1)
if Match(r'TEST', function): # Handle TEST... macros
parameter_regexp = Search(r'(\(.*\))', joined_line)
if parameter_regexp: # Ignore bad syntax
function += parameter_regexp.group(1)
else:
function += '()'
function_state.Begin(function)
break
if not body_found:
# No body for the function (or evidence of a non-function) was found.
error(filename, linenum, 'readability/fn_size', 5,
'Lint failed to find start of function body.')
elif Match(r'^\}\s*$', line): # function end
function_state.Check(error, filename, linenum)
function_state.End()
elif not Match(r'^\s*$', line):
function_state.Count() # Count non-blank/non-comment lines.
_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
def CheckComment(line, filename, linenum, next_line_start, error):
"""Checks for common mistakes in comments.
Args:
line: The line in question.
filename: The name of the current file.
linenum: The number of the line to check.
next_line_start: The first non-whitespace column of the next line.
error: The function to call with any errors found.
"""
commentpos = line.find('//')
if commentpos != -1:
# Check if the // may be in quotes. If so, ignore it
if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
# Allow one space for new scopes, two spaces otherwise:
if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
((commentpos >= 1 and
line[commentpos-1] not in string.whitespace) or
(commentpos >= 2 and
line[commentpos-2] not in string.whitespace))):
error(filename, linenum, 'whitespace/comments', 2,
'At least two spaces is best between code and comments')
# Checks for common mistakes in TODO comments.
comment = line[commentpos:]
match = _RE_PATTERN_TODO.match(comment)
if match:
# One whitespace is correct; zero whitespace is handled elsewhere.
leading_whitespace = match.group(1)
if len(leading_whitespace) > 1:
error(filename, linenum, 'whitespace/todo', 2,
'Too many spaces before TODO')
username = match.group(2)
if not username:
error(filename, linenum, 'readability/todo', 2,
'Missing username in TODO; it should look like '
'"// TODO(my_username): Stuff."')
middle_whitespace = match.group(3)
# Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
if middle_whitespace != ' ' and middle_whitespace != '':
error(filename, linenum, 'whitespace/todo', 2,
'TODO(my_username) should be followed by a space')
# If the comment contains an alphanumeric character, there
# should be a space somewhere between it and the // unless
# it's a /// or //! Doxygen comment.
if (Match(r'//[^ ]*\w', comment) and
not Match(r'(///|//\!)(\s+|$)', comment)):
error(filename, linenum, 'whitespace/comments', 4,
'Should have a space between // and comment')
def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
"""Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw = clean_lines.lines_without_raw_strings
line = raw[linenum]
# Before nixing comments, check if the line is blank for no good
# reason. This includes the first line after a block is opened, and
# blank lines at the end of a function (ie, right before a line like '}'
#
# Skip all the blank line checks if we are immediately inside a
# namespace body. In other words, don't issue blank line warnings
# for this block:
# namespace {
#
# }
#
# A warning about missing end of namespace comments will be issued instead.
#
# Also skip blank line checks for 'extern "C"' blocks, which are formatted
# like namespaces.
if (IsBlankLine(line) and
not nesting_state.InNamespaceBody() and
not nesting_state.InExternC()):
elided = clean_lines.elided
prev_line = elided[linenum - 1]
prevbrace = prev_line.rfind('{')
# TODO(unknown): Don't complain if line before blank line, and line after,
# both start with alnums and are indented the same amount.
# This ignores whitespace at the start of a namespace block
# because those are not usually indented.
if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
# OK, we have a blank line at the start of a code block. Before we
# complain, we check if it is an exception to the rule: The previous
# non-empty line has the parameters of a function header that are indented
# 4 spaces (because they did not fit in a 80 column line when placed on
# the same line as the function name). We also check for the case where
# the previous line is indented 6 spaces, which may happen when the
# initializers of a constructor do not fit into a 80 column line.
exception = False
if Match(r' {6}\w', prev_line): # Initializer list?
# We are looking for the opening column of initializer list, which
# should be indented 4 spaces to cause 6 space indentation afterwards.
search_position = linenum-2
while (search_position >= 0
and Match(r' {6}\w', elided[search_position])):
search_position -= 1
exception = (search_position >= 0
and elided[search_position][:5] == ' :')
else:
# Search for the function arguments or an initializer list. We use a
# simple heuristic here: If the line is indented 4 spaces; and we have a
# closing paren, without the opening paren, followed by an opening brace
# or colon (for initializer lists) we assume that it is the last line of
# a function header. If we have a colon indented 4 spaces, it is an
# initializer list.
exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
prev_line)
or Match(r' {4}:', prev_line))
if not exception:
error(filename, linenum, 'whitespace/blank_line', 2,
'Redundant blank line at the start of a code block '
'should be deleted.')
# Ignore blank lines at the end of a block in a long if-else
# chain, like this:
# if (condition1) {
# // Something followed by a blank line
#
# } else if (condition2) {
# // Something else
# }
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
if (next_line
and Match(r'\s*}', next_line)
and next_line.find('} else ') == -1):
error(filename, linenum, 'whitespace/blank_line', 3,
'Redundant blank line at the end of a code block '
'should be deleted.')
matched = Match(r'\s*(public|protected|private):', prev_line)
if matched:
error(filename, linenum, 'whitespace/blank_line', 3,
'Do not leave a blank line after "%s:"' % matched.group(1))
# Next, check comments
next_line_start = 0
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
next_line_start = len(next_line) - len(next_line.lstrip())
CheckComment(line, filename, linenum, next_line_start, error)
# get rid of comments and strings
line = clean_lines.elided[linenum]
# You shouldn't have spaces before your brackets, except maybe after
# 'delete []' or 'return []() {};'
if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return|auto)\s+\[', line):
error(filename, linenum, 'whitespace/braces', 5,
'Extra space before [')
# In range-based for, we wanted spaces before and after the colon, but
# not around "::" tokens that might appear.
if (Search(r'for *\(.*[^:]:[^: ]', line) or
Search(r'for *\(.*[^: ]:[^:]', line)):
error(filename, linenum, 'whitespace/forcolon', 2,
'Missing space around colon in range-based for loop')
def CheckOperatorSpacing(filename, clean_lines, linenum, error):
"""Checks for horizontal spacing around operators.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Don't try to do spacing checks for operator methods. Do this by
# replacing the troublesome characters with something else,
# preserving column position for all other characters.
#
# The replacement is done repeatedly to avoid false positives from
# operators that call operators.
while True:
match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
if match:
line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
else:
break
# We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
# Otherwise not. Note we only check for non-spaces on *both* sides;
# sometimes people put non-spaces on one side when aligning ='s among
# many lines (not that this is behavior that I approve of...)
if ((Search(r'[\w.]=', line) or
Search(r'=[\w.]', line))
and not Search(r'\b(if|while|for) ', line)
# Operators taken from [lex.operators] in C++11 standard.
and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
and not Search(r'operator=', line)):
error(filename, linenum, 'whitespace/operators', 4,
'Missing spaces around =')
# It's ok not to have spaces around binary operators like + - * /, but if
# there's too little whitespace, we get concerned. It's hard to tell,
# though, so we punt on this one for now. TODO.
# You should always have whitespace around binary operators.
#
# Check <= and >= first to avoid false positives with < and >, then
# check non-include lines for spacing around < and >.
#
# If the operator is followed by a comma, assume it's be used in a
# macro context and don't do any checks. This avoids false
# positives.
#
# Note that && is not included here. This is because there are too
# many false positives due to RValue references.
match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around %s' % match.group(1))
elif not Match(r'#.*include', line):
# Look for < that is not surrounded by spaces. This is only
# triggered if both sides are missing spaces, even though
# technically should should flag if at least one side is missing a
# space. This is done to avoid some false positives with shifts.
match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
if match:
(_, _, end_pos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
if end_pos <= -1:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <')
# Look for > that is not surrounded by spaces. Similar to the
# above, we only trigger if both sides are missing spaces to avoid
# false positives with shifts.
match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
if match:
(_, _, start_pos) = ReverseCloseExpression(
clean_lines, linenum, len(match.group(1)))
if start_pos <= -1:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >')
# We allow no-spaces around << when used like this: 10<<20, but
# not otherwise (particularly, not when used as streams)
#
# We also allow operators following an opening parenthesis, since
# those tend to be macros that deal with operators.
match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
not (match.group(1) == 'operator' and match.group(2) == ';')):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <<')
# We allow no-spaces around >> for almost anything. This is because
# C++11 allows ">>" to close nested templates, which accounts for
# most cases when ">>" is not followed by a space.
#
# We still warn on ">>" followed by alpha character, because that is
# likely due to ">>" being used for right shifts, e.g.:
# value >> alpha
#
# When ">>" is used to close templates, the alphanumeric letter that
# follows would be part of an identifier, and there should still be
# a space separating the template type and the identifier.
# type<type<type>> alpha
match = Search(r'>>[a-zA-Z_]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >>')
# There shouldn't be space around unary operators
match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
if match:
error(filename, linenum, 'whitespace/operators', 4,
'Extra space for operator %s' % match.group(1))
def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
"""Checks for horizontal spacing around parentheses.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# No spaces after an if, while, switch, or for
match = Search(r' (if\(|for\(|while\(|switch\()', line)
if match:
error(filename, linenum, 'whitespace/parens', 5,
'Missing space before ( in %s' % match.group(1))
# For if/for/while/switch, the left and right parens should be
# consistent about how many spaces are inside the parens, and
# there should either be zero or one spaces inside the parens.
# We don't want: "if ( foo)" or "if ( foo )".
# Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
match = Search(r'\b(if|for|while|switch)\s*'
r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
line)
if match:
if len(match.group(2)) != len(match.group(4)):
if not (match.group(3) == ';' and
len(match.group(2)) == 1 + len(match.group(4)) or
not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
error(filename, linenum, 'whitespace/parens', 5,
'Mismatching spaces inside () in %s' % match.group(1))
if len(match.group(2)) not in [0, 1]:
error(filename, linenum, 'whitespace/parens', 5,
'Should have zero or one spaces inside ( and ) in %s' %
match.group(1))
def CheckCommaSpacing(filename, clean_lines, linenum, error):
"""Checks for horizontal spacing near commas and semicolons.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
raw = clean_lines.lines_without_raw_strings
line = clean_lines.elided[linenum]
# You should always have a space after a comma (either as fn arg or operator)
#
# This does not apply when the non-space character following the
# comma is another comma, since the only time when that happens is
# for empty macro arguments.
#
# We run this check in two passes: first pass on elided lines to
# verify that lines contain missing whitespaces, second pass on raw
# lines to confirm that those missing whitespaces are not due to
# elided comments.
if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
Search(r',[^,\s]', raw[linenum])):
error(filename, linenum, 'whitespace/comma', 3,
'Missing space after ,')
# You should always have a space after a semicolon
# except for few corner cases
# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
# space after ;
if Search(r';[^\s};\\)/]', line):
error(filename, linenum, 'whitespace/semicolon', 3,
'Missing space after ;')
def _IsType(clean_lines, nesting_state, expr):
"""Check if expression looks like a type name, returns true if so.
Args:
clean_lines: A CleansedLines instance containing the file.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
expr: The expression to check.
Returns:
True, if token looks like a type.
"""
# Keep only the last token in the expression
last_word = Match(r'^.*(\b\S+)$', expr)
if last_word:
token = last_word.group(1)
else:
token = expr
# Match native types and stdint types
if _TYPES.match(token):
return True
# Try a bit harder to match templated types. Walk up the nesting
# stack until we find something that resembles a typename
# declaration for what we are looking for.
typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
r'\b')
block_index = len(nesting_state.stack) - 1
while block_index >= 0:
if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
return False
# Found where the opening brace is. We want to scan from this
# line up to the beginning of the function, minus a few lines.
# template <typename Type1, // stop scanning here
# ...>
# class C
# : public ... { // start scanning here
last_line = nesting_state.stack[block_index].starting_linenum
next_block_start = 0
if block_index > 0:
next_block_start = nesting_state.stack[block_index - 1].starting_linenum
first_line = last_line
while first_line >= next_block_start:
if clean_lines.elided[first_line].find('template') >= 0:
break
first_line -= 1
if first_line < next_block_start:
# Didn't find any "template" keyword before reaching the next block,
# there are probably no template things to check for this block
block_index -= 1
continue
# Look for typename in the specified range
for i in range(first_line, last_line + 1, 1):
if Search(typename_pattern, clean_lines.elided[i]):
return True
block_index -= 1
return False
def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
"""Checks for horizontal spacing near commas.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Except after an opening paren, or after another opening brace (in case of
# an initializer list, for instance), you should have spaces before your
# braces when they are delimiting blocks, classes, namespaces etc.
# And since you should never have braces at the beginning of a line,
# this is an easy test. Except that braces used for initialization don't
# follow the same rule; we often don't want spaces before those.
match = Match(r'^(.*[^ ({>]){', line)
if match:
# Try a bit harder to check for brace initialization. This
# happens in one of the following forms:
# Constructor() : initializer_list_{} { ... }
# Constructor{}.MemberFunction()
# Type variable{};
# FunctionCall(type{}, ...);
# LastArgument(..., type{});
# LOG(INFO) << type{} << " ...";
# map_of_type[{...}] = ...;
# ternary = expr ? new type{} : nullptr;
# OuterTemplate<InnerTemplateConstructor<Type>{}>
#
# We check for the character following the closing brace, and
# silence the warning if it's one of those listed above, i.e.
# "{.;,)<>]:".
#
# To account for nested initializer list, we allow any number of
# closing braces up to "{;,)<". We can't simply silence the
# warning on first sight of closing brace, because that would
# cause false negatives for things that are not initializer lists.
# Silence this: But not this:
# Outer{ if (...) {
# Inner{...} if (...){ // Missing space before {
# }; }
#
# There is a false negative with this approach if people inserted
# spurious semicolons, e.g. "if (cond){};", but we will catch the
# spurious semicolon with a separate check.
leading_text = match.group(1)
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
trailing_text = ''
if endpos > -1:
trailing_text = endline[endpos:]
for offset in range(endlinenum + 1,
min(endlinenum + 3, clean_lines.NumLines() - 1)):
trailing_text += clean_lines.elided[offset]
# We also suppress warnings for `uint64_t{expression}` etc., as the style
# guide recommends brace initialization for integral types to avoid
# overflow/truncation.
if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
and not _IsType(clean_lines, nesting_state, leading_text)):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before {')
# Make sure '} else {' has spaces.
if Search(r'}else', line):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before else')
# You shouldn't have a space before a semicolon at the end of the line.
# There's a special case for "for" since the style guide allows space before
# the semicolon there.
if Search(r':\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Semicolon defining empty statement. Use {} instead.')
elif Search(r'^\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Line contains only semicolon. If this should be an empty statement, '
'use {} instead.')
elif (Search(r'\s+;\s*$', line) and
not Search(r'\bfor\b', line)):
error(filename, linenum, 'whitespace/semicolon', 5,
'Extra space before last semicolon. If this should be an empty '
'statement, use {} instead.')
def IsDecltype(clean_lines, linenum, column):
"""Check if the token ending on (linenum, column) is decltype().
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: the number of the line to check.
column: end column of the token to check.
Returns:
True if this token is decltype() expression, False otherwise.
"""
(text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
if start_col < 0:
return False
if Search(r'\bdecltype\s*$', text[0:start_col]):
return True
return False
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
"""Checks for additional blank line issues related to sections.
Currently the only thing checked here is blank line before protected/private.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
class_info: A _ClassInfo objects.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Skip checks if the class is small, where small means 25 lines or less.
# 25 lines seems like a good cutoff since that's the usual height of
# terminals, and any class that can't fit in one screen can't really
# be considered "small".
#
# Also skip checks if we are on the first line. This accounts for
# classes that look like
# class Foo { public: ... };
#
# If we didn't find the end of the class, last_line would be zero,
# and the check will be skipped by the first condition.
if (class_info.last_line - class_info.starting_linenum <= 24 or
linenum <= class_info.starting_linenum):
return
matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
if matched:
# Issue warning if the line before public/protected/private was
# not a blank line, but don't do this if the previous line contains
# "class" or "struct". This can happen two ways:
# - We are at the beginning of the class.
# - We are forward-declaring an inner class that is semantically
# private, but needed to be public for implementation reasons.
# Also ignores cases where the previous line ends with a backslash as can be
# common when defining classes in C macros.
prev_line = clean_lines.lines[linenum - 1]
if (not IsBlankLine(prev_line) and
not Search(r'\b(class|struct)\b', prev_line) and
not Search(r'\\$', prev_line)):
# Try a bit harder to find the beginning of the class. This is to
# account for multi-line base-specifier lists, e.g.:
# class Derived
# : public Base {
end_class_head = class_info.starting_linenum
for i in range(class_info.starting_linenum, linenum):
if Search(r'\{\s*$', clean_lines.lines[i]):
end_class_head = i
break
if end_class_head < linenum - 1:
error(filename, linenum, 'whitespace/blank_line', 3,
'"%s:" should be preceded by a blank line' % matched.group(1))
def GetPreviousNonBlankLine(clean_lines, linenum):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line.
"""
prevlinenum = linenum - 1
while prevlinenum >= 0:
prevline = clean_lines.elided[prevlinenum]
if not IsBlankLine(prevline): # if not a blank line...
return (prevline, prevlinenum)
prevlinenum -= 1
return ('', -1)
def CheckBraces(filename, clean_lines, linenum, error):
"""Looks for misplaced braces (e.g. at the end of line).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum] # get rid of comments and strings
if Match(r'\s*{\s*$', line):
# We allow an open brace to start a line in the case where someone is using
# braces in a block to explicitly create a new scope, which is commonly used
# to control the lifetime of stack-allocated variables. Braces are also
# used for brace initializers inside function calls. We don't detect this
# perfectly: we just don't complain if the last non-whitespace character on
# the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
# previous line starts a preprocessor block. We also allow a brace on the
# following line if it is part of an array initialization and would not fit
# within the 80 character limit of the preceding line.
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if (not Search(r'[,;:}{(]\s*$', prevline) and
not Match(r'\s*#', prevline) and
not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
error(filename, linenum, 'whitespace/braces', 4,
'{ should almost always be at the end of the previous line')
# An else clause should be on the same line as the preceding closing brace.
if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if Match(r'\s*}\s*$', prevline):
error(filename, linenum, 'whitespace/newline', 4,
'An else should appear on the same line as the preceding }')
# If braces come on one side of an else, they should be on both.
# However, we have to worry about "else if" that spans multiple lines!
if Search(r'else if\s*\(', line): # could be multi-line if
brace_on_left = bool(Search(r'}\s*else if\s*\(', line))
# find the ( after the if
pos = line.find('else if')
pos = line.find('(', pos)
if pos > 0:
(endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
brace_on_right = endline[endpos:].find('{') != -1
if brace_on_left != brace_on_right: # must be brace after if
error(filename, linenum, 'readability/braces', 5,
'If an else has a brace on one side, it should have it on both')
elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
error(filename, linenum, 'readability/braces', 5,
'If an else has a brace on one side, it should have it on both')
# Likewise, an else should never have the else clause on the same line
if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
error(filename, linenum, 'whitespace/newline', 4,
'Else clause should never be on same line as else (use 2 lines)')
# In the same way, a do/while should never be on one line
if Match(r'\s*do [^\s{]', line):
error(filename, linenum, 'whitespace/newline', 4,
'do/while clauses should not be on a single line')
# Check single-line if/else bodies. The style guide says 'curly braces are not
# required for single-line statements'. We additionally allow multi-line,
# single statements, but we reject anything with more than one semicolon in
# it. This means that the first semicolon after the if should be at the end of
# its line, and the line after that should have an indent level equal to or
# lower than the if. We also check for ambiguous if/else nesting without
# braces.
if_else_match = Search(r'\b(if\s*\(|else\b)', line)
if if_else_match and not Match(r'\s*#', line):
if_indent = GetIndentLevel(line)
endline, endlinenum, endpos = line, linenum, if_else_match.end()
if_match = Search(r'\bif\s*\(', line)
if if_match:
# This could be a multiline if condition, so find the end first.
pos = if_match.end() - 1
(endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
# Check for an opening brace, either directly after the if or on the next
# line. If found, this isn't a single-statement conditional.
if (not Match(r'\s*{', endline[endpos:])
and not (Match(r'\s*$', endline[endpos:])
and endlinenum < (len(clean_lines.elided) - 1)
and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
while (endlinenum < len(clean_lines.elided)
and ';' not in clean_lines.elided[endlinenum][endpos:]):
endlinenum += 1
endpos = 0
if endlinenum < len(clean_lines.elided):
endline = clean_lines.elided[endlinenum]
# We allow a mix of whitespace and closing braces (e.g. for one-liner
# methods) and a single \ after the semicolon (for macros)
endpos = endline.find(';')
if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
# Semicolon isn't the last character, there's something trailing.
# Output a warning if the semicolon is not contained inside
# a lambda expression.
if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
endline):
error(filename, linenum, 'readability/braces', 4,
'If/else bodies with multiple statements require braces')
elif endlinenum < len(clean_lines.elided) - 1:
# Make sure the next line is dedented
next_line = clean_lines.elided[endlinenum + 1]
next_indent = GetIndentLevel(next_line)
# With ambiguous nested if statements, this will error out on the
# if that *doesn't* match the else, regardless of whether it's the
# inner one or outer one.
if (if_match and Match(r'\s*else\b', next_line)
and next_indent != if_indent):
error(filename, linenum, 'readability/braces', 4,
'Else clause should be indented at the same level as if. '
'Ambiguous nested if/else chains require braces.')
elif next_indent > if_indent:
error(filename, linenum, 'readability/braces', 4,
'If/else bodies with multiple statements require braces')
def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
"""Looks for redundant trailing semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Block bodies should not be followed by a semicolon. Due to C++11
# brace initialization, there are more places where semicolons are
# required than not, so we use a whitelist approach to check these
# rather than a blacklist. These are the places where "};" should
# be replaced by just "}":
# 1. Some flavor of block following closing parenthesis:
# for (;;) {};
# while (...) {};
# switch (...) {};
# Function(...) {};
# if (...) {};
# if (...) else if (...) {};
#
# 2. else block:
# if (...) else {};
#
# 3. const member function:
# Function(...) const {};
#
# 4. Block following some statement:
# x = 42;
# {};
#
# 5. Block at the beginning of a function:
# Function(...) {
# {};
# }
#
# Note that naively checking for the preceding "{" will also match
# braces inside multi-dimensional arrays, but this is fine since
# that expression will not contain semicolons.
#
# 6. Block following another block:
# while (true) {}
# {};
#
# 7. End of namespaces:
# namespace {};
#
# These semicolons seems far more common than other kinds of
# redundant semicolons, possibly due to people converting classes
# to namespaces. For now we do not warn for this case.
#
# Try matching case 1 first.
match = Match(r'^(.*\)\s*)\{', line)
if match:
# Matched closing parenthesis (case 1). Check the token before the
# matching opening parenthesis, and don't warn if it looks like a
# macro. This avoids these false positives:
# - macro that defines a base class
# - multi-line macro that defines a base class
# - macro that defines the whole class-head
#
# But we still issue warnings for macros that we know are safe to
# warn, specifically:
# - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
# - TYPED_TEST
# - INTERFACE_DEF
# - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
#
# We implement a whitelist of safe macros instead of a blacklist of
# unsafe macros, even though the latter appears less frequently in
# google code and would have been easier to implement. This is because
# the downside for getting the whitelist wrong means some extra
# semicolons, while the downside for getting the blacklist wrong
# would result in compile errors.
#
# In addition to macros, we also don't want to warn on
# - Compound literals
# - Lambdas
# - alignas specifier with anonymous structs
# - decltype
closing_brace_pos = match.group(1).rfind(')')
opening_parenthesis = ReverseCloseExpression(
clean_lines, linenum, closing_brace_pos)
if opening_parenthesis[2] > -1:
line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
func = Match(r'^(.*\])\s*$', line_prefix)
if ((macro and
macro.group(1) not in (
'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
(func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
Search(r'\bdecltype$', line_prefix) or
Search(r'\s+=\s*$', line_prefix)):
match = None
if (match and
opening_parenthesis[1] > 1 and
Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
# Multi-line lambda-expression
match = None
else:
# Try matching cases 2-3.
match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
if not match:
# Try matching cases 4-6. These are always matched on separate lines.
#
# Note that we can't simply concatenate the previous line to the
# current line and do a single match, otherwise we may output
# duplicate warnings for the blank line case:
# if (cond) {
# // blank line
# }
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if prevline and Search(r'[;{}]\s*$', prevline):
match = Match(r'^(\s*)\{', line)
# Check matching closing brace
if match:
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
# Current {} pair is eligible for semicolon check, and we have found
# the redundant semicolon, output warning here.
#
# Note: because we are scanning forward for opening braces, and
# outputting warnings for the matching closing brace, if there are
# nested blocks with trailing semicolons, we will get the error
# messages in reversed order.
# We need to check the line forward for NOLINT
raw_lines = clean_lines.raw_lines
ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,
error)
ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum,
error)
error(filename, endlinenum, 'readability/braces', 4,
"You don't need a ; after a }")
def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
"""Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Search for loop keywords at the beginning of the line. Because only
# whitespaces are allowed before the keywords, this will also ignore most
# do-while-loops, since those lines should start with closing brace.
#
# We also check "if" blocks here, since an empty conditional block
# is likely an error.
line = clean_lines.elided[linenum]
matched = Match(r'\s*(for|while|if)\s*\(', line)
if matched:
# Find the end of the conditional expression.
(end_line, end_linenum, end_pos) = CloseExpression(
clean_lines, linenum, line.find('('))
# Output warning if what follows the condition expression is a semicolon.
# No warning for all other cases, including whitespace or newline, since we
# have a separate check for semicolons preceded by whitespace.
if end_pos >= 0 and Match(r';', end_line[end_pos:]):
if matched.group(1) == 'if':
error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
'Empty conditional bodies should use {}')
else:
error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
'Empty loop bodies should use {} or continue')
# Check for if statements that have completely empty bodies (no comments)
# and no else clauses.
if end_pos >= 0 and matched.group(1) == 'if':
# Find the position of the opening { for the if statement.
# Return without logging an error if it has no brackets.
opening_linenum = end_linenum
opening_line_fragment = end_line[end_pos:]
# Loop until EOF or find anything that's not whitespace or opening {.
while not Search(r'^\s*\{', opening_line_fragment):
if Search(r'^(?!\s*$)', opening_line_fragment):
# Conditional has no brackets.
return
opening_linenum += 1
if opening_linenum == len(clean_lines.elided):
# Couldn't find conditional's opening { or any code before EOF.
return
opening_line_fragment = clean_lines.elided[opening_linenum]
# Set opening_line (opening_line_fragment may not be entire opening line).
opening_line = clean_lines.elided[opening_linenum]
# Find the position of the closing }.
opening_pos = opening_line_fragment.find('{')
if opening_linenum == end_linenum:
# We need to make opening_pos relative to the start of the entire line.
opening_pos += end_pos
(closing_line, closing_linenum, closing_pos) = CloseExpression(
clean_lines, opening_linenum, opening_pos)
if closing_pos < 0:
return
# Now construct the body of the conditional. This consists of the portion
# of the opening line after the {, all lines until the closing line,
# and the portion of the closing line before the }.
if (clean_lines.raw_lines[opening_linenum] !=
CleanseComments(clean_lines.raw_lines[opening_linenum])):
# Opening line ends with a comment, so conditional isn't empty.
return
if closing_linenum > opening_linenum:
# Opening line after the {. Ignore comments here since we checked above.
body = list(opening_line[opening_pos+1:])
# All lines until closing line, excluding closing line, with comments.
body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
# Closing line before the }. Won't (and can't) have comments.
body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
body = '\n'.join(body)
else:
# If statement has brackets and fits on a single line.
body = opening_line[opening_pos+1:closing_pos-1]
# Check if the body is empty
if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
return
# The body is empty. Now make sure there's not an else clause.
current_linenum = closing_linenum
current_line_fragment = closing_line[closing_pos:]
# Loop until EOF or find anything that's not whitespace or else clause.
while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
if Search(r'^(?=\s*else)', current_line_fragment):
# Found an else clause, so don't log an error.
return
current_linenum += 1
if current_linenum == len(clean_lines.elided):
break
current_line_fragment = clean_lines.elided[current_linenum]
# The body is empty and there's no else clause until EOF or other code.
error(filename, end_linenum, 'whitespace/empty_if_body', 4,
('If statement had no body and no else clause'))
def FindCheckMacro(line):
"""Find a replaceable CHECK-like macro.
Args:
line: line to search on.
Returns:
(macro name, start position), or (None, -1) if no replaceable
macro is found.
"""
for macro in _CHECK_MACROS:
i = line.find(macro)
if i >= 0:
# Find opening parenthesis. Do a regular expression match here
# to make sure that we are matching the expected CHECK macro, as
# opposed to some other macro that happens to contain the CHECK
# substring.
matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
if not matched:
continue
return (macro, len(matched.group(1)))
return (None, -1)
def CheckCheck(filename, clean_lines, linenum, error):
"""Checks the use of CHECK and EXPECT macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Decide the set of replacement macros that should be suggested
lines = clean_lines.elided
(check_macro, start_pos) = FindCheckMacro(lines[linenum])
if not check_macro:
return
# Find end of the boolean expression by matching parentheses
(last_line, end_line, end_pos) = CloseExpression(
clean_lines, linenum, start_pos)
if end_pos < 0:
return
# If the check macro is followed by something other than a
# semicolon, assume users will log their own custom error messages
# and don't suggest any replacements.
if not Match(r'\s*;', last_line[end_pos:]):
return
if linenum == end_line:
expression = lines[linenum][start_pos + 1:end_pos - 1]
else:
expression = lines[linenum][start_pos + 1:]
for i in range(linenum + 1, end_line):
expression += lines[i]
expression += last_line[0:end_pos - 1]
# Parse expression so that we can take parentheses into account.
# This avoids false positives for inputs like "CHECK((a < 4) == b)",
# which is not replaceable by CHECK_LE.
lhs = ''
rhs = ''
operator = None
while expression:
matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
r'==|!=|>=|>|<=|<|\()(.*)$', expression)
if matched:
token = matched.group(1)
if token == '(':
# Parenthesized operand
expression = matched.group(2)
(end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
if end < 0:
return # Unmatched parenthesis
lhs += '(' + expression[0:end]
expression = expression[end:]
elif token in ('&&', '||'):
# Logical and/or operators. This means the expression
# contains more than one term, for example:
# CHECK(42 < a && a < b);
#
# These are not replaceable with CHECK_LE, so bail out early.
return
elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
# Non-relational operator
lhs += token
expression = matched.group(2)
else:
# Relational operator
operator = token
rhs = matched.group(2)
break
else:
# Unparenthesized operand. Instead of appending to lhs one character
# at a time, we do another regular expression match to consume several
# characters at once if possible. Trivial benchmark shows that this
# is more efficient when the operands are longer than a single
# character, which is generally the case.
matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
if not matched:
matched = Match(r'^(\s*\S)(.*)$', expression)
if not matched:
break
lhs += matched.group(1)
expression = matched.group(2)
# Only apply checks if we got all parts of the boolean expression
if not (lhs and operator and rhs):
return
# Check that rhs do not contain logical operators. We already know
# that lhs is fine since the loop above parses out && and ||.
if rhs.find('&&') > -1 or rhs.find('||') > -1:
return
# At least one of the operands must be a constant literal. This is
# to avoid suggesting replacements for unprintable things like
# CHECK(variable != iterator)
#
# The following pattern matches decimal, hex integers, strings, and
# characters (in that order).
lhs = lhs.strip()
rhs = rhs.strip()
match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
if Match(match_constant, lhs) or Match(match_constant, rhs):
# Note: since we know both lhs and rhs, we can provide a more
# descriptive error message like:
# Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
# Instead of:
# Consider using CHECK_EQ instead of CHECK(a == b)
#
# We are still keeping the less descriptive message because if lhs
# or rhs gets long, the error message might become unreadable.
error(filename, linenum, 'readability/check', 2,
'Consider using %s instead of %s(a %s b)' % (
_CHECK_REPLACEMENT[check_macro][operator],
check_macro, operator))
def CheckAltTokens(filename, clean_lines, linenum, error):
"""Check alternative keywords being used in boolean expressions.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Avoid preprocessor lines
if Match(r'^\s*#', line):
return
# Last ditch effort to avoid multi-line comments. This will not help
# if the comment started before the current line or ended after the
# current line, but it catches most of the false positives. At least,
# it provides a way to workaround this warning for people who use
# multi-line comments in preprocessor macros.
#
# TODO(unknown): remove this once cpplint has better support for
# multi-line comments.
if line.find('/*') >= 0 or line.find('*/') >= 0:
return
for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
error(filename, linenum, 'readability/alt_tokens', 2,
'Use operator %s instead of %s' % (
_ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
def GetLineWidth(line):
"""Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters.
"""
if python2_version and isinstance(line, unicode):
width = 0
for uc in unicodedata.normalize('NFC', line):
if unicodedata.east_asian_width(uc) in ('W', 'F'):
width += 2
elif not unicodedata.combining(uc):
width += 1
return width
else:
return len(line)
def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
error):
"""Checks rules from the 'C++ style rules' section of cppguide.html.
Most of these rules are hard to test (naming, comment style), but we
do what we can. In particular we check for 2-space indents, line lengths,
tab usage, spaces inside code, etc.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw_lines = clean_lines.lines_without_raw_strings
line = raw_lines[linenum]
prev = raw_lines[linenum - 1] if linenum > 0 else ''
if line.find('\t') != -1:
error(filename, linenum, 'whitespace/tab', 1,
'Tab found; better to use spaces')
# One or three blank spaces at the beginning of the line is weird; it's
# hard to reconcile that with 2-space indents.
# NOTE: here are the conditions rob pike used for his tests. Mine aren't
# as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
# if(RLENGTH > 20) complain = 0;
# if(match($0, " +(error|private|public|protected):")) complain = 0;
# if(match(prev, "&& *$")) complain = 0;
# if(match(prev, "\\|\\| *$")) complain = 0;
# if(match(prev, "[\",=><] *$")) complain = 0;
# if(match($0, " <<")) complain = 0;
# if(match(prev, " +for \\(")) complain = 0;
# if(prevodd && match(prevprev, " +for \\(")) complain = 0;
scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
classinfo = nesting_state.InnermostClass()
initial_spaces = 0
cleansed_line = clean_lines.elided[linenum]
while initial_spaces < len(line) and line[initial_spaces] == ' ':
initial_spaces += 1
# There are certain situations we allow one space, notably for
# section labels, and also lines containing multi-line raw strings.
# We also don't check for lines that look like continuation lines
# (of lines ending in double quotes, commas, equals, or angle brackets)
# because the rules for how to indent those are non-trivial.
if (not Search(r'[",=><] *$', prev) and
(initial_spaces == 1 or initial_spaces == 3) and
not Match(scope_or_label_pattern, cleansed_line) and
not (clean_lines.raw_lines[linenum] != line and
Match(r'^\s*""', line))):
error(filename, linenum, 'whitespace/indent', 3,
'Weird number of spaces at line-start. '
'Are you using a 2-space indent?')
if line and line[-1].isspace():
error(filename, linenum, 'whitespace/end_of_line', 4,
'Line ends in whitespace. Consider deleting these extra spaces.')
# Check if the line is a header guard.
is_header_guard = False
if IsHeaderExtension(file_extension):
cppvar = GetHeaderGuardCPPVariable(filename)
if (line.startswith('#ifndef %s' % cppvar) or
line.startswith('#define %s' % cppvar) or
line.startswith('#endif // %s' % cppvar)):
is_header_guard = True
# #include lines and header guards can be long, since there's no clean way to
# split them.
#
# URLs can be long too. It's possible to split these, but it makes them
# harder to cut&paste.
#
# The "$Id:...$" comment may also get very long without it being the
# developers fault.
if (not line.startswith('#include') and not is_header_guard and
not Match(r'^\s*//.*http(s?)://\S*$', line) and
not Match(r'^\s*//\s*[^\s]*$', line) and
not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
line_width = GetLineWidth(line)
if line_width > _line_length:
error(filename, linenum, 'whitespace/line_length', 2,
'Lines should be <= %i characters long' % _line_length)
if (cleansed_line.count(';') > 1 and
# for loops are allowed two ;'s (and may run over two lines).
cleansed_line.find('for') == -1 and
(GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
# It's ok to have many commands in a switch case that fits in 1 line
not ((cleansed_line.find('case ') != -1 or
cleansed_line.find('default:') != -1) and
cleansed_line.find('break;') != -1)):
error(filename, linenum, 'whitespace/newline', 0,
'More than one command on the same line')
# Some more style checks
CheckBraces(filename, clean_lines, linenum, error)
CheckTrailingSemicolon(filename, clean_lines, linenum, error)
CheckEmptyBlockBody(filename, clean_lines, linenum, error)
CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
CheckOperatorSpacing(filename, clean_lines, linenum, error)
CheckParenthesisSpacing(filename, clean_lines, linenum, error)
CheckCommaSpacing(filename, clean_lines, linenum, error)
CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
CheckCheck(filename, clean_lines, linenum, error)
CheckAltTokens(filename, clean_lines, linenum, error)
classinfo = nesting_state.InnermostClass()
if classinfo:
CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
# Matches the first component of a filename delimited by -s and _s. That is:
# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
def _DropCommonSuffixes(filename):
"""Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
'foo/foo_unusualinternal'
Args:
filename: The input filename.
Returns:
The filename with the common suffix removed.
"""
for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
'inl.h', 'impl.h', 'internal.h'):
if (filename.endswith(suffix) and len(filename) > len(suffix) and
filename[-len(suffix) - 1] in ('-', '_')):
return filename[:-len(suffix) - 1]
return os.path.splitext(filename)[0]
def _ClassifyInclude(fileinfo, include, is_system):
"""Figures out what kind of header 'include' is.
Args:
fileinfo: The current file cpplint is running over. A FileInfo instance.
include: The path to a #included file.
is_system: True if the #include used <> rather than "".
Returns:
One of the _XXX_HEADER constants.
For example:
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
_C_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
_CPP_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
_LIKELY_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
... 'bar/foo_other_ext.h', False)
_POSSIBLE_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
_OTHER_HEADER
"""
# This is a list of all standard c++ header files, except
# those already checked for above.
def basename(name):
# os-dependent delimiters are allowed (e.g. backslash '\' in Windows)
name = os.path.split(name)[1]
# C allows slash ('/') as path delimiter on all systems
name = name.split('/')[-1]
return name
is_cpp_h = include in _CPP_HEADERS \
or include.endswith(".hpp") \
or include.endswith(".hxx") \
or include.endswith(".H") \
or include.endswith(".hh") \
or '.' not in basename(include) # no extension
if is_system:
if is_cpp_h:
return _CPP_SYS_HEADER
else:
return _C_SYS_HEADER
# If the target file and the include we're checking share a
# basename when we drop common extensions, and the include
# lives in . , then it's likely to be owned by the target file.
target_dir, target_base = (
os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
if target_base == include_base and (
include_dir == target_dir or
include_dir == os.path.normpath(target_dir + '/../public')):
return _LIKELY_MY_HEADER
# If the target and include share some initial basename
# component, it's possible the target is implementing the
# include, so it's allowed to be first, but we'll never
# complain if it's not there.
target_first_component = _RE_FIRST_COMPONENT.match(target_base)
include_first_component = _RE_FIRST_COMPONENT.match(include_base)
if (target_first_component and include_first_component and
target_first_component.group(0) ==
include_first_component.group(0)):
return _POSSIBLE_MY_HEADER
return _OTHER_HEADER
def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
"""Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found.
"""
fileinfo = FileInfo(filename)
line = clean_lines.lines[linenum]
# "include" should use the new style "foo/bar.h" instead of just "bar.h"
# Only do this check if the included header follows google naming
# conventions. If not, assume that it's a 3rd party API that
# requires special include conventions.
#
# We also make an exception for Lua headers, which follow google
# naming convention but not the include convention.
match = Match(r'#include\s*"([^/]+\.h)"', line)
if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
error(filename, linenum, 'build/include', 4,
'Include the directory when naming .h files')
# we shouldn't include a file more than once. actually, there are a
# handful of instances where doing so is okay, but in general it's
# not.
match = _RE_PATTERN_INCLUDE.search(line)
if match:
include = match.group(2)
is_system = (match.group(1) == '<')
duplicate_line = include_state.FindHeader(include)
if duplicate_line >= 0:
error(filename, linenum, 'build/include', 4,
'"%s" already included at %s:%s' %
(include, filename, duplicate_line))
elif (include.endswith('.cc') and
os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
error(filename, linenum, 'build/include', 4,
'Do not include .cc files from other packages')
elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
include_state.include_list[-1].append((include, linenum))
# We want to ensure that headers appear in the right order:
# 1) for foo.cc, foo.h (preferred location)
# 2) c system files
# 3) cpp system files
# 4) for foo.cc, foo.h (deprecated location)
# 5) other google headers
#
# We classify each include statement as one of those 5 types
# using a number of techniques. The include_state object keeps
# track of the highest type seen, and complains if we see a
# lower type after that.
error_message = include_state.CheckNextIncludeOrder(
_ClassifyInclude(fileinfo, include, is_system))
if error_message:
error(filename, linenum, 'build/include_order', 4,
'%s. Should be: %s.h, c system, c++ system, other.' %
(error_message, fileinfo.BaseName()))
canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
if not include_state.IsInAlphabeticalOrder(
clean_lines, linenum, canonical_include):
error(filename, linenum, 'build/include_alpha', 4,
'Include "%s" not in alphabetical order' % include)
include_state.SetLastHeader(canonical_include)
def _GetTextInside(text, start_pattern):
r"""Retrieves all the text between matching open and close parentheses.
Given a string of lines and a regular expression string, retrieve all the text
following the expression and between opening punctuation symbols like
(, [, or {, and the matching close-punctuation symbol. This properly nested
occurrences of the punctuations, so for the text like
printf(a(), b(c()));
a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
start_pattern must match string having an open punctuation symbol at the end.
Args:
text: The lines to extract text. Its comments and strings must be elided.
It can be single line and can span multiple lines.
start_pattern: The regexp string indicating where to start extracting
the text.
Returns:
The extracted text.
None if either the opening string or ending punctuation could not be found.
"""
# TODO(unknown): Audit cpplint.py to see what places could be profitably
# rewritten to use _GetTextInside (and use inferior regexp matching today).
# Give opening punctuations to get the matching close-punctuations.
matching_punctuation = {'(': ')', '{': '}', '[': ']'}
closing_punctuation = set([value for _, value in matching_punctuation.items()])
# Find the position to start extracting text.
match = re.search(start_pattern, text, re.M)
if not match: # start_pattern not found in text.
return None
start_position = match.end(0)
assert start_position > 0, (
'start_pattern must ends with an opening punctuation.')
assert text[start_position - 1] in matching_punctuation, (
'start_pattern must ends with an opening punctuation.')
# Stack of closing punctuations we expect to have in text after position.
punctuation_stack = [matching_punctuation[text[start_position - 1]]]
position = start_position
while punctuation_stack and position < len(text):
if text[position] == punctuation_stack[-1]:
punctuation_stack.pop()
elif text[position] in closing_punctuation:
# A closing punctuation without matching opening punctuations.
return None
elif text[position] in matching_punctuation:
punctuation_stack.append(matching_punctuation[text[position]])
position += 1
if punctuation_stack:
# Opening punctuations left without matching close-punctuations.
return None
# punctuations match.
return text[start_position:position - 1]
# Patterns for matching call-by-reference parameters.
#
# Supports nested templates up to 2 levels deep using this messy pattern:
# < (?: < (?: < [^<>]*
# >
# | [^<>] )*
# >
# | [^<>] )*
# >
_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
_RE_PATTERN_TYPE = (
r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
r'(?:\w|'
r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
r'::)+')
# A call-by-reference parameter ends with '& identifier'.
_RE_PATTERN_REF_PARAM = re.compile(
r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
# A call-by-const-reference parameter either ends with 'const& identifier'
# or looks like 'const type& identifier' when 'type' is atomic.
_RE_PATTERN_CONST_REF_PARAM = (
r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
# Stream types.
_RE_PATTERN_REF_STREAM_PARAM = (
r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
def CheckLanguage(filename, clean_lines, linenum, file_extension,
include_state, nesting_state, error):
"""Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
include_state: An _IncludeState instance in which the headers are inserted.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# If the line is empty or consists of entirely a comment, no need to
# check it.
line = clean_lines.elided[linenum]
if not line:
return
match = _RE_PATTERN_INCLUDE.search(line)
if match:
CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
return
# Reset include state across preprocessor directives. This is meant
# to silence warnings for conditional includes.
match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
if match:
include_state.ResetSection(match.group(1))
# Make Windows paths like Unix.
fullname = os.path.abspath(filename).replace('\\', '/')
# Perform other checks now that we are sure that this is not an include line
CheckCasts(filename, clean_lines, linenum, error)
CheckGlobalStatic(filename, clean_lines, linenum, error)
CheckPrintf(filename, clean_lines, linenum, error)
if IsHeaderExtension(file_extension):
# TODO(unknown): check that 1-arg constructors are explicit.
# How to tell it's a constructor?
# (handled in CheckForNonStandardConstructs for now)
# TODO(unknown): check that classes declare or disable copy/assign
# (level 1 error)
pass
# Check if people are using the verboten C basic types. The only exception
# we regularly allow is "unsigned short port" for port.
if Search(r'\bshort port\b', line):
if not Search(r'\bunsigned short port\b', line):
error(filename, linenum, 'runtime/int', 4,
'Use "unsigned short" for ports, not "short"')
else:
match = Search(r'\b(short|long(?! +double)|long long)\b', line)
if match:
error(filename, linenum, 'runtime/int', 4,
'Use int16/int64/etc, rather than the C type %s' % match.group(1))
# Check if some verboten operator overloading is going on
# TODO(unknown): catch out-of-line unary operator&:
# class X {};
# int operator&(const X& x) { return 42; } // unary operator&
# The trick is it's hard to tell apart from binary operator&:
# class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
if Search(r'\boperator\s*&\s*\(\s*\)', line):
error(filename, linenum, 'runtime/operator', 4,
'Unary operator& is dangerous. Do not use it.')
# Check for suspicious usage of "if" like
# } if (a == b) {
if Search(r'\}\s*if\s*\(', line):
error(filename, linenum, 'readability/braces', 4,
'Did you mean "else if"? If not, start a new line for "if".')
# Check for potential format string bugs like printf(foo).
# We constrain the pattern not to pick things like DocidForPrintf(foo).
# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
# TODO(unknown): Catch the following case. Need to change the calling
# convention of the whole function to process multiple line to handle it.
# printf(
# boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
if printf_args:
match = Match(r'([\w.\->()]+)$', printf_args)
if match and match.group(1) != '__VA_ARGS__':
function_name = re.search(r'\b((?:string)?printf)\s*\(',
line, re.I).group(1)
error(filename, linenum, 'runtime/printf', 4,
'Potential format string bug. Do %s("%%s", %s) instead.'
% (function_name, match.group(1)))
# Check for potential memset bugs like memset(buf, sizeof(buf), 0).
match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
error(filename, linenum, 'runtime/memset', 4,
'Did you mean "memset(%s, 0, %s)"?'
% (match.group(1), match.group(2)))
if Search(r'\busing namespace\b', line):
error(filename, linenum, 'build/namespaces', 5,
'Do not use namespace using-directives. '
'Use using-declarations instead.')
# Detect variable-length arrays.
match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
match.group(3).find(']') == -1):
# Split the size using space and arithmetic operators as delimiters.
# If any of the resulting tokens are not compile time constants then
# report the error.
tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
is_const = True
skip_next = False
for tok in tokens:
if skip_next:
skip_next = False
continue
if Search(r'sizeof\(.+\)', tok): continue
if Search(r'arraysize\(\w+\)', tok): continue
tok = tok.lstrip('(')
tok = tok.rstrip(')')
if not tok: continue
if Match(r'\d+', tok): continue
if Match(r'0[xX][0-9a-fA-F]+', tok): continue
if Match(r'k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
# A catch all for tricky sizeof cases, including 'sizeof expression',
# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
# requires skipping the next token because we split on ' ' and '*'.
if tok.startswith('sizeof'):
skip_next = True
continue
is_const = False
break
if not is_const:
error(filename, linenum, 'runtime/arrays', 1,
'Do not use variable-length arrays. Use an appropriately named '
"('k' followed by CamelCase) compile-time constant for the size.")
# Check for use of unnamed namespaces in header files. Registration
# macros are typically OK, so we allow use of "namespace {" on lines
# that end with backslashes.
if (IsHeaderExtension(file_extension)
and Search(r'\bnamespace\s*{', line)
and line[-1] != '\\'):
error(filename, linenum, 'build/namespaces', 4,
'Do not use unnamed namespaces in header files. See '
'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
' for more information.')
def CheckGlobalStatic(filename, clean_lines, linenum, error):
"""Check for unsafe global or static objects.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Match two lines at a time to support multiline declarations
if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
line += clean_lines.elided[linenum + 1].strip()
# Check for people declaring static/global STL strings at the top level.
# This is dangerous because the C++ language does not guarantee that
# globals with constructors are initialized before the first access, and
# also because globals can be destroyed when some threads are still running.
# TODO(unknown): Generalize this to also find static unique_ptr instances.
# TODO(unknown): File bugs for clang-tidy to find these.
match = Match(
r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
r'([a-zA-Z0-9_:]+)\b(.*)',
line)
# Remove false positives:
# - String pointers (as opposed to values).
# string *pointer
# const string *pointer
# string const *pointer
# string *const pointer
#
# - Functions and template specializations.
# string Function<Type>(...
# string Class<Type>::Method(...
#
# - Operators. These are matched separately because operator names
# cross non-word boundaries, and trying to match both operators
# and functions at the same time would decrease accuracy of
# matching identifiers.
# string Class::operator*()
if (match and
not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
not Search(r'\boperator\W', line) and
not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
if Search(r'\bconst\b', line):
error(filename, linenum, 'runtime/string', 4,
'For a static/global string constant, use a C style string '
'instead: "%schar%s %s[]".' %
(match.group(1), match.group(2) or '', match.group(3)))
else:
error(filename, linenum, 'runtime/string', 4,
'Static/global string variables are not permitted.')
if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
error(filename, linenum, 'runtime/init', 4,
'You seem to be initializing a member variable with itself.')
def CheckPrintf(filename, clean_lines, linenum, error):
"""Check for printf related issues.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# When snprintf is used, the second argument shouldn't be a literal.
match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
if match and match.group(2) != '0':
# If 2nd arg is zero, snprintf is used to calculate size.
error(filename, linenum, 'runtime/printf', 3,
'If you can, use sizeof(%s) instead of %s as the 2nd arg '
'to snprintf.' % (match.group(1), match.group(2)))
# Check if some verboten C functions are being used.
if Search(r'\bsprintf\s*\(', line):
error(filename, linenum, 'runtime/printf', 5,
'Never use sprintf. Use snprintf instead.')
match = Search(r'\b(strcpy|strcat)\s*\(', line)
if match:
error(filename, linenum, 'runtime/printf', 4,
'Almost always, snprintf is better than %s' % match.group(1))
def IsDerivedFunction(clean_lines, linenum):
"""Check if current line contains an inherited function.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains a function with "override"
virt-specifier.
"""
# Scan back a few lines for start of current function
for i in range(linenum, max(-1, linenum - 10), -1):
match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
if match:
# Look for "override" after the matching closing parenthesis
line, _, closing_paren = CloseExpression(
clean_lines, i, len(match.group(1)))
return (closing_paren >= 0 and
Search(r'\boverride\b', line[closing_paren:]))
return False
def IsOutOfLineMethodDefinition(clean_lines, linenum):
"""Check if current line contains an out-of-line method definition.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains an out-of-line method definition.
"""
# Scan back a few lines for start of current function
for i in range(linenum, max(-1, linenum - 10), -1):
if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
return False
def IsInitializerList(clean_lines, linenum):
"""Check if current line is inside constructor initializer list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line appears to be inside constructor initializer
list, False otherwise.
"""
for i in range(linenum, 1, -1):
line = clean_lines.elided[i]
if i == linenum:
remove_function_body = Match(r'^(.*)\{\s*$', line)
if remove_function_body:
line = remove_function_body.group(1)
if Search(r'\s:\s*\w+[({]', line):
# A lone colon tend to indicate the start of a constructor
# initializer list. It could also be a ternary operator, which
# also tend to appear in constructor initializer lists as
# opposed to parameter lists.
return True
if Search(r'\}\s*,\s*$', line):
# A closing brace followed by a comma is probably the end of a
# brace-initialized member in constructor initializer list.
return True
if Search(r'[{};]\s*$', line):
# Found one of the following:
# - A closing brace or semicolon, probably the end of the previous
# function.
# - An opening brace, probably the start of current class or namespace.
#
# Current line is probably not inside an initializer list since
# we saw one of those things without seeing the starting colon.
return False
# Got to the beginning of the file without seeing the start of
# constructor initializer list.
return False
# This check is disabled for DALI
def CheckForNonConstReference(filename, clean_lines, linenum,
nesting_state, error):
"""Check for non-const references.
Separate from CheckLanguage since it scans backwards from current
line, instead of scanning forward.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Do nothing if there is no '&' on current line.
line = clean_lines.elided[linenum]
if '&' not in line:
return
# If a function is inherited, current function doesn't have much of
# a choice, so any non-const references should not be blamed on
# derived function.
if IsDerivedFunction(clean_lines, linenum):
return
# Don't warn on out-of-line method definitions, as we would warn on the
# in-line declaration, if it isn't marked with 'override'.
if IsOutOfLineMethodDefinition(clean_lines, linenum):
return
# Long type names may be broken across multiple lines, usually in one
# of these forms:
# LongType
# ::LongTypeContinued &identifier
# LongType::
# LongTypeContinued &identifier
# LongType<
# ...>::LongTypeContinued &identifier
#
# If we detected a type split across two lines, join the previous
# line to current line so that we can match const references
# accordingly.
#
# Note that this only scans back one line, since scanning back
# arbitrary number of lines would be expensive. If you have a type
# that spans more than 2 lines, please use a typedef.
if linenum > 1:
previous = None
if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
# previous_line\n + ::current_line
previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
clean_lines.elided[linenum - 1])
elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
# previous_line::\n + current_line
previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
clean_lines.elided[linenum - 1])
if previous:
line = previous.group(1) + line.lstrip()
else:
# Check for templated parameter that is split across multiple lines
endpos = line.rfind('>')
if endpos > -1:
(_, startline, startpos) = ReverseCloseExpression(
clean_lines, linenum, endpos)
if startpos > -1 and startline < linenum:
# Found the matching < on an earlier line, collect all
# pieces up to current line.
line = ''
for i in range(startline, linenum + 1):
line += clean_lines.elided[i].strip()
# Check for non-const references in function parameters. A single '&' may
# found in the following places:
# inside expression: binary & for bitwise AND
# inside expression: unary & for taking the address of something
# inside declarators: reference parameter
# We will exclude the first two cases by checking that we are not inside a
# function body, including one that was just introduced by a trailing '{'.
# TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
if (nesting_state.previous_stack_top and
not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
# Not at toplevel, not within a class, and not within a namespace
return
# Avoid initializer lists. We only need to scan back from the
# current line for something that starts with ':'.
#
# We don't need to check the current line, since the '&' would
# appear inside the second set of parentheses on the current line as
# opposed to the first set.
if linenum > 0:
for i in range(linenum - 1, max(0, linenum - 10), -1):
previous_line = clean_lines.elided[i]
if not Search(r'[),]\s*$', previous_line):
break
if Match(r'^\s*:\s+\S', previous_line):
return
# Avoid preprocessors
if Search(r'\\\s*$', line):
return
# Avoid constructor initializer lists
if IsInitializerList(clean_lines, linenum):
return
# We allow non-const references in a few standard places, like functions
# called "swap()" or iostream operators like "<<" or ">>". Do not check
# those function parameters.
#
# We also accept & in static_assert, which looks like a function but
# it's actually a declaration expression.
whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
r'operator\s*[<>][<>]|'
r'static_assert|COMPILE_ASSERT'
r')\s*\(')
if Search(whitelisted_functions, line):
return
elif not Search(r'\S+\([^)]*$', line):
# Don't see a whitelisted function on this line. Actually we
# didn't see any function name on this line, so this is likely a
# multi-line parameter list. Try a bit harder to catch this case.
for i in range(2):
if (linenum > i and
Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
return
decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
error(filename, linenum, 'runtime/references', 2,
'Is this a non-const reference? '
'If so, make const or use a pointer: ' +
ReplaceAll(' *<', '<', parameter))
def CheckCasts(filename, clean_lines, linenum, error):
"""Various cast related checks.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Check to see if they're using an conversion function cast.
# I just try to capture the most common basic types, though there are more.
# Parameterless conversion functions, such as bool(), are allowed as they are
# probably a member operator declaration or default constructor.
match = Search(
r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
r'(\([^)].*)', line)
expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
if match and not expecting_function:
matched_type = match.group(2)
# matched_new_or_template is used to silence two false positives:
# - New operators
# - Template arguments with function types
#
# For template arguments, we match on types immediately following
# an opening bracket without any spaces. This is a fast way to
# silence the common case where the function type is the first
# template argument. False negative with less-than comparison is
# avoided because those operators are usually followed by a space.
#
# function<double(double)> // bracket + no space = false positive
# value < double(42) // bracket + space = true positive
matched_new_or_template = match.group(1)
# Avoid arrays by looking for brackets that come after the closing
# parenthesis.
if Match(r'\([^()]+\)\s*\[', match.group(3)):
return
# Other things to ignore:
# - Function pointers
# - Casts to pointer types
# - Placement new
# - Alias declarations
matched_funcptr = match.group(3)
if (matched_new_or_template is None and
not (matched_funcptr and
(Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
matched_funcptr) or
matched_funcptr.startswith('(*)'))) and
not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
not Search(r'new\(\S+\)\s*' + matched_type, line)):
error(filename, linenum, 'readability/casting', 4,
'Using deprecated casting style. '
'Use static_cast<%s>(...) instead' %
matched_type)
if not expecting_function:
CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
# This doesn't catch all cases. Consider (const char * const)"hello".
#
# (char *) "foo" should always be a const_cast (reinterpret_cast won't
# compile).
if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
r'\((char\s?\*+\s?)\)\s*"', error):
pass
else:
# Check pointer casts for other than string constants
CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
r'\((\w+\s?\*+\s?)\)', error)
# In addition, we look for people taking the address of a cast. This
# is dangerous -- casts can assign to temporaries, so the pointer doesn't
# point where you think.
#
# Some non-identifier character is required before the '&' for the
# expression to be recognized as a cast. These are casts:
# expression = &static_cast<int*>(temporary());
# function(&(int*)(temporary()));
#
# This is not a cast:
# reference_type&(int* function_param);
match = Search(
r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
if match:
# Try a better error message when the & is bound to something
# dereferenced by the casted pointer, as opposed to the casted
# pointer itself.
parenthesis_error = False
match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
if match:
_, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
_, y2, x2 = CloseExpression(clean_lines, y1, x1)
if x2 >= 0:
extended_line = clean_lines.elided[y2][x2:]
if y2 < clean_lines.NumLines() - 1:
extended_line += clean_lines.elided[y2 + 1]
if Match(r'\s*(?:->|\[)', extended_line):
parenthesis_error = True
if parenthesis_error:
error(filename, linenum, 'readability/casting', 4,
('Are you taking an address of something dereferenced '
'from a cast? Wrapping the dereferenced expression in '
'parentheses will make the binding more obvious'))
else:
error(filename, linenum, 'runtime/casting', 4,
('Are you taking an address of a cast? '
'This is dangerous: could be a temp var. '
'Take the address before doing the cast, rather than after'))
def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
"""Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise.
"""
line = clean_lines.elided[linenum]
match = Search(pattern, line)
if not match:
return False
# Exclude lines with keywords that tend to look like casts
context = line[0:match.start(1) - 1]
if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
return False
# Try expanding current context to see if we one level of
# parentheses inside a macro.
if linenum > 0:
for i in range(linenum - 1, max(0, linenum - 5), -1):
context = clean_lines.elided[i] + context
if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
return False
# operator++(int) and operator--(int)
if context.endswith(' operator++') or context.endswith(' operator--'):
return False
# A single unnamed argument for a function tends to look like old style cast.
# If we see those, don't issue warnings for deprecated casts.
remainder = line[match.end(0):]
if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
remainder):
return False
# At this point, all that should be left is actual casts.
error(filename, linenum, 'readability/casting', 4,
'Using C-style cast. Use %s<%s>(...) instead' %
(cast_type, match.group(1)))
return True
def ExpectingFunctionArgs(clean_lines, linenum):
"""Checks whether where function type arguments are expected.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if the line at 'linenum' is inside something that expects arguments
of function types.
"""
line = clean_lines.elided[linenum]
return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
(linenum >= 2 and
(Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
clean_lines.elided[linenum - 1]) or
Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
clean_lines.elided[linenum - 2]) or
Search(r'\bstd::m?function\s*\<\s*$',
clean_lines.elided[linenum - 1]))))
_HEADERS_CONTAINING_TEMPLATES = (
('<atomic>', ('atomic',)),
('<deque>', ('deque',)),
('<functional>', ('unary_function', 'binary_function',
'plus', 'minus', 'multiplies', 'divides', 'modulus',
'negate',
'equal_to', 'not_equal_to', 'greater', 'less',
'greater_equal', 'less_equal',
'logical_and', 'logical_or', 'logical_not',
'unary_negate', 'not1', 'binary_negate', 'not2',
'bind1st', 'bind2nd',
'pointer_to_unary_function',
'pointer_to_binary_function',
'ptr_fun',
'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
'mem_fun_ref_t',
'const_mem_fun_t', 'const_mem_fun1_t',
'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
'mem_fun_ref',
)),
('<limits>', ('numeric_limits',)),
('<list>', ('list',)),
('<map>', ('map', 'multimap',)),
('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
'unique_ptr', 'weak_ptr')),
('<queue>', ('queue', 'priority_queue',)),
('<set>', ('set', 'multiset',)),
('<stack>', ('stack',)),
('<string>', ('char_traits', 'basic_string',)),
('<tuple>', ('tuple',)),
('<unordered_map>', ('unordered_map', 'unordered_multimap')),
('<unordered_set>', ('unordered_set', 'unordered_multiset')),
('<utility>', ('pair',)),
('<vector>', ('vector',)),
# gcc extensions.
# Note: std::hash is their hash, ::hash is our hash
('<hash_map>', ('hash_map', 'hash_multimap',)),
('<hash_set>', ('hash_set', 'hash_multiset',)),
('<slist>', ('slist',)),
)
_HEADERS_MAYBE_TEMPLATES = (
('<algorithm>', ('min_element',)),
('<utility>', ('forward', 'make_pair', 'move')),
)
_RE_PATTERN_STRING = re.compile(r'\bstring\b')
_re_pattern_headers_maybe_templates = []
for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
for _template in _templates:
# Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
# type::max().
_re_pattern_headers_maybe_templates.append(
(re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
_template,
_header))
# Other scripts may reach in and modify this pattern.
_re_pattern_templates = []
for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
for _template in _templates:
_re_pattern_templates.append(
(re.compile(r'(\<|\b)' + _template + r'\s*\<'),
_template + '<>',
_header))
def FilesBelongToSameModule(filename_cc, filename_h):
"""Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and some/path/internal/xyzzy are also considered
to belong to the same module here.
If the filename_cc contains a longer path than the filename_h, for example,
'/absolute/path/to/base/sysinfo.cc', and this file would include
'base/sysinfo.h', this function also produces the prefix needed to open the
header. This is used by the caller of this function to more robustly open the
header file. We don't have access to the real include paths in this context,
so we need this guesswork here.
Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
according to this implementation. Because of this, this function gives
some false positives. This should be sufficiently rare in practice.
Args:
filename_cc: is the path for the .cc file
filename_h: is the path for the header path
Returns:
Tuple with a bool and a string:
bool: True if filename_cc and filename_h belong to the same module.
string: the additional prefix needed to open the header file.
"""
fileinfo = FileInfo(filename_cc)
if not fileinfo.IsSource():
return (False, '')
filename_cc = filename_cc[:-len(fileinfo.Extension())]
matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
if matched_test_suffix:
filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
filename_cc = filename_cc.replace('/public/', '/')
filename_cc = filename_cc.replace('/internal/', '/')
if not filename_h.endswith('.h'):
return (False, '')
filename_h = filename_h[:-len('.h')]
if filename_h.endswith('-inl'):
filename_h = filename_h[:-len('-inl')]
filename_h = filename_h.replace('/public/', '/')
filename_h = filename_h.replace('/internal/', '/')
files_belong_to_same_module = filename_cc.endswith(filename_h)
common_path = ''
if files_belong_to_same_module:
common_path = filename_cc[:-len(filename_h)]
return files_belong_to_same_module, common_path
def UpdateIncludeState(filename, include_dict, io=codecs):
"""Fill up the include_dict with new includes found from the file.
Args:
filename: the name of the header to read.
include_dict: a dictionary in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was successfully added. False otherwise.
"""
headerfile = None
try:
headerfile = io.open(filename, 'r', 'utf8', 'replace')
except IOError:
return False
linenum = 0
for line in headerfile:
linenum += 1
clean_line = CleanseComments(line)
match = _RE_PATTERN_INCLUDE.search(clean_line)
if match:
include = match.group(2)
include_dict.setdefault(include, linenum)
return True
def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
io=codecs):
"""Reports for missing stl includes.
This function will output warnings to make sure you are including the headers
necessary for the stl containers and functions that you use. We only give one
reason to include a header. For example, if you use both equal_to<> and
less<> in a .h file, only one (the latter in the file) of these will be
reported as a reason to include the <functional>.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
include_state: An _IncludeState instance.
error: The function to call with any errors found.
io: The IO factory to use to read the header file. Provided for unittest
injection.
"""
required = {} # A map of header name to linenumber and the template entity.
# Example of required: { '<functional>': (1219, 'less<>') }
for linenum in range(clean_lines.NumLines()):
line = clean_lines.elided[linenum]
if not line or line[0] == '#':
continue
# String is special -- it is a non-templatized type in STL.
matched = _RE_PATTERN_STRING.search(line)
if matched:
# Don't warn about strings in non-STL namespaces:
# (We check only the first match per line; good enough.)
prefix = line[:matched.start()]
if prefix.endswith('std::') or not prefix.endswith('::'):
required['<string>'] = (linenum, 'string')
for pattern, template, header in _re_pattern_headers_maybe_templates:
if pattern.search(line):
required[header] = (linenum, template)
# The following function is just a speed up, no semantics are changed.
if not '<' in line: # Reduces the cpu time usage by skipping lines.
continue
for pattern, template, header in _re_pattern_templates:
matched = pattern.search(line)
if matched:
# Don't warn about IWYU in non-STL namespaces:
# (We check only the first match per line; good enough.)
prefix = line[:matched.start()]
if prefix.endswith('std::') or not prefix.endswith('::'):
required[header] = (linenum, template)
# The policy is that if you #include something in foo.h you don't need to
# include it again in foo.cc. Here, we will look at possible includes.
# Let's flatten the include_state include_list and copy it into a dictionary.
include_dict = dict([item for sublist in include_state.include_list
for item in sublist])
# Did we find the header for this file (if any) and successfully load it?
header_found = False
# Use the absolute path so that matching works properly.
abs_filename = FileInfo(filename).FullName()
# For Emacs's flymake.
# If cpplint is invoked from Emacs's flymake, a temporary file is generated
# by flymake and that file name might end with '_flymake.cc'. In that case,
# restore original file name here so that the corresponding header file can be
# found.
# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
# instead of 'foo_flymake.h'
abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
# include_dict is modified during iteration, so we iterate over a copy of
# the keys.
header_keys = list(include_dict.keys())
for header in header_keys:
(same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
fullpath = common_path + header
if same_module and UpdateIncludeState(fullpath, include_dict, io):
header_found = True
# If we can't find the header file for a .cc, assume it's because we don't
# know where to look. In that case we'll give up as we're not sure they
# didn't include it in the .h file.
# TODO(unknown): Do a better job of finding .h files so we are confident that
# not having the .h file means there isn't one.
if filename.endswith('.cc') and not header_found:
return
# All the lines have been processed, report the errors found.
for required_header_unstripped in required:
template = required[required_header_unstripped][1]
if required_header_unstripped.strip('<>"') not in include_dict:
error(filename, required[required_header_unstripped][0],
'build/include_what_you_use', 4,
'Add #include ' + required_header_unstripped + ' for ' + template)
_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
"""Check that make_pair's template arguments are deduced.
G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
if match:
error(filename, linenum, 'build/explicit_make_pair',
4, # 4 = high confidence
'For C++11-compatibility, omit template arguments from make_pair'
' OR use pair directly OR if appropriate, construct a pair directly')
def CheckRedundantVirtual(filename, clean_lines, linenum, error):
"""Check if line contains a redundant "virtual" function-specifier.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Look for "virtual" on current line.
line = clean_lines.elided[linenum]
virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
if not virtual: return
# Ignore "virtual" keywords that are near access-specifiers. These
# are only used in class base-specifier and do not apply to member
# functions.
if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
return
# Ignore the "virtual" keyword from virtual base classes. Usually
# there is a column on the same line in these cases (virtual base
# classes are rare in google3 because multiple inheritance is rare).
if Match(r'^.*[^:]:[^:].*$', line): return
# Look for the next opening parenthesis. This is the start of the
# parameter list (possibly on the next line shortly after virtual).
# TODO(unknown): doesn't work if there are virtual functions with
# decltype() or other things that use parentheses, but csearch suggests
# that this is rare.
end_col = -1
end_line = -1
start_col = len(virtual.group(2))
for start_line in range(linenum, min(linenum + 3, clean_lines.NumLines())):
line = clean_lines.elided[start_line][start_col:]
parameter_list = Match(r'^([^(]*)\(', line)
if parameter_list:
# Match parentheses to find the end of the parameter list
(_, end_line, end_col) = CloseExpression(
clean_lines, start_line, start_col + len(parameter_list.group(1)))
break
start_col = 0
if end_col < 0:
return # Couldn't find end of parameter list, give up
# Look for "override" or "final" after the parameter list
# (possibly on the next few lines).
for i in range(end_line, min(end_line + 3, clean_lines.NumLines())):
line = clean_lines.elided[i][end_col:]
match = Search(r'\b(override|final)\b', line)
if match:
error(filename, linenum, 'readability/inheritance', 4,
('"virtual" is redundant since function is '
'already declared as "%s"' % match.group(1)))
# Set end_col to check whole lines after we are done with the
# first line.
end_col = 0
if Search(r'[^\w]\s*$', line):
break
def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
"""Check if line contains a redundant "override" or "final" virt-specifier.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Look for closing parenthesis nearby. We need one to confirm where
# the declarator ends and where the virt-specifier starts to avoid
# false positives.
line = clean_lines.elided[linenum]
declarator_end = line.rfind(')')
if declarator_end >= 0:
fragment = line[declarator_end:]
else:
if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
fragment = line
else:
return
# Check that at most one of "override" or "final" is present, not both
if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
error(filename, linenum, 'readability/inheritance', 4,
('"override" is redundant since function is '
'already declared as "final"'))
# Returns true if we are at a new block, and it is directly
# inside of a namespace.
def IsBlockInNameSpace(nesting_state, is_forward_declaration):
"""Checks that the new block is directly in a namespace.
Args:
nesting_state: The _NestingState object that contains info about our state.
is_forward_declaration: If the class is a forward declared class.
Returns:
Whether or not the new block is directly in a namespace.
"""
if is_forward_declaration:
if len(nesting_state.stack) >= 1 and (
isinstance(nesting_state.stack[-1], _NamespaceInfo)):
return True
else:
return False
return (len(nesting_state.stack) > 1 and
nesting_state.stack[-1].check_namespace_indentation and
isinstance(nesting_state.stack[-2], _NamespaceInfo))
def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
raw_lines_no_comments, linenum):
"""This method determines if we should apply our namespace indentation check.
Args:
nesting_state: The current nesting state.
is_namespace_indent_item: If we just put a new class on the stack, True.
If the top of the stack is not a class, or we did not recently
add the class, False.
raw_lines_no_comments: The lines without the comments.
linenum: The current line number we are processing.
Returns:
True if we should apply our namespace indentation check. Currently, it
only works for classes and namespaces inside of a namespace.
"""
is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
linenum)
if not (is_namespace_indent_item or is_forward_declaration):
return False
# If we are in a macro, we do not want to check the namespace indentation.
if IsMacroDefinition(raw_lines_no_comments, linenum):
return False
return IsBlockInNameSpace(nesting_state, is_forward_declaration)
# Call this method if the line is directly inside of a namespace.
# If the line above is blank (excluding comments) or the start of
# an inner namespace, it cannot be indented.
def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
error):
line = raw_lines_no_comments[linenum]
if Match(r'^\s+', line):
error(filename, linenum, 'runtime/indentation_namespace', 4,
'Do not indent within a namespace')
def ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions=[]):
"""Processes a single line in the file.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
clean_lines: An array of strings, each representing a line of the file,
with comments stripped.
line: Number of line being processed.
include_state: An _IncludeState instance in which the headers are inserted.
function_state: A _FunctionState instance which counts function lines, etc.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
raw_lines = clean_lines.raw_lines
ParseNolintSuppressions(filename, raw_lines[line], line, error)
nesting_state.Update(filename, clean_lines, line, error)
CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
error)
if nesting_state.InAsmBlock(): return
CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
CheckLanguage(filename, clean_lines, line, file_extension, include_state,
nesting_state, error)
# CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
CheckForNonStandardConstructs(filename, clean_lines, line,
nesting_state, error)
CheckVlogArguments(filename, clean_lines, line, error)
CheckPosixThreading(filename, clean_lines, line, error)
CheckInvalidIncrement(filename, clean_lines, line, error)
CheckMakePairUsesDeduction(filename, clean_lines, line, error)
CheckRedundantVirtual(filename, clean_lines, line, error)
CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
for check_fn in extra_check_functions:
check_fn(filename, clean_lines, line, error)
def FlagCxx11Features(filename, clean_lines, linenum, error):
"""Flag those c++11 features that we only allow in certain places.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
# Flag unapproved C++ TR1 headers.
if include and include.group(1).startswith('tr1/'):
error(filename, linenum, 'build/c++tr1', 5,
('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
# DISABLE UNAPPROVED C++11 HEADERS
# Flag unapproved C++11 headers.
# if include and include.group(1) in ('cfenv',
# 'condition_variable',
# 'fenv.h',
# 'future',
# 'mutex',
# 'thread',
# 'chrono',
# 'ratio',
# 'regex',
# 'system_error',
# ):
# error(filename, linenum, 'build/c++11', 5,
# ('<%s> is an unapproved C++11 header.') % include.group(1))
# The only place where we need to worry about C++11 keywords and library
# features in preprocessor directives is in macro definitions.
if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
# These are classes and free functions. The classes are always
# mentioned as std::*, but we only catch the free functions if
# they're not found by ADL. They're alphabetical by header.
for top_name in (
# type_traits
'alignment_of',
'aligned_union',
):
if Search(r'\bstd::%s\b' % top_name, line):
error(filename, linenum, 'build/c++11', 5,
('std::%s is an unapproved C++11 class or function. Send c-style '
'an example of where it would make your code more readable, and '
'they may let you use it.') % top_name)
def FlagCxx14Features(filename, clean_lines, linenum, error):
"""Flag those C++14 features that we restrict.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
# Flag unapproved C++14 headers.
if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
error(filename, linenum, 'build/c++14', 5,
('<%s> is an unapproved C++14 header.') % include.group(1))
def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=[]):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
nesting_state = NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
ProcessGlobalSuppresions(lines)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
if IsHeaderExtension(file_extension):
CheckForHeaderGuard(filename, clean_lines, error)
for line in range(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
FlagCxx11Features(filename, clean_lines, line, error)
nesting_state.CheckCompletedBlocks(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# Check that the .cc file has included its header if it exists.
if _IsSourceExtension(file_extension):
CheckHeaderFileIncluded(filename, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForBadCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error)
def ProcessConfigOverrides(filename):
""" Loads the configuration files and processes the config overrides.
Args:
filename: The name of the file being processed by the linter.
Returns:
False if the current |filename| should not be processed further.
"""
abs_filename = os.path.abspath(filename)
cfg_filters = []
keep_looking = True
while keep_looking:
abs_path, base_name = os.path.split(abs_filename)
if not base_name:
break # Reached the root directory.
cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
abs_filename = abs_path
if not os.path.isfile(cfg_file):
continue
try:
with open(cfg_file) as file_handle:
for line in file_handle:
line, _, _ = line.partition('#') # Remove comments.
if not line.strip():
continue
name, _, val = line.partition('=')
name = name.strip()
val = val.strip()
if name == 'set noparent':
keep_looking = False
elif name == 'filter':
cfg_filters.append(val)
elif name == 'exclude_files':
# When matching exclude_files pattern, use the base_name of
# the current file name or the directory name we are processing.
# For example, if we are checking for lint errors in /foo/bar/baz.cc
# and we found the .cfg file at /foo/CPPLINT.cfg, then the config
# file's "exclude_files" filter is meant to be checked against "bar"
# and not "baz" nor "bar/baz.cc".
if base_name:
pattern = re.compile(val)
if pattern.match(base_name):
if _cpplint_state.quiet:
# Suppress "Ignoring file" warning when using --quiet.
return False
sys.stderr.write('Ignoring "%s": file excluded by "%s". '
'File path component "%s" matches '
'pattern "%s"\n' %
(filename, cfg_file, base_name, val))
return False
elif name == 'linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
sys.stderr.write('Line length must be numeric.')
elif name == 'root':
global _root
# root directories are specified relative to CPPLINT.cfg dir.
_root = os.path.join(os.path.dirname(cfg_file), val)
elif name == 'headers':
ProcessHppHeadersOption(val)
else:
sys.stderr.write(
'Invalid configuration option (%s) in file %s\n' %
(name, cfg_file))
except IOError:
sys.stderr.write(
"Skipping config file '%s': Can't open for reading\n" % cfg_file)
keep_looking = False
# Apply all the accumulated filters in reverse order (top-level directory
# config options having the least priority).
for filter in reversed(cfg_filters):
_AddFilters(filter)
return True
def ProcessFile(filename, vlevel, extra_check_functions=[]):
"""Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
_SetVerboseLevel(vlevel)
_BackupFilters()
old_errors = _cpplint_state.error_count
if not ProcessConfigOverrides(filename):
_RestoreFilters()
return
lf_lines = []
crlf_lines = []
try:
# Support the UNIX convention of using "-" for stdin. Note that
# we are not opening the file with universal newline support
# (which codecs doesn't support anyway), so the resulting lines do
# contain trailing '\r' characters if we are reading a file that
# has CRLF endings.
# If after the split a trailing '\r' is present, it is removed
# below.
if filename == '-':
lines = codecs.StreamReaderWriter(sys.stdin,
codecs.getreader('utf8'),
codecs.getwriter('utf8'),
'replace').read().split('\n')
else:
lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
# Remove trailing '\r'.
# The -1 accounts for the extra trailing blank line we get from split()
for linenum in range(len(lines) - 1):
if lines[linenum].endswith('\r'):
lines[linenum] = lines[linenum].rstrip('\r')
crlf_lines.append(linenum + 1)
else:
lf_lines.append(linenum + 1)
except IOError:
sys.stderr.write(
"Skipping input '%s': Can't open for reading\n" % filename)
_RestoreFilters()
return
# Note, if no dot is found, this will give the entire filename as the ext.
file_extension = filename[filename.rfind('.') + 1:]
# When reading from stdin, the extension is unknown, so no cpplint tests
# should rely on the extension.
if filename != '-' and file_extension not in _valid_extensions:
sys.stderr.write('Ignoring %s; not a valid file name '
'(%s)\n' % (filename, ', '.join(_valid_extensions)))
else:
ProcessFileData(filename, file_extension, lines, Error,
extra_check_functions)
# If end-of-line sequences are a mix of LF and CR-LF, issue
# warnings on the lines with CR.
#
# Don't issue any warnings if all lines are uniformly LF or CR-LF,
# since critique can handle these just fine, and the style guide
# doesn't dictate a particular end of line sequence.
#
# We can't depend on os.linesep to determine what the desired
# end-of-line sequence should be, since that will return the
# server-side end-of-line sequence.
if lf_lines and crlf_lines:
# Warn on every line with CR. An alternative approach might be to
# check whether the file is mostly CRLF or just LF, and warn on the
# minority, we bias toward LF here since most tools prefer LF.
for linenum in crlf_lines:
Error(filename, linenum, 'whitespace/newline', 1,
'Unexpected \\r (^M) found; better to use only \\n')
# Suppress printing anything if --quiet was passed unless the error
# count has increased after processing this file.
if not _cpplint_state.quiet or old_errors != _cpplint_state.error_count:
sys.stdout.write('Done processing %s\n' % filename)
_RestoreFilters()
def PrintUsage(message):
"""Prints a brief usage string and exits, optionally with an error message.
Args:
message: The optional error message.
"""
sys.stderr.write(_USAGE)
if message:
sys.exit('\nFATAL ERROR: ' + message)
else:
sys.exit(1)
def PrintCategories():
"""Prints a list of all the error-categories used by error messages.
These are the categories used to filter messages via --filter.
"""
sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
sys.exit(0)
def ParseArguments(args):
"""Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint.
"""
try:
(opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
'counting=',
'filter=',
'root=',
'linelength=',
'extensions=',
'headers=',
'quiet'])
except getopt.GetoptError:
PrintUsage('Invalid arguments.')
verbosity = _VerboseLevel()
output_format = _OutputFormat()
filters = ''
quiet = _Quiet()
counting_style = ''
for (opt, val) in opts:
if opt == '--help':
PrintUsage(None)
elif opt == '--output':
if val not in ('emacs', 'vs7', 'eclipse'):
PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
output_format = val
elif opt == '--quiet':
quiet = True
elif opt == '--verbose':
verbosity = int(val)
elif opt == '--filter':
filters = val
if not filters:
PrintCategories()
elif opt == '--counting':
if val not in ('total', 'toplevel', 'detailed'):
PrintUsage('Valid counting options are total, toplevel, and detailed')
counting_style = val
elif opt == '--root':
global _root
_root = val
elif opt == '--linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
PrintUsage('Line length must be digits.')
elif opt == '--extensions':
global _valid_extensions
try:
_valid_extensions = set(val.split(','))
except ValueError:
PrintUsage('Extensions must be comma seperated list.')
elif opt == '--headers':
ProcessHppHeadersOption(val)
if not filenames:
PrintUsage('No files were specified.')
_SetOutputFormat(output_format)
_SetQuiet(quiet)
_SetVerboseLevel(verbosity)
_SetFilters(filters)
_SetCountingStyle(counting_style)
return filenames
def main():
filenames = ParseArguments(sys.argv[1:])
# Change stderr to write with replacement characters so we don't die
# if we try to print something containing non-ASCII characters.
if python2_version:
sys.stderr = codecs.StreamReaderWriter(sys.stderr,
codecs.getreader('utf8'),
codecs.getwriter('utf8'),
'replace')
_cpplint_state.ResetErrorCounts()
for filename in filenames:
ProcessFile(filename, _cpplint_state.verbose_level)
# If --quiet is passed, suppress printing error count unless there are errors.
if not _cpplint_state.quiet or _cpplint_state.error_count > 0:
_cpplint_state.PrintErrorCounts()
sys.exit(_cpplint_state.error_count > 0)
if __name__ == '__main__':
main()
|
DALI-main
|
third_party/cpplint.py
|
# Copyright (c) 2019-2022, NVIDIA CORPORATION & AFFILIATES. 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 subprocess
import os
import re
import sys
import fnmatch
from distutils.version import StrictVersion
# Find file matching `pattern` in `path`
def find(pattern, path):
result = []
for root, _, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
# Get path to python module `module_name`
def get_module_path(module_name):
module_path = ''
for d in sys.path:
possible_path = os.path.join(d, module_name)
# skip current dir as this is plugin dir
if os.path.isdir(possible_path) and len(d) != 0:
module_path = possible_path
break
return module_path
# Get compiler version used to build tensorflow
def get_tf_compiler_version():
tensorflow_libs = find('libtensorflow_framework*so*', get_module_path('tensorflow'))
if not tensorflow_libs:
tensorflow_libs = find('libtensorflow_framework*so*', get_module_path('tensorflow_core'))
if not tensorflow_libs:
return ''
lib = tensorflow_libs[0]
cmd = 'strings -a ' + lib + ' | grep "GCC: ("'
s = str(subprocess.check_output(cmd, shell=True))
lines = s.split('\\n')
ret_ver = ''
for line in lines:
res = re.search(r"GCC:\s*\(.*\)\s*(\d+.\d+).\d+", line)
if res:
ver = res.group(1)
if not ret_ver or StrictVersion(ret_ver) < StrictVersion(ver):
ret_ver = ver
return ret_ver
# Get current tensorflow version
def get_tf_version():
try:
import pkg_resources
s = pkg_resources.get_distribution("tensorflow-gpu").version
except pkg_resources.DistributionNotFound:
# pkg_resources.get_distribution doesn't work well with conda installed packages
try:
import tensorflow as tf
s = tf.__version__
except ModuleNotFoundError:
return ""
version = re.search(r"(\d+.\d+).\d+", s).group(1)
return version
# Get C++ compiler
def get_cpp_compiler():
return os.environ.get('CXX') or 'g++'
# Get C++ compiler version
def get_cpp_compiler_version():
cmd = get_cpp_compiler() + ' --version | head -1 | grep "[c|g]++ ("'
s = str(subprocess.check_output(cmd, shell=True).strip())
version = re.search(r"[g|c]\+\+\s*\(.*\)\s*(\d+.\d+).\d+", s).group(1)
return version
# Runs `which` program
def which(program):
try:
return subprocess.check_output('which ' + program, shell=True).strip()
except subprocess.CalledProcessError:
return None
# Checks whether we are inside a conda env
def is_conda_env():
return True if os.environ.get('CONDA_PREFIX') else False
# Get compile and link flags for installed tensorflow
def get_tf_build_flags():
tf_cflags = ''
tf_lflags = ''
try:
import tensorflow as tensorflow
tf_cflags = " ".join(tensorflow.sysconfig.get_compile_flags())
tf_lflags = " ".join(tensorflow.sysconfig.get_link_flags())
except ModuleNotFoundError:
tensorflow_path = get_module_path('tensorflow')
if tensorflow_path != '':
tf_cflags = " ".join(["-I" + tensorflow_path + "/include", "-I" + tensorflow_path +
"/include/external/nsync/public", "-D_GLIBCXX_USE_CXX11_ABI=0"])
tf_lflags = " ".join(["-L" + tensorflow_path, "-ltensorflow_framework"])
if tf_cflags == '' and tf_lflags == '':
raise ImportError(
'Could not find Tensorflow. Tensorflow must be installed before installing' +
'NVIDIA DALI TF plugin')
return (tf_cflags, tf_lflags)
# Get compile and link flags for installed DALI
def get_dali_build_flags():
dali_cflags = ''
dali_lflags = ''
try:
import nvidia.dali.sysconfig as dali_sc
# We are linking with DALI's C library, so we don't need the C++ compile flags
# including the CXX11_ABI setting
dali_cflags = " ".join(dali_sc.get_include_flags())
dali_lflags = " ".join(dali_sc.get_link_flags())
except ModuleNotFoundError:
dali_path = get_module_path('nvidia/dali')
if dali_path != '':
dali_cflags = " ".join(["-I" + dali_path + "/include"])
dali_lflags = " ".join(["-L" + dali_path, "-ldali"])
if dali_cflags == '' and dali_lflags == '':
raise ImportError('Could not find DALI.')
return (dali_cflags, dali_lflags)
# Get compile and link flags for installed CUDA
def get_cuda_build_flags():
cuda_cflags = ''
cuda_lflags = ''
cuda_home = os.environ.get('CUDA_HOME')
if not cuda_home:
cuda_home = '/usr/local/cuda'
cuda_cflags = " ".join(["-I" + cuda_home + "/include"])
cuda_lflags = " ".join([])
return (cuda_cflags, cuda_lflags)
def find_available_prebuilt_tf(requested_version, available_libs):
req_ver_first, req_ver_second = [int(v) for v in requested_version.split('.', 2)]
selected_ver = None
for file in available_libs:
re_match = re.search(r".*(\d+)_(\d+).*", file)
if re_match is None:
continue
ver_first, ver_second = [int(v) for v in re_match.groups()]
if ver_first == req_ver_first:
if ver_second <= req_ver_second and (selected_ver is None or
selected_ver < (ver_first, ver_second)):
selected_ver = (ver_first, ver_second)
return '.'.join([str(v) for v in selected_ver]) if selected_ver is not None else None
|
DALI-main
|
dali_tf_plugin/dali_tf_plugin_utils.py
|
# Copyright (c) 2019-2022, NVIDIA CORPORATION & AFFILIATES. 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 platform
from shutil import copyfile
from dali_tf_plugin_utils import get_module_path, is_conda_env, get_tf_version, \
get_tf_compiler_version, get_cpp_compiler, get_cpp_compiler_version, which, find, \
find_available_prebuilt_tf, get_cuda_build_flags, get_tf_build_flags
import os
from distutils.version import StrictVersion, LooseVersion
from pathlib import Path
import tempfile
from stubgen import stubgen
from multiprocessing import Process
import subprocess
def plugin_load_and_test(dali_tf_path):
# Make sure that TF won't try using CUDA
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from nvidia.dali.pipeline import pipeline_def
import nvidia.dali.types as types
import tensorflow as tf
try:
from tensorflow.compat.v1 import Session
except Exception:
# Older TF versions don't have compat.v1 layer
from tensorflow import Session
try:
tf.compat.v1.disable_eager_execution()
except Exception:
pass
@pipeline_def()
def get_dali_pipe():
data = types.Constant(1)
return data
_dali_tf_module = tf.load_op_library(dali_tf_path)
_dali_tf = _dali_tf_module.dali
def get_data():
batch_size = 3
pipe = get_dali_pipe(batch_size=batch_size,
device_id=types.CPU_ONLY_DEVICE_ID, num_threads=1)
out = []
with tf.device('/cpu'):
data = _dali_tf(serialized_pipeline=pipe.serialize(),
shapes=[(batch_size,)],
dtypes=[tf.int32],
device_id=types.CPU_ONLY_DEVICE_ID,
batch_size=batch_size,
exec_separated=False,
gpu_prefetch_queue_depth=2,
cpu_prefetch_queue_depth=2)
out.append(data)
return [out]
test_batch = get_data()
with Session() as sess:
for _ in range(3):
print(sess.run(test_batch))
class InstallerHelper:
def __init__(self, plugin_dest_dir=None):
self.src_path = os.path.dirname(os.path.realpath(__file__))
self.dali_lib_path = get_module_path('nvidia/dali')
self.tf_path = get_module_path('tensorflow')
self.plugin_dest_dir = os.path.join(
self.src_path, 'nvidia', 'dali_tf_plugin') if plugin_dest_dir is None else \
plugin_dest_dir
self.is_conda = is_conda_env()
self.tf_version = get_tf_version()
self.tf_compiler = get_tf_compiler_version()
self.cpp_compiler = get_cpp_compiler()
self.default_cpp_version = get_cpp_compiler_version()
self.alt_compiler = 'g++-{}'.format(self.tf_compiler)
self.has_alt_compiler = which(self.alt_compiler) is not None
self.platform_system = platform.system()
self.platform_machine = platform.machine()
self.is_compatible_with_prebuilt_bin = self.platform_system == 'Linux' and \
self.platform_machine == 'x86_64'
self.prebuilt_dir = os.path.join(self.src_path, 'prebuilt')
self.prebuilt_stub_dir = os.path.join(self.prebuilt_dir, 'stub')
dali_stubs = find('libdali.so', self.prebuilt_stub_dir)
self.prebuilt_dali_stub = dali_stubs[0] if len(dali_stubs) > 0 else None
# If set, checking for prebuilt binaries or compiler version check is disabled
self.always_build = bool(int(os.getenv('DALI_TF_ALWAYS_BUILD', '0')))
# Can install prebuilt if both conditions apply:
# - we know the compiler used to build TF
# - we have prebuilt artifacts for that compiler version
# - We have an exact match with the TF version major.minor or an exact match of the
# major version and the minor version in the prebuilt plugin is lower than the
# requested one.
self.can_install_prebuilt = not self.always_build and \
bool(self.tf_compiler) and \
StrictVersion(self.tf_compiler) >= StrictVersion('5.0') and \
self.is_compatible_with_prebuilt_bin and \
self.prebuilt_dali_stub is not None
self.prebuilt_plugins_available = []
self.prebuilt_plugin_best_match = None
self.plugin_name = None
self.prebuilt_exact_ver = False
if self.can_install_prebuilt:
self.prebuilt_plugins_available = find('libdali_tf_*.so', self.prebuilt_dir)
best_version = find_available_prebuilt_tf(
self.tf_version, self.prebuilt_plugins_available)
if best_version is None:
# No prebuilt plugins available
self.can_install_prebuilt = False
else:
self.prebuilt_exact_ver = (best_version == self.tf_version)
tf_version_underscore = best_version.replace('.', '_')
self.plugin_name = 'libdali_tf_' + tf_version_underscore + '.so'
self.prebuilt_plugin_best_match = os.path.join(self.prebuilt_dir, self.plugin_name)
# Allow to compile if either condition apply
# - The default C++ compiler version matches the one used to build TF
# - The compiler used to build TF is unknown
# - Both TF and default compilers are >= 5.0
self.can_default_compile = self.always_build or \
self.default_cpp_version == self.tf_compiler or \
not bool(self.tf_compiler) or \
(StrictVersion(self.default_cpp_version) >= StrictVersion('5.0') and
StrictVersion(self.tf_compiler) >= StrictVersion('5.0'))
def debug_str(self):
s = "\n Environment:"
s += "\n ----------------------------------------------------------------------------------"
s += "\n Platform system: {}".format(self.platform_system)
s += "\n Platform machine: {}".format(self.platform_machine)
s += "\n DALI lib path: {}".format(
self.dali_lib_path or "Not Installed")
s += "\n TF path: {}".format(self.tf_path or "Not Installed")
s += "\n DALI TF plugin destination directory: {}".format(self.plugin_dest_dir)
s += "\n Is Conda environment? {}".format("Yes" if self.is_conda else "No")
s += "\n Using compiler: \"{}\", version {}".format(
self.cpp_compiler, self.default_cpp_version or "Unknown")
s += "\n TF version installed: {}".format(self.tf_version or "Unknown")
if self.tf_version:
s += "\n g++ version used to compile TF: {}".format(self.tf_compiler or "Unknown")
s += "\n Is {} present in the system? {}".format(
self.alt_compiler, "Yes" if self.has_alt_compiler else "No")
s += "\n Can install prebuilt plugin? {}".format(
"Yes" if self.can_install_prebuilt else "No")
s += "\n Prebuilt for exact TF version? {}".format(
"Yes" if self.prebuilt_exact_ver else "No")
s += "\n Prebuilt plugin path: {}".format(
self.prebuilt_plugin_best_match or "N/A")
s += "\n Prebuilt plugins available: {}".format(
", ".join(self.prebuilt_plugins_available) or "N/A")
s += "\n Prebuilt DALI stub available: {}".format(
self.prebuilt_dali_stub or "N/A")
s += "\n Can compile with default compiler? {}".format(
"Yes" if self.can_default_compile else "No")
s += "\n Can compile with alt compiler? {}".format(
"Yes" if self.has_alt_compiler else "No")
s += "\n-----------------------------------------------------------------------------------"
return s
def _test_plugin_in_tmp_dir(self, lib_path, dali_stub, test_fn):
lib_name = os.path.basename(lib_path)
dali_stub_name = os.path.basename(dali_stub)
print("Importing the DALI TF library to check for errors")
# The DALI TF lib and the DALI stub lib should be at the same directory for
# check_load_plugin to succeed. Unfortunately the copy is necessary because we
# can't change LD_LIBRARY_PATH from within the script
with tempfile.TemporaryDirectory(prefix="check_load_plugin_tmp") as tmpdir:
lib_path_tmpdir = os.path.join(tmpdir, lib_name)
copyfile(lib_path, lib_path_tmpdir)
dali_stub_tmpdir = os.path.join(tmpdir, dali_stub_name)
copyfile(dali_stub, dali_stub_tmpdir)
try:
print("Loading DALI TF library: ", lib_path_tmpdir)
# try in a separate process just in case it recives SIGV
p = Process(target=test_fn, args=(lib_path_tmpdir, ))
p.start()
p.join(5)
ret = p.exitcode
if ret is None:
p.terminate()
p.join()
return ret == 0
except Exception as e:
print("Failed to import TF library: ", str(e))
return False
def check_load_plugin(self, lib_path, dali_stub):
import tensorflow as tf
return self._test_plugin_in_tmp_dir(lib_path, dali_stub, tf.load_op_library)
def test_plugin(self, lib_path, dali_stub):
return self._test_plugin_in_tmp_dir(lib_path, dali_stub, plugin_load_and_test)
def check_plugin(self, plugin_path, dali_stub_path):
dali_available = True
try:
import nvidia.dali as dali
assert dali
except ImportError:
dali_available = False
if dali_available:
# If DALI is available, test the plugin
return self.test_plugin(plugin_path, dali_stub_path)
else:
# If DALI not available, at least check loading to TF
return self.check_load_plugin(plugin_path, dali_stub_path)
def install_prebuilt(self):
assert (self.can_install_prebuilt)
assert (self.prebuilt_plugin_best_match is not None)
assert (self.plugin_name is not None)
print(f"Tensorflow was built with g++ {self.tf_compiler}, providing prebuilt plugin")
if self.check_plugin(self.prebuilt_plugin_best_match, self.prebuilt_dali_stub):
print("Copy {} to {}".format(self.prebuilt_plugin_best_match, self.plugin_dest_dir))
plugin_dest = os.path.join(self.plugin_dest_dir, self.plugin_name)
copyfile(self.prebuilt_plugin_best_match, plugin_dest)
print("Installation successful")
return True
else:
print("Failed check for {self.prebuilt_plugin_best_match}," +
"will not install prebuilt plugin")
return False
def get_compiler(self):
compiler = self.cpp_compiler
if not self.can_default_compile:
if self.has_alt_compiler:
print("Will use alternative compiler {}".format(self.alt_compiler))
compiler = self.alt_compiler
elif self.is_conda:
error_msg = "Installation error:"
error_msg += "\n Conda C++ compiler version should be the same as the compiler " + \
"used to build tensorflow " + \
f"({self.default_cpp_version} != {self.tf_compiler})."
error_msg += f"\n Try to run `conda install gxx_linux-64=={self.tf_compiler}` " + \
f"or install an alternative compiler `g++-{self.tf_compiler}` and " + \
"install again"
error_msg += '\n' + self.debug_str()
raise ImportError(error_msg)
else:
error_msg = "Installation error:"
error_msg += "\n Tensorflow was built with a different compiler than the " + \
"currently installed " + \
f"({self.default_cpp_version} != {self.tf_compiler})"
error_msg += f"\n Try to install `g++-{self.tf_compiler}` or use CXX " + \
"environment variable to point to the right compiler and install again"
error_msg += '\n' + self.debug_str()
raise ImportError(error_msg)
return compiler
def build(self):
print("Proceed with build from source...")
compiler = self.get_compiler()
cuda_cflags, cuda_lflags = get_cuda_build_flags()
with tempfile.TemporaryDirectory(prefix="dali_stub_") as tmpdir:
# Building a DALI stub library. During runtime, the real libdali.so will be already
# loaded at the moment when the DALI TF plugin is loaded
# This is done to avoid depending on DALI being installed during
# DALI TF sdist installation
dali_stub_src = os.path.join(tmpdir, 'dali_stub.cc')
dali_stub_lib = os.path.join(tmpdir, 'libdali.so')
dali_c_api_hdr = os.path.join(self.src_path, 'include', 'dali', 'c_api.h')
with open(dali_stub_src, 'w+') as f:
stubgen(header_filepath=dali_c_api_hdr, out_file=f)
dali_lflags = '-L' + tmpdir + ' -ldali'
dali_cflags = '-I' + os.path.join(self.src_path, 'include')
cmd = compiler + ' -Wl,-R,\'$ORIGIN/..\' -std=c++14 -DNDEBUG -shared ' \
+ dali_stub_src + ' -o ' + dali_stub_lib + ' -fPIC ' + dali_cflags + ' ' \
+ cuda_cflags + ' ' + cuda_lflags + ' -O2'
print('Building DALI stub lib:\n\n ' + cmd + '\n\n')
subprocess.check_call(cmd, cwd=self.src_path, shell=True)
tf_cflags, tf_lflags = get_tf_build_flags()
filenames = ['daliop.cc', 'dali_dataset_op.cc']
plugin_src = ''
for filename in filenames:
plugin_src = plugin_src + ' ' + os.path.join(self.src_path, filename)
lib_filename = 'libdali_tf_current.so'
lib_path = os.path.join(self.plugin_dest_dir, lib_filename)
# for a newer TF we need to compiler with C++17
cpp_ver = "--std=c++14" if self.tf_version < LooseVersion('2.10') else "--std=c++17"
# Note: DNDEBUG flag is needed due to issue with TensorFlow custom ops:
# https://github.com/tensorflow/tensorflow/issues/17316
# Do not remove it.
# the latest TF in conda needs to include /PREFIX/include
root_include = "-I" + os.getenv("PREFIX", default="/usr") + "/include"
cmd = compiler + ' -Wl,-R,\'$ORIGIN/..\' -Wl,-rpath,\'$ORIGIN\' ' + cpp_ver + \
' -DNDEBUG -shared ' + plugin_src + ' -o ' + lib_path + ' -fPIC ' + \
dali_cflags + ' ' + tf_cflags + ' ' + root_include + ' ' + cuda_cflags + \
' ' + dali_lflags + ' ' + tf_lflags + ' ' + cuda_lflags + ' -O2'
print("Build DALI TF library:\n\n " + cmd + '\n\n')
subprocess.check_call(cmd, cwd=self.src_path, shell=True)
if not self.check_plugin(lib_path, dali_stub_lib):
raise ImportError("Error while loading or testing the DALI TF plugin built " +
"from source, will not install")
print("Installation successful")
def check_install_env(self):
print("Checking build environment for DALI TF plugin ...")
print(self.debug_str())
if not self.tf_version or not self.tf_path:
error_msg = "Installation error:"
error_msg += "\n Tensorflow installation not found. Install `tensorflow-gpu` " + \
"and try again"
error_msg += '\n' + self.debug_str()
raise ImportError(error_msg)
Path(self.plugin_dest_dir).mkdir(parents=True, exist_ok=True)
def install(self):
self.check_install_env()
if self.prebuilt_exact_ver and self.install_prebuilt():
return
try:
self.build()
except Exception as e:
print("Build from source failed with error: ", e)
# If we haven't tried the prebuilt binary yet but there is one available, try now
if self.can_install_prebuilt and not self.prebuilt_exact_ver:
print("Trying to install prebuilt plugin")
if self.install_prebuilt():
return
raise e
def main():
env = InstallerHelper()
env.install()
if __name__ == "__main__":
main()
|
DALI-main
|
dali_tf_plugin/dali_tf_plugin_install_tool.py
|
#!/usr/bin/python
import sys
import os
import argparse
def get_module_path(module_name):
module_path = ''
for d in sys.path:
possible_path = os.path.join(d, module_name)
# skip current dir as this is plugin dir
if os.path.isdir(possible_path) and len(d) != 0:
module_path = possible_path
break
return module_path
def get_dali_build_flags():
dali_cflags = ''
dali_lflags = ''
dali_include_flags = ''
try:
import nvidia.dali.sysconfig as dali_sc
dali_include_flags = " ".join(dali_sc.get_include_flags())
dali_cflags = " ".join(dali_sc.get_compile_flags())
dali_lflags = " ".join(dali_sc.get_link_flags())
except BaseException:
dali_path = get_module_path('nvidia/dali')
if dali_path != '':
dali_include_flags = " ".join(["-I" + dali_path + "/include"])
dali_cflags = " ".join(["-I" + dali_path + "/include", "-D_GLIBCXX_USE_CXX11_ABI=0"])
dali_lflags = " ".join(["-L" + dali_path, "-ldali"])
if dali_include_flags == '' and dali_cflags == '' and dali_lflags == '':
raise ImportError('Could not find DALI.')
return (dali_include_flags, dali_cflags, dali_lflags)
parser = argparse.ArgumentParser(description='DALI TF plugin compile flags')
parser.add_argument('--include_flags', dest='include_flags', action='store_true')
parser.add_argument('--cflags', dest='cflags', action='store_true')
parser.add_argument('--lflags', dest='lflags', action='store_true')
args = parser.parse_args()
include_flags, cflags, lflags = get_dali_build_flags()
flags = []
if args.include_flags:
flags = flags + [include_flags]
if args.cflags:
flags = flags + [cflags]
if args.lflags:
flags = flags + [lflags]
print(" ".join(flags))
|
DALI-main
|
dali_tf_plugin/dali_compile_flags.py
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION & AFFILIATES. 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 tensorflow as tf
import os
import glob
import re
_dali_tf_module = None
def load_dali_tf_plugin():
global _dali_tf_module
if _dali_tf_module is not None:
return _dali_tf_module
import nvidia.dali as dali # Make sure DALI lib is loaded
assert dali
tf_plugins = glob.glob(os.path.join(os.path.dirname(
os.path.realpath(__file__)), 'libdali_tf*.so'))
# Order: 'current', prebuilt for current TF version, prebuilt for other TF versions
tf_version = re.search(r"(\d+.\d+).\d+", tf.__version__).group(1)
tf_version_underscore = tf_version.replace('.', '_')
dali_tf_current = list(filter(lambda x: 'current' in x, tf_plugins))
dali_tf_prebuilt_tf_ver = list(filter(lambda x: tf_version_underscore in x, tf_plugins))
dali_tf_prebuilt_others = list(
filter(lambda x: 'current' not in x and tf_version_underscore not in x, tf_plugins))
processed_tf_plugins = dali_tf_current + dali_tf_prebuilt_tf_ver + dali_tf_prebuilt_others
first_error = None
for libdali_tf in processed_tf_plugins:
try:
_dali_tf_module = tf.load_op_library(libdali_tf)
break
# if plugin is not compatible skip it
except tf.errors.NotFoundError as error:
if first_error is None:
first_error = error
else:
raise first_error or Exception(
'No matching DALI plugin found for installed TensorFlow version')
return _dali_tf_module
|
DALI-main
|
dali_tf_plugin/nvidia/dali_tf_plugin/dali_tf_plugin.py
|
# Copyright (c) 2017-2018, NVIDIA CORPORATION. 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 argparse
from nvidia.dali.pipeline import Pipeline
import nvidia.dali.ops as ops
import nvidia.dali.types as types
import numpy as np
from timeit import default_timer as timer
image_folder = "/data/dali/benchmark/benchmark_images"
def read_jpegs(folder):
with open(folder + "/image_list.txt", 'r') as file:
files = [line.rstrip() for line in file]
images = []
for fname in files:
f = open(image_folder + "/" + fname, 'rb')
images.append(np.fromstring(f.read(), dtype=np.uint8))
return images
def make_batch(size):
data = read_jpegs(image_folder)
return [data[i % len(data)] for i in range(size)]
class C2Pipe(Pipeline):
def __init__(self, batch_size, num_threads, device_id, pipelined=True, exec_async=True):
super(C2Pipe, self).__init__(batch_size,
num_threads,
device_id,
exec_pipelined=pipelined,
exec_async=exec_async)
self.input = ops.ExternalSource()
self.decode = ops.ImageDecoder(device='cpu', output_type=types.RGB)
self.rcm = ops.FastResizeCropMirror(crop=(224, 224))
self.np = ops.CropMirrorNormalize(device="gpu",
dtype=types.FLOAT16,
mean=[128., 128., 128.],
std=[1., 1., 1.])
self.uniform = ops.random.Uniform(range=(0., 1.))
self.resize_uniform = ops.random.Uniform(range=(256., 480.))
self.mirror = ops.random.CoinFlip(probability=0.5)
def define_graph(self):
self.jpegs = self.input()
images = self.decode(self.jpegs)
resized = self.rcm(images, crop_pos_x=self.uniform(),
crop_pos_y=self.uniform(),
mirror=self.mirror(),
resize_shorter=self.resize_uniform())
output = self.np(resized.gpu())
return output
def iter_setup(self):
raw_data = make_batch(self.batch_size)
self.feed_input(self.jpegs, raw_data)
class HybridPipe(Pipeline):
def __init__(self, batch_size, num_threads, device_id, pipelined=True, exec_async=True):
super(HybridPipe, self).__init__(batch_size,
num_threads,
device_id,
exec_pipelined=pipelined,
exec_async=exec_async)
self.input = ops.ExternalSource()
self.decode = ops.ImageDecoder(device="mixed", output_type=types.RGB)
self.resize = ops.Resize(device="gpu",
interp_type=types.INTERP_LINEAR)
self.cmnp = ops.CropMirrorNormalize(device="gpu",
dtype=types.FLOAT16,
crop=(224, 224),
mean=[128., 128., 128.],
std=[1., 1., 1.])
self.uniform = ops.random.Uniform(range=(0., 1.))
self.resize_uniform = ops.random.Uniform(range=(256., 480.))
self.mirror = ops.random.CoinFlip(probability=0.5)
def define_graph(self):
self.jpegs = self.input()
images = self.decode(self.jpegs)
resized = self.resize(images, resize_shorter=self.resize_uniform())
output = self.cmnp(resized, mirror=self.mirror(),
crop_pos_x=self.uniform(),
crop_pos_y=self.uniform())
return output
def iter_setup(self):
raw_data = make_batch(self.batch_size)
self.feed_input(self.jpegs, raw_data)
def run_benchmarks(PipeType, args):
print("Running Benchmarks For {}".format(PipeType.__name__))
for executor in args.executors:
pipelined = executor > 0
exec_async = executor > 1
for batch_size in args.batch_sizes:
for num_threads in args.thread_counts:
pipe = PipeType(batch_size, num_threads, 0, pipelined, exec_async)
pipe.build()
start_time = timer()
for i in range(args.num_iters):
pipe.run()
total_time = timer() - start_time
print("{}/{}/{}/{}: FPS={}"
.format(PipeType.__name__, executor, batch_size, num_threads,
float(batch_size * args.num_iters) / total_time))
def get_args():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--batch-sizes', default=[128],
help='Comma separated list of batch sizes to run')
parser.add_argument('--thread-counts', default=[1, 2, 3, 4],
help='Comma separated list of thread counts')
parser.add_argument('--executors', default=[2],
help='List of executors to run')
parser.add_argument('--num-iters', type=int, default=100,
help='Number of iterations to run')
return parser.parse_args()
def main():
args = get_args()
pipe_types = [C2Pipe, HybridPipe]
for PipeType in pipe_types:
run_benchmarks(PipeType, args)
if __name__ == '__main__':
main()
|
DALI-main
|
dali/benchmark/resnet50_bench.py
|
# Copyright (c) 2019, NVIDIA CORPORATION. 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
import nvidia.dali.ops as ops
import nvidia.dali.plugin.pytorch as dalitorch
import nvidia.dali.types as types
import os
import torch
from nvidia.dali.pipeline import Pipeline
from test_utils import get_dali_extra_path
test_data_root = get_dali_extra_path()
images_dir = os.path.join(test_data_root, 'db', 'single', 'jpeg')
DEVICE_ID = 0
BATCH_SIZE = 8
ITERS = 32
NUM_WORKERS = 6
class CommonPipeline(Pipeline):
def __init__(self, batch_size=BATCH_SIZE, num_threads=NUM_WORKERS, device_id=DEVICE_ID,
image_dir=images_dir):
super().__init__(batch_size, num_threads, device_id, exec_async=False, exec_pipelined=False)
self.input = ops.readers.File(file_root=image_dir)
self.decode = ops.decoders.Image(device='cpu', output_type=types.RGB)
def load(self):
jpegs, labels = self.input()
decoded = self.decode(jpegs)
return decoded, labels
class BasicPipeline(CommonPipeline):
def __init__(self, batch_size=BATCH_SIZE, num_threads=NUM_WORKERS, device_id=DEVICE_ID,
image_dir=images_dir):
super().__init__(batch_size, num_threads, device_id, image_dir)
def define_graph(self):
images, labels = self.load()
return images
class TorchPythonFunctionPipeline(CommonPipeline):
def __init__(self, function, device, bp=False, batch_size=BATCH_SIZE, num_threads=NUM_WORKERS,
device_id=DEVICE_ID, image_dir=images_dir):
super().__init__(batch_size, num_threads, device_id, image_dir)
self.device = device
self.torch_function = dalitorch.TorchPythonFunction(function=function, num_outputs=2,
device=device, batch_processing=bp)
def define_graph(self):
images, labels = self.load()
return self.torch_function(images if self.device == 'cpu' else images.gpu())
def torch_operation(tensor):
tensor_n = tensor.double() / 255
return tensor_n.sin(), tensor_n.cos()
def torch_batch_operation(tensors):
out = [torch_operation(t) for t in tensors]
return [p[0] for p in out], [p[1] for p in out]
def check_pytorch_operator(device):
pipe = BasicPipeline()
pt_pipe = TorchPythonFunctionPipeline(torch_operation, device)
pipe.build()
pt_pipe.build()
for it in range(ITERS):
preprocessed_output, = pipe.run()
output1, output2 = pt_pipe.run()
if device == 'gpu':
output1 = output1.as_cpu()
output2 = output2.as_cpu()
for i in range(len(output1)):
res1 = output1.at(i)
res2 = output2.at(i)
exp1_t, exp2_t = torch_operation(torch.from_numpy(preprocessed_output.at(i)))
assert numpy.allclose(res1, exp1_t.numpy())
assert numpy.allclose(res2, exp2_t.numpy())
def test_pytorch_operator():
for device in {'cpu', 'gpu'}:
yield check_pytorch_operator, device
def check_pytorch_operator_batch_processing(device):
pipe = BasicPipeline()
pt_pipe = TorchPythonFunctionPipeline(torch_batch_operation, device, True)
pipe.build()
pt_pipe.build()
for it in range(ITERS):
preprocessed_output, = pipe.run()
tensors = [torch.from_numpy(preprocessed_output.at(i)) for i in range(BATCH_SIZE)]
exp1, exp2 = torch_batch_operation(tensors)
output1, output2 = pt_pipe.run()
if device == 'gpu':
output1 = output1.as_cpu()
output2 = output2.as_cpu()
for i in range(len(output1)):
res1 = output1.at(i)
res2 = output2.at(i)
assert numpy.allclose(res1, exp1[i].numpy())
assert numpy.allclose(res2, exp2[i].numpy())
def test_pytorch_operator_batch_processing():
for device in {'cpu', 'gpu'}:
yield check_pytorch_operator_batch_processing, device
|
DALI-main
|
dali/test/python/test_pytorch_operator.py
|
# Copyright (c) 2021-2023, NVIDIA CORPORATION & AFFILIATES. 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 os
from nose.plugins.attrib import attr
from nvidia.dali import fn
from nvidia.dali import tensors
from nvidia.dali import types
from nvidia.dali.pipeline.experimental import pipeline_def
from nose_utils import raises
from test_utils import compare_pipelines, get_dali_extra_path
from nose_utils import assert_raises
from conditionals.test_pipeline_conditionals import (pred_gens,
_impl_against_split_merge,
_impl_dot_gpu,
_impl_arg_inputs_scoped_tracking,
_impl_arg_inputs_scoped_uninitialized,
_impl_generators,
_impl_uninitialized)
file_root = os.path.join(get_dali_extra_path(), 'db/single/jpeg')
@pipeline_def(batch_size=8, num_threads=3, device_id=0)
def rn50_pipeline_base():
rng = fn.random.coin_flip(probability=0.5, seed=47)
jpegs, labels = fn.readers.file(file_root=file_root, shard_id=0, num_shards=2)
images = fn.decoders.image(jpegs, device='mixed', output_type=types.RGB)
resized_images = fn.random_resized_crop(images, device="gpu", size=(224, 224), seed=27)
out_type = types.FLOAT16
output = fn.crop_mirror_normalize(resized_images.gpu(), mirror=rng, device="gpu",
dtype=out_type, crop=(224, 224),
mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
return rng, jpegs, labels, images, resized_images, output
def test_debug_pipeline_base():
pipe_standard = rn50_pipeline_base()
pipe_debug = rn50_pipeline_base(debug=True)
compare_pipelines(pipe_standard, pipe_debug, 8, 10)
@pipeline_def(batch_size=8, num_threads=3, device_id=0, debug=True)
def rn50_pipeline():
rng = fn.random.coin_flip(probability=0.5, seed=47)
print(f'rng: {rng.get().as_array()}')
tmp = rng ^ 1
print(f'rng xor: {tmp.get().as_array()}')
jpegs, labels = fn.readers.file(file_root=file_root, shard_id=0, num_shards=2)
if jpegs.get().is_dense_tensor():
print(f'jpegs: {jpegs.get().as_array()}')
else:
print('jpegs shapes:')
for j in jpegs.get():
print(j.shape())
print(f'labels: {labels.get().as_array()}')
images = fn.decoders.image(jpegs, device='mixed', output_type=types.RGB)
for i in images.get().as_cpu():
print(i)
for i in images.get():
print(i.shape())
images = fn.random_resized_crop(images, device="gpu", size=(224, 224), seed=27)
for i in images.get():
print(i.shape())
print(np.array(images.get().as_cpu()[0]))
images += 1
print(np.array(images.get().as_cpu()[0]))
out_type = types.FLOAT16
output = fn.crop_mirror_normalize(images.gpu(), mirror=rng, device="gpu", dtype=out_type,
crop=(224, 224), mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
return (output, labels.gpu())
def test_operations_on_debug_pipeline():
pipe = rn50_pipeline()
pipe.build()
pipe.run()
@pipeline_def(batch_size=8, num_threads=3, device_id=0)
def load_images_pipeline():
jpegs, labels = fn.readers.file(
file_root=file_root, shard_id=0, num_shards=2)
images = fn.decoders.image(jpegs, output_type=types.RGB)
return images, labels
@pipeline_def(batch_size=8, num_threads=3, device_id=0, debug=True)
def injection_pipeline(callback, device='cpu'):
rng = fn.random.coin_flip(probability=0.5, seed=47)
images = fn.random_resized_crop(callback(), device=device, size=(224, 224), seed=27)
out_type = types.FLOAT16
output = fn.crop_mirror_normalize(images.gpu(), mirror=rng, device="gpu", dtype=out_type,
crop=(224, 224), mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
return rng, images, output
@pipeline_def(batch_size=8, num_threads=3, device_id=0)
def injection_pipeline_standard(device='cpu'):
jpegs, _ = fn.readers.file(file_root=file_root, shard_id=0, num_shards=2)
images = fn.decoders.image(jpegs, output_type=types.RGB)
rng = fn.random.coin_flip(probability=0.5, seed=47)
if device == "gpu":
images = images.gpu()
images = fn.random_resized_crop(images, device=device, size=(224, 224), seed=27)
out_type = types.FLOAT16
output = fn.crop_mirror_normalize(images.gpu(), mirror=rng, device="gpu", dtype=out_type,
crop=(224, 224), mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
return rng, images, output
def _test_injection(device, name, transform, eps=1e-07):
pipe_load = load_images_pipeline()
pipe_load.build()
pipe_standard = injection_pipeline_standard(device)
pipe_debug = injection_pipeline(lambda: transform(pipe_load.run()[0]), device)
compare_pipelines(pipe_standard, pipe_debug, 8, 10, eps=eps)
def test_injection_numpy():
_test_injection('cpu', 'numpy array', lambda xs: [np.array(x) for x in xs])
@attr('mxnet')
def test_injection_mxnet():
import mxnet
_test_injection('cpu', 'mxnet array', lambda xs: [mxnet.nd.array(x, dtype='uint8') for x in xs])
@attr('pytorch')
def test_injection_torch():
import torch
yield _test_injection, 'cpu', 'torch cpu tensor', lambda xs: [
torch.tensor(np.array(x), device='cpu') for x in xs
]
yield _test_injection, 'gpu', 'torch gpu tensor', lambda xs: [
torch.tensor(np.array(x), device='cuda') for x in xs
]
@attr('cupy')
def test_injection_cupy():
import cupy
_test_injection('gpu', 'cupy array', lambda xs: [cupy.array(x) for x in xs])
def test_injection_dali_types():
yield _test_injection, 'gpu', 'list of TensorGPU', lambda xs: [x._as_gpu() for x in xs]
yield _test_injection, 'cpu', 'TensorListCPU', lambda xs: xs
yield _test_injection, 'gpu', 'TensorListGPU', lambda xs: xs._as_gpu()
@pipeline_def(batch_size=8, num_threads=3, device_id=0, debug=True)
def es_pipeline_debug():
images = fn.external_source(name='input')
labels = fn.external_source(name='labels')
rng = fn.random.coin_flip(probability=0.5, seed=47)
images = fn.random_resized_crop(images, size=(224, 224), seed=27)
out_type = types.FLOAT16
output = fn.crop_mirror_normalize(images.gpu(), mirror=rng, device="gpu", dtype=out_type,
crop=(224, 224), mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
return rng, images, output, labels
@pipeline_def(batch_size=8, num_threads=3, device_id=0)
def es_pipeline_standard():
jpegs, labels = fn.readers.file(file_root=file_root, shard_id=0, num_shards=2)
images = fn.decoders.image(jpegs, output_type=types.RGB)
rng = fn.random.coin_flip(probability=0.5, seed=47)
images = fn.random_resized_crop(images, size=(224, 224), seed=27)
out_type = types.FLOAT16
output = fn.crop_mirror_normalize(images.gpu(), mirror=rng, device="gpu", dtype=out_type,
crop=(224, 224), mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
return rng, images, output, labels
def test_external_source_debug_sample_pipeline():
n_iters = 10
prefetch_queue_depth = 2
pipe_load = load_images_pipeline()
pipe_standard = es_pipeline_standard(prefetch_queue_depth=prefetch_queue_depth)
pipe_debug = es_pipeline_debug(prefetch_queue_depth=prefetch_queue_depth)
pipe_load.build()
pipe_debug.build()
# Call feed_input `prefetch_queue_depth` extra times to avoid issues with
# missing batches near the end of the epoch caused by prefetching
for _ in range(n_iters + prefetch_queue_depth):
images, labels = pipe_load.run()
pipe_debug.feed_input('input', [np.array(t) for t in images])
pipe_debug.feed_input('labels', np.array(labels.as_tensor()))
compare_pipelines(pipe_standard, pipe_debug, 8, 10)
@pipeline_def(batch_size=8, num_threads=3, device_id=0)
def es_pipeline(source, batch):
if source is not None:
return fn.external_source(source, batch=batch, cycle=(not batch))
else:
return fn.external_source(name='input')
def _test_external_source_debug(source, batch):
n_iters = 8
prefetch_queue_depth = 2
pipe_debug = es_pipeline(source, batch, prefetch_queue_depth=prefetch_queue_depth, debug=True)
pipe_standard = es_pipeline(source, batch, prefetch_queue_depth=prefetch_queue_depth)
pipe_debug.build()
pipe_standard.build()
if source is None:
# Call feed_input `prefetch_queue_depth` extra times to avoid issues with
# missing batches near the end of the epoch caused by prefetching
for _ in range(n_iters + prefetch_queue_depth):
x = np.random.rand(8, 5, 1)
pipe_debug.feed_input('input', x)
pipe_standard.feed_input('input', x)
compare_pipelines(pipe_standard, pipe_debug, 8, n_iters)
def test_external_source_debug():
for source in [np.random.rand(8, 8, 1), None]:
for batch in [True, False]:
yield _test_external_source_debug, source, batch
@pipeline_def(num_threads=3, device_id=0)
def es_pipeline_multiple_outputs(source, num_outputs):
out1, out2, out3 = fn.external_source(source, num_outputs=num_outputs)
return out1, out2, out3
def test_external_source_debug_multiple_outputs():
n_iters = 13
batch_size = 8
num_outputs = 3
data = [[np.random.rand(batch_size, 120, 120, 3)] * num_outputs] * n_iters
pipe_debug = es_pipeline_multiple_outputs(data, num_outputs, batch_size=batch_size, debug=True)
pipe_standard = es_pipeline_multiple_outputs(data, num_outputs, batch_size=batch_size)
compare_pipelines(pipe_standard, pipe_debug, 8, n_iters)
@pipeline_def(batch_size=8, num_threads=3, device_id=0, debug=True)
def order_change_pipeline():
if order_change_pipeline.change:
rng = 0
else:
order_change_pipeline.change = True
rng = fn.random.coin_flip(probability=0.5, seed=47)
jpegs, labels = fn.readers.file(file_root=file_root, shard_id=0, num_shards=2)
images = fn.decoders.image(jpegs, device='mixed', output_type=types.RGB)
resized_images = fn.random_resized_crop(images, device="gpu", size=(224, 224), seed=27)
out_type = types.FLOAT16
output = fn.crop_mirror_normalize(resized_images.gpu(), mirror=rng, device="gpu",
dtype=out_type, crop=(224, 224),
mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
return rng, jpegs, labels, images, resized_images, output
@raises(RuntimeError, glob=('Unexpected operator *. Debug mode does not support'
' changing the order of operators executed within the pipeline.'))
def test_operators_order_change():
order_change_pipeline.change = False
pipe = order_change_pipeline()
pipe.build()
pipe.run()
pipe.run()
@pipeline_def(batch_size=8, num_threads=3, device_id=0, debug=True)
def inputs_len_change():
input = [np.zeros(1)] * 8
if inputs_len_change.change:
inputs_len_change.change = False
inputs = [input]
else:
inputs = [input] * 2
return fn.cat(*inputs)
@raises(RuntimeError, glob=('Trying to use operator * with different number of inputs than when'
' it was built.'))
def test_inputs_len_change():
inputs_len_change.change = True
pipe = inputs_len_change()
pipe.build()
pipe.run()
pipe.run()
@pipeline_def(batch_size=8, num_threads=3, device_id=0, debug=True)
def kwargs_len_change():
input = [np.zeros(1)] * 8
inputs = [input] * 2
kwargs = {}
if kwargs_len_change.change:
kwargs_len_change.change = False
kwargs['axis'] = 0
return fn.cat(*inputs, **kwargs)
@raises(RuntimeError, glob=('Trying to use operator * with different number of keyword arguments'
' than when it was built.'))
def test_kwargs_len_change():
kwargs_len_change.change = True
pipe = kwargs_len_change()
pipe.build()
pipe.run()
pipe.run()
@pipeline_def(batch_size=8, num_threads=3, device_id=0, debug=True)
def inputs_batch_change():
if inputs_batch_change.change:
inputs_batch_change.change = False
input = np.zeros(8)
else:
input = [np.zeros(1)] * 8
return fn.random.coin_flip(input)
@raises(RuntimeError, glob='Input * for operator * is')
def test_inputs_batch_change():
inputs_batch_change.change = True
pipe = inputs_batch_change()
pipe.build()
pipe.run()
pipe.run()
@pipeline_def(batch_size=8, num_threads=3, device_id=0, debug=True)
def kwargs_batch_change():
kwargs = {}
if kwargs_batch_change.change:
kwargs_batch_change.change = False
kwargs['probability'] = 0.75
else:
kwargs['probability'] = [np.zeros(1)] * 8
return fn.random.coin_flip(**kwargs)
@raises(RuntimeError, glob='Argument * for operator * is')
def test_kwargs_batch_change():
kwargs_batch_change.change = True
pipe = kwargs_batch_change()
pipe.build()
pipe.run()
pipe.run()
@pipeline_def
def init_config_pipeline():
jpegs, labels = fn.readers.file(file_root=file_root, shard_id=0, num_shards=2)
return jpegs, labels
def test_init_config_pipeline():
pipe_standard = init_config_pipeline(batch_size=8, num_threads=3, device_id=0)
pipe_debug = init_config_pipeline(batch_size=8, num_threads=3, device_id=0, debug=True)
compare_pipelines(pipe_standard, pipe_debug, 8, 10)
@pipeline_def(batch_size=8, num_threads=3, device_id=0, seed=47, debug=True)
def shape_pipeline(output_device):
jpegs, _ = fn.readers.file(file_root=file_root, shard_id=0, num_shards=2)
images = fn.decoders.image(jpegs, device=output_device, output_type=types.RGB)
assert images.shape() == [tuple(im.shape()) for im in images.get()]
return images
def _test_shape_pipeline(device):
pipe = shape_pipeline(device)
pipe.build()
res, = pipe.run()
# Test TensorList.shape() directly.
assert res.shape() == [tuple(im.shape()) for im in res]
def test_shape_pipeline():
for device in ['cpu', 'mixed']:
yield _test_shape_pipeline, device
@pipeline_def(batch_size=8, num_threads=3, device_id=0, seed=47, debug=True)
def seed_pipeline():
coin_flip = fn.random.coin_flip()
normal = fn.random.normal()
uniform = fn.random.uniform()
batch_permutation = fn.batch_permutation()
return coin_flip, normal, uniform, batch_permutation
def test_seed_generation():
pipe1 = seed_pipeline()
pipe2 = seed_pipeline()
compare_pipelines(pipe1, pipe2, 8, 10)
@pipeline_def(batch_size=8, num_threads=3, device_id=0, seed=47, debug=True)
def seed_rn50_pipeline_base():
rng = fn.random.coin_flip(probability=0.5)
jpegs, labels = fn.readers.file(file_root=file_root, shard_id=0, num_shards=2,
random_shuffle=True)
images = fn.decoders.image(jpegs, device='mixed', output_type=types.RGB)
resized_images = fn.random_resized_crop(images, device="gpu", size=(224, 224))
out_type = types.FLOAT16
output = fn.crop_mirror_normalize(resized_images.gpu(), mirror=rng, device="gpu",
dtype=out_type, crop=(224, 224),
mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
return rng, jpegs, labels, images, resized_images, output
def test_seed_generation_base():
pipe1 = seed_rn50_pipeline_base()
pipe2 = seed_rn50_pipeline_base()
compare_pipelines(pipe1, pipe2, 8, 10)
@pipeline_def(batch_size=8, num_threads=3, device_id=0, seed=47, debug=True)
def device_change_rn50_pipeline_base():
jpegs, labels = fn.readers.file(
file_root=file_root, shard_id=0, num_shards=2, random_shuffle=True)
images = fn.decoders.image(jpegs, output_type=types.RGB)
if device_change_rn50_pipeline_base.change:
images = images.gpu()
output = fn.random_resized_crop(images, size=(224, 224))
return labels, output
@raises(RuntimeError, glob='Input * for operator * is on * but was on * when created.')
def test_device_change():
pipe = device_change_rn50_pipeline_base()
pipe.build()
device_change_rn50_pipeline_base.change = True
pipe.run()
device_change_rn50_pipeline_base.change = False
pipe.run()
@pipeline_def(batch_size=8, num_threads=3, device_id=0, seed=47, debug=True)
def cpu_after_gpu_pipeline():
jpegs, labels = fn.readers.file(
file_root=file_root, shard_id=0, num_shards=2, random_shuffle=True)
images = fn.decoders.image(jpegs, output_type=types.RGB, device='mixed')
output = fn.random_resized_crop(images, size=(224, 224), device='cpu')
return labels, output
@raises(RuntimeError, glob='Cannot call * operator * with * input *')
def test_cpu_operator_after_gpu():
pipe = cpu_after_gpu_pipeline()
pipe.build()
pipe.run()
@pipeline_def(batch_size=8, num_threads=3, device_id=0)
def input_sets_stateful_op_pipeline():
set_size = 5
jpegs = [fn.readers.file(file_root=file_root, seed=42, random_shuffle=True)[0]
for _ in range(set_size)]
images = fn.decoders.image(jpegs, seed=42)
output = fn.random_resized_crop(images, size=(224, 224), seed=42)
assert len(output) == set_size
return tuple(output)
def test_input_sets():
pipe_standard = input_sets_stateful_op_pipeline()
pipe_debug = input_sets_stateful_op_pipeline(debug=True)
compare_pipelines(pipe_standard, pipe_debug, 8, 10)
@pipeline_def(batch_size=8, num_threads=3, device_id=0, debug=True)
def incorrect_input_sets_pipeline():
jpegs, _ = fn.readers.file(file_root=file_root, seed=42, random_shuffle=True)
images = fn.decoders.image(jpegs, seed=42)
output = fn.cat([images, images, images], [images, images])
return tuple(output)
@raises(ValueError, glob=("All argument lists for Multiple Input Sets used with operator"
" 'cat' must have the same length."))
def test_incorrect_input_sets():
pipe = incorrect_input_sets_pipeline()
pipe.build()
pipe.run()
@pipeline_def(batch_size=8, num_threads=3, device_id=0)
def multiple_input_sets_pipeline():
jpegs = [fn.readers.file(file_root=file_root, seed=42, random_shuffle=True)[0]
for _ in range(6)]
images = fn.decoders.image(jpegs, seed=42)
cropped_images = fn.random_resized_crop(images, size=(224, 224), seed=42)
output = fn.cat(cropped_images[:3], cropped_images[3:])
return tuple(output)
def test_multiple_input_sets():
pipe_standard = multiple_input_sets_pipeline()
pipe_debug = multiple_input_sets_pipeline(debug=True)
compare_pipelines(pipe_standard, pipe_debug, 8, 10)
@pipeline_def(batch_size=8, num_threads=3, device_id=0, seed=47, debug=True)
def variable_batch_size_from_external_source_pipeline(src_data):
images = fn.external_source(src_data)
output = fn.random_resized_crop(images, size=(32, 32))
return output,
def test_variable_batch_size_from_external_source():
batch_sizes = [3, 6, 7, 8]
src_data = [np.zeros((batch_size, 64, 64, 3), dtype=np.uint8) for batch_size in batch_sizes]
pipe = variable_batch_size_from_external_source_pipeline(src_data)
pipe.build()
for batch_size in batch_sizes:
output, = pipe.run()
assert len(output) == batch_size
@pipeline_def(batch_size=8, num_threads=3, device_id=0, seed=47, debug=True)
def incorrect_variable_batch_size_from_es_pipeline():
rng = fn.random.coin_flip(probability=0.5)
src_data = np.zeros((1, 6, 64, 64, 3), dtype=np.uint8)
images = fn.external_source(src_data)
return images, rng
@raises(RuntimeError, glob=('Batch size must be uniform across an iteration.'
' External Source operator returned batch size*'))
def test_incorrect_variable_batch_size_from_es():
pipe = incorrect_variable_batch_size_from_es_pipeline()
pipe.build()
pipe.run()
@pipeline_def(batch_size=8, num_threads=3, device_id=0, seed=47, debug=True)
def incorrect_variable_batch_size_inside_es_pipeline():
src_data = [[[np.ones((120, 120, 3), dtype=np.uint8)] * 8,
[np.ones((120, 120, 3), dtype=np.float32)] * 6]]
out1, out2 = fn.external_source(source=src_data, num_outputs=2,
dtype=[types.DALIDataType.UINT8, types.DALIDataType.FLOAT])
return out1, out2
@raises(RuntimeError, glob='External source must return outputs with consistent batch size.*')
def test_incorrect_variable_batch_size_inside_es():
pipe = incorrect_variable_batch_size_inside_es_pipeline()
pipe.build()
pipe.run()
@pipeline_def(batch_size=8, num_threads=3, device_id=0, seed=47, debug=True)
def incorrect_variable_batch_size_pipeline():
jpegs, labels = fn.readers.file(file_root=file_root)
images = fn.decoders.image(jpegs)
images = [images.get()[i] for i in range(6)]
output = fn.random_resized_crop(images, size=(224, 224))
return labels, output
@raises(RuntimeError, glob='Batch size must be uniform across an iteration. Input*')
def test_variable_batch_size():
pipe = incorrect_variable_batch_size_pipeline()
pipe.build()
pipe.run()
@pipeline_def(batch_size=8, num_threads=3, device_id=0, seed=47, debug=True)
def unused_arg_es_pipeline(kwargs):
return fn.external_source(np.zeros((2, 8, 1)), **kwargs)
def _test_es_unused_args(kwargs):
pipe = unused_arg_es_pipeline(kwargs)
pipe.build()
pipe.run()
def test_external_source_unused_args():
kwargs_list = [{'parallel': True}, {'foo': 123, 'bar': 'BAR'}]
for kwargs in kwargs_list:
yield _test_es_unused_args, kwargs
@pipeline_def(batch_size=8, num_threads=3, device_id=0, seed=47, debug=True)
def es_device_change_pipeline(source, device):
return fn.external_source(source=source, device=device)
def _test_es_device_change(source, device):
pipe = es_device_change_pipeline(source, device)
pipe.build()
res, = pipe.run()
assert device in str(type(res)).lower()
def test_es_device_change():
cpu_data = np.zeros((8, 1))
gpu_data = tensors.TensorListCPU(cpu_data)._as_gpu()
for data, device in zip([gpu_data], ['cpu']):
yield _test_es_device_change, data, device
@pipeline_def(batch_size=8, num_threads=3, device_id=0, seed=47, debug=True)
def nan_check_pipeline(source):
return fn.constant(fdata=next(source))
def _test_nan_check(values):
pipe = nan_check_pipeline(iter(values))
pipe.build()
for _ in range(2):
pipe.run()
def test_nan_check():
err_msg = "Argument 'fdata' for operator 'constant' unexpectedly changed value from*"
for values in [[np.nan, 1], [1, np.nan]]:
yield raises(RuntimeError, glob=err_msg)(_test_nan_check), values
for values in [[1, 1], [np.nan, np.nan]]:
yield _test_nan_check, values
def test_debug_pipeline_conditionals():
@pipeline_def(batch_size=8, num_threads=3, device_id=0, enable_conditionals=False)
def pipeline_split_merge():
pred = fn.random.coin_flip(seed=42, dtype=types.BOOL)
input = fn.constant(idata=[10], shape=[])
true, false = fn._conditional.split(input, predicate=pred)
output_true = true + 2
output_false = false + 100
output = fn._conditional.merge(output_true, output_false, predicate=pred)
print(
f"Pred: {pred}, Output if: {output_true}, Output else: {output_false}, Output {output}")
return pred, output
@pipeline_def(batch_size=8, num_threads=3, device_id=0, enable_conditionals=True)
def pipeline_cond():
pred = fn.random.coin_flip(seed=42, dtype=types.BOOL)
input = fn.constant(idata=[10], shape=[])
print(f"Pred: {pred}")
if pred:
output = input + 2
print(f"Output if: {output}")
else:
output = input + 100
print(f"Output else: {output}")
print(f"Output: {output}")
return pred, output
pipe_standard = pipeline_split_merge(debug=True)
pipe_standard.build()
pipe_cond = pipeline_cond(debug=True)
pipe_cond.build()
compare_pipelines(pipe_standard, pipe_cond, 8, 5)
def test_debug_pipeline_conditional_repeated_op():
@pipeline_def(batch_size=8, num_threads=3, device_id=0, enable_conditionals=False)
def pipeline_split_merge():
pred = fn.random.coin_flip(seed=42, dtype=types.BOOL)
rng1 = fn.random.coin_flip(seed=1)
rng2 = fn.random.coin_flip(seed=2)
true, _ = fn._conditional.split(rng1, predicate=pred)
_, false = fn._conditional.split(rng2, predicate=pred)
output_true = true + 20
output_false = false + 10
output = fn._conditional.merge(output_true, output_false, predicate=pred)
print(
f"Pred: {pred}, Output if: {output_true}, Output else: {output_false}, Output {output}")
return pred, output
@pipeline_def(batch_size=8, num_threads=3, device_id=0, enable_conditionals=True)
def pipeline_cond():
pred = fn.random.coin_flip(seed=42, dtype=types.BOOL)
rng1 = fn.random.coin_flip(seed=1)
rng2 = fn.random.coin_flip(seed=2)
print(f"Pred: {pred}")
if pred:
output = rng1 + 20
print(f"Output if: {output}")
else:
output = rng2 + 10
print(f"Output else: {output}")
print(f"Output: {output}")
return pred, output
pipe_standard = pipeline_split_merge(debug=True)
pipe_standard.build()
pipe_cond = pipeline_cond(debug=True)
pipe_cond.build()
compare_pipelines(pipe_standard, pipe_cond, 8, 5)
def test_against_split_merge():
for base_debug, conditional_debug in [(True, False), (False, True), (True, True)]:
yield _impl_against_split_merge, {'debug': base_debug}, {'debug': conditional_debug}
def test_dot_gpu():
for base_debug, conditional_debug in [(True, False), (False, True), (True, True)]:
yield _impl_dot_gpu, {'debug': base_debug}, {'debug': conditional_debug}
def test_arg_inputs_scoped_tracking():
for global_debug, scoped_debug in [(True, False), (False, True), (True, True)]:
yield _impl_arg_inputs_scoped_tracking, {'debug': global_debug}, {'debug': scoped_debug}
def test_arg_inputs_scoped_uninitialized():
yield _impl_arg_inputs_scoped_uninitialized, {'debug': True}
def test_generators():
for pred in pred_gens[:-1]:
for base_debug, conditional_debug in [(True, False), (False, True), (True, True)]:
yield _impl_generators, pred, {'debug': base_debug}, {'debug': conditional_debug}
def test_uninitialized():
yield _impl_uninitialized, {'debug': True}
def test_debug_pipeline_conditional_without_data_node():
@pipeline_def(batch_size=8, num_threads=3, device_id=0, enable_conditionals=True)
def pipeline_cond():
pred = fn.random.coin_flip(seed=42, dtype=types.BOOL)
rng1 = fn.random.coin_flip(seed=1)
if pred:
output = fn.copy(rng1.get())
else:
output = rng1 + 10
return pred, output
with assert_raises(
ValueError, glob=("Debug mode with conditional execution (when "
"`enable_conditionals=True`) doesn't allow for modification of"
" operator outputs by libraries other than DALI or using the"
" TensorLists extracted via `.get()` as inputs."
" Expected `DataNodeDebug` as an input, got * at input *.")):
pipe_cond = pipeline_cond(debug=True)
pipe_cond.build()
pipe_cond.run()
|
DALI-main
|
dali/test/python/test_pipeline_debug.py
|
# Copyright (c) 2020-2021, NVIDIA CORPORATION & AFFILIATES. 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 nvidia.dali.ops as ops
from nvidia.dali.pipeline import Pipeline
import test_utils
from nose_utils import raises
class TestPipeline(Pipeline):
def __init__(self, batch_size, num_threads, shape):
super().__init__(batch_size, num_threads, device_id=0, seed=42)
self.cf = ops.random.Uniform(device="cpu", shape=shape, seed=42)
def define_graph(self):
cf = self.cf()
return cf
def check_deserialization(batch_size, num_threads, shape):
ref_pipe = TestPipeline(batch_size=batch_size, num_threads=num_threads, shape=shape)
serialized = ref_pipe.serialize()
test_pipe = Pipeline.deserialize(serialized)
test_utils.compare_pipelines(ref_pipe, test_pipe, batch_size=batch_size, N_iterations=3)
def check_deserialization_with_params(batch_size, num_threads, shape):
init_pipe = TestPipeline(batch_size=batch_size, num_threads=num_threads, shape=shape)
serialized = init_pipe.serialize()
ref_pipe = TestPipeline(batch_size=batch_size ** 2, num_threads=num_threads + 1, shape=shape)
test_pipe = Pipeline.deserialize(serialized, batch_size=batch_size ** 2,
num_threads=num_threads + 1)
test_utils.compare_pipelines(ref_pipe, test_pipe, batch_size=batch_size ** 2, N_iterations=3)
def check_deserialization_from_file(batch_size, num_threads, shape):
filename = "/tmp/dali.serialize.pipeline.test"
ref_pipe = TestPipeline(batch_size=batch_size, num_threads=num_threads, shape=shape)
ref_pipe.serialize(filename=filename)
test_pipe = Pipeline.deserialize(filename=filename)
test_utils.compare_pipelines(ref_pipe, test_pipe, batch_size=batch_size, N_iterations=3)
def check_deserialization_from_file_with_params(batch_size, num_threads, shape):
filename = "/tmp/dali.serialize.pipeline.test"
init_pipe = TestPipeline(batch_size=batch_size, num_threads=num_threads, shape=shape)
init_pipe.serialize(filename=filename)
ref_pipe = TestPipeline(batch_size=batch_size ** 2, num_threads=num_threads + 1, shape=shape)
test_pipe = Pipeline.deserialize(filename=filename, batch_size=batch_size ** 2,
num_threads=num_threads + 1)
test_utils.compare_pipelines(ref_pipe, test_pipe, batch_size=batch_size ** 2, N_iterations=3)
def test_deserialization():
batch_sizes = [3]
nums_thread = [1]
shapes = [[6], [2, 5], [3, 1, 6]]
for bs in batch_sizes:
for nt in nums_thread:
for sh in shapes:
yield check_deserialization, bs, nt, sh
def test_deserialization_with_params():
batch_sizes = [3]
nums_thread = [1]
shapes = [[6], [2, 5], [3, 1, 6]]
for bs in batch_sizes:
for nt in nums_thread:
for sh in shapes:
yield check_deserialization_with_params, bs, nt, sh
def test_deserialization_from_file():
batch_sizes = [3]
nums_thread = [1]
shapes = [[6], [2, 5], [3, 1, 6]]
for bs in batch_sizes:
for nt in nums_thread:
for sh in shapes:
yield check_deserialization, bs, nt, sh
def test_deserialization_from_file_with_params():
batch_sizes = [3]
nums_thread = [1]
shapes = [[6], [2, 5], [3, 1, 6]]
for bs in batch_sizes:
for nt in nums_thread:
for sh in shapes:
yield check_deserialization_with_params, bs, nt, sh
@raises(ValueError,
"serialized_pipeline and filename arguments are mutually exclusive. Precisely one of them should be defined.") # noqa: E501
def test_incorrect_invocation_mutually_exclusive_params():
filename = "/tmp/dali.serialize.pipeline.test"
pipe = TestPipeline(batch_size=3, num_threads=1, shape=[666])
serialized = pipe.serialize(filename=filename)
Pipeline.deserialize(serialized_pipeline=serialized, filename=filename)
@raises(ValueError,
"serialized_pipeline and filename arguments are mutually exclusive. Precisely one of them should be defined.") # noqa: E501
def test_incorrect_invocation_no_params():
Pipeline.deserialize()
|
DALI-main
|
dali/test/python/test_deserialization.py
|
# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. 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 nvidia.dali as dali
import nvidia.dali.fn as fn
from nvidia.dali.pipeline import pipeline_def
from test_utils import compare_pipelines
from nose2.tools import params
from nose_utils import assert_raises
# Test configuration
batch_size = 8
test_data_shape = [25, 15, 3]
test_data_layout = "HWC"
def tensor_list_to_array(tensor_list):
if isinstance(tensor_list, dali.backend_impl.TensorListGPU):
tensor_list = tensor_list.as_cpu()
return tensor_list.as_array()
# Check whether a given pipeline is stateless
def check_is_pipeline_stateless(pipeline_factory, iterations=10):
args = {
'batch_size': batch_size,
'num_threads': 4,
'device_id': 0,
'exec_async': True,
'exec_pipelined': True,
}
pipe = pipeline_factory(**args)
pipe.build()
for _ in range(iterations):
pipe.run()
# Compare a pipeline that was already used with a fresh one
compare_pipelines(pipe, pipeline_factory(**args), batch_size, iterations)
# Provides the same random batch each time
class RandomBatch:
def __init__(self):
rng = np.random.default_rng(1234)
self.batch = [rng.integers(255, size=test_data_shape, dtype=np.uint8)
for _ in range(batch_size)]
def __call__(self):
return self.batch
def move_to(tensor, device):
return tensor.gpu() if device == 'gpu' else tensor
def check_single_input(op, device, **kwargs):
@pipeline_def
def pipeline_factory():
data = fn.external_source(source=RandomBatch(), layout=test_data_layout, batch=True)
return op(move_to(data, device), device=device, **kwargs)
check_is_pipeline_stateless(pipeline_factory)
def check_no_input(op, device, **kwargs):
@pipeline_def
def pipeline_factory():
return op(device=device, **kwargs)
check_is_pipeline_stateless(pipeline_factory)
@params('cpu', 'gpu')
def test_stateful(device):
assert_raises(
AssertionError, check_single_input, fn.random.coin_flip, device,
glob='Mean error: *, Min error: *, Max error: *'
'Total error count: *, Tensor size: *'
'Index in batch: 0')
@params('cpu', 'gpu')
def test_rotate_stateless(device):
check_single_input(fn.rotate, device, angle=40)
@params('cpu', 'gpu')
def test_resize_stateless(device):
check_single_input(fn.resize, device, resize_x=50, resize_y=50)
@params('cpu', 'gpu')
def test_flip_stateless(device):
check_single_input(fn.flip, device)
@params('cpu', 'gpu')
def test_crop_mirror_normalize_stateless(device):
check_single_input(fn.crop_mirror_normalize, device)
@params('cpu', 'gpu')
def test_warp_affine_stateless(device):
check_single_input(fn.warp_affine, device, matrix=(0.1, 0.9, 10, 0.8, -0.2, -20))
@params('cpu', 'gpu')
def test_saturation_stateless(device):
check_single_input(fn.saturation, device)
@params('cpu', 'gpu')
def test_reductions_min_stateless(device):
check_single_input(fn.reductions.min, device)
@params('cpu', 'gpu')
def test_reductions_max_stateless(device):
check_single_input(fn.reductions.max, device)
@params('cpu', 'gpu')
def test_reductions_sum_stateless(device):
check_single_input(fn.reductions.sum, device)
@params('cpu', 'gpu')
def test_equalize_stateless(device):
check_single_input(fn.experimental.equalize, device)
def test_transforms_crop_stateless():
check_no_input(fn.transforms.crop, 'cpu')
def test_transforms_rotation_stateless():
check_no_input(fn.transforms.rotation, 'cpu', angle=35)
def test_transforms_shear_stateless():
check_no_input(fn.transforms.shear, 'cpu', shear=(2, 2))
def test_transforms_scale_stateless():
check_no_input(fn.transforms.scale, 'cpu', scale=(3, 2))
def test_transforms_translation_stateless():
check_no_input(fn.transforms.translation, 'cpu', offset=(4, 3))
@params('cpu', 'gpu')
def test_cast_like_stateless(device):
@pipeline_def
def pipeline_factory():
return fn.cast_like(
np.array([1, 2, 3], dtype=np.int32),
np.array([1.0], dtype=np.float32),
device=device)
check_is_pipeline_stateless(pipeline_factory)
def arithm_ops_outputs(data):
return (data * 2,
data + 2,
data - 2,
data / 2,
data // 2,
data ** 2,
data == 2,
data != 2,
data < 2,
data <= 2,
data > 2,
data >= 2,
data & 2,
data | 2,
data ^ 2)
@params('cpu', 'gpu')
def test_arithm_ops_stateless_cpu(device):
@pipeline_def
def pipeline_factory():
data = fn.external_source(source=RandomBatch(), layout="HWC")
return arithm_ops_outputs(move_to(data, device))
check_is_pipeline_stateless(pipeline_factory)
|
DALI-main
|
dali/test/python/test_dali_stateless_operators.py
|
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. 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
from scipy.signal import convolve2d
# note, it uses opencv's convention of naming the pattern after 2x2 tile
# that starts in the second row and column of the sensors' matrix
class BayerPattern:
BGGR = 0
GBRG = 1
GRBG = 2
RGGB = 3
bayer_patterns = [BayerPattern.BGGR, BayerPattern.GBRG, BayerPattern.GRBG, BayerPattern.RGGB]
def blue_position(pattern):
assert 0 <= pattern <= 3
return pattern // 2, pattern % 2
def blue_position2pattern(blue_position):
y, x = blue_position
assert 0 <= x <= 1 and 0 <= y <= 1
return 2 * y + x
def rgb_bayer_masks(img_shape, pattern):
h, w = img_shape
assert h % 2 == 0 and w % 2 == 0, f"h: {h}, w: {w}"
assert 0 <= pattern <= 3
def sensor_matrix_00_is_green(pattern):
return pattern in (BayerPattern.GRBG, BayerPattern.GBRG)
def red_is_in_the_first_row(pattern):
return pattern in (BayerPattern.BGGR, BayerPattern.GBRG)
def vec(n, mod=2):
return np.arange(0, n, dtype=np.uint8) % mod
if sensor_matrix_00_is_green(pattern):
top_right_mask = np.outer(1 - vec(h), vec(w))
bottom_left_mask = np.outer(vec(h), 1 - vec(w))
green = 1 - top_right_mask - bottom_left_mask
if red_is_in_the_first_row(pattern):
return top_right_mask, green, bottom_left_mask
return bottom_left_mask, green, top_right_mask
else:
top_left_mask = np.outer(1 - vec(h), 1 - vec(w))
bottom_right_mask = np.outer(vec(h), vec(w))
green = 1 - top_left_mask - bottom_right_mask
if red_is_in_the_first_row(pattern):
return top_left_mask, green, bottom_right_mask
return bottom_right_mask, green, top_left_mask
def rgb2bayer(img, pattern):
h, w, c = img.shape
assert c == 3
h = h // 2 * 2
w = w // 2 * 2
r, g, b = rgb_bayer_masks((h, w), pattern)
return img[:h, :w, 0] * r + img[:h, :w, 1] * g + img[:h, :w, 2] * b
def rgb2bayer_seq(seq, patterns):
f, h, w, c = seq.shape
assert f == len(patterns)
assert c == 3
h = h // 2 * 2
w = w // 2 * 2
bayer_masks = {pattern: rgb_bayer_masks((h, w), pattern) for pattern in bayer_patterns}
seq_masks = [bayer_masks[pattern] for pattern in patterns]
reds, greens, blues = [np.stack(channel) for channel in zip(*seq_masks)]
return seq[:, :h, :w, 0] * reds + seq[:, :h, :w, 1] * greens + seq[:, :h, :w, 2] * blues
def conv2d_border101(img, filt):
r, s = filt.shape
assert r % 2 == 1 and s % 2 == 1
padded = np.pad(img, ((r // 2, r // 2), (s // 2, s // 2)), "reflect")
return convolve2d(padded, filt, mode="valid")
def conv2d_border101_seq(seq, filt):
r, s = filt.shape
assert r % 2 == 1 and s % 2 == 1
padded = np.pad(seq, ((0, 0), (r // 2, r // 2), (s // 2, s // 2)), "reflect")
debayered_frames = [convolve2d(frame, filt, mode="valid") for frame in padded]
return np.stack(debayered_frames)
def debayer_bilinear_npp_masks(img, masks):
"""
Computes the "bilinear with chroma correction for green channel" as
defined by the NPP.
"""
in_dtype = img.dtype
ndim = len(img.shape)
assert ndim in (2, 3)
is_seq = ndim == 3
conv = conv2d_border101 if not is_seq else conv2d_border101_seq
red_mask, green_mask, blue_mask = masks
red_signal = img * red_mask
green_signal = img * green_mask
blue_signal = img * blue_mask
# When inferring red color for blue or green base, there are either
# four red base neigbours at four corners or two base neigbours in
# x or y axis. The blue color case is analogous.
rb_filter = np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]], dtype=np.int32)
green_x_filter = np.array([[1, 0, 1]], dtype=np.int32)
green_y_filter = green_x_filter.transpose()
green_filter = np.array([[0, 1, 0], [1, 4, 1], [0, 1, 0]], dtype=np.int32)
red = conv(red_signal, rb_filter) // 4
blue = conv(blue_signal, rb_filter) // 4
green_bilinear = conv(green_signal, green_filter) // 4
green_x = conv(green_signal, green_x_filter) // 2
green_y = conv(green_signal, green_y_filter) // 2
def green_with_chroma_correlation(color_signal):
# For red and blue based positions, there are always four
# green neighbours (y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1).
# NPP does not simply average 4 of them to get green intensity.
# Instead, it averages only two in either y or x axis as explained in
# https://docs.nvidia.com/cuda/npp/group__image__color__debayer.html
# I.e. the axis is chosen by looking at:
# * abs(color(x, y), avg(color(y - 2, x), color(y + 2, x))) and
# * abs(color(x, y), avg(color(y, x - 2), color(y, x - 2)))
# and choosing the axis where the difference is smaller.
# In other words, if we are inferring green color for blue(red)-based
# position we check in which axis the blue(red) intensity changes less
# and pick that axis.
diff_filter_x = np.array([[1, 0, 0, 0, 1]], dtype=np.int32)
diff_filter_y = diff_filter_x.transpose()
# First compute the average, then the difference. Doing it with a single
# conv yields different results (and as this servers as a mask,
# it results in substantial differences in the end)
x_avg = conv(color_signal, diff_filter_x) // 2
y_avg = conv(color_signal, diff_filter_y) // 2
diff_x = np.abs(color_signal - x_avg)
diff_y = np.abs(color_signal - y_avg)
return diff_x < diff_y, diff_x > diff_y
pick_x_red_based, pick_y_red_based = green_with_chroma_correlation(red_signal)
pick_x_blue_based, pick_y_blue_based = green_with_chroma_correlation(blue_signal)
pick_x = pick_x_red_based + pick_x_blue_based
pick_y = pick_y_red_based + pick_y_blue_based
green = pick_x * green_x + pick_y * green_y + (1 - pick_x - pick_y) * green_bilinear
return np.stack([red, green, blue], axis=ndim).astype(in_dtype)
def debayer_bilinear_npp_pattern(img, pattern):
h, w = img.shape
masks = rgb_bayer_masks((h, w), pattern)
return debayer_bilinear_npp_masks(img, masks)
def debayer_bilinear_npp_pattern_seq(seq, patterns):
f, h, w = seq.shape
assert f == len(patterns)
bayer_masks = {pattern: rgb_bayer_masks((h, w), pattern) for pattern in bayer_patterns}
seq_masks = [bayer_masks[pattern] for pattern in patterns]
reds, greens, blues = [np.stack(channel) for channel in zip(*seq_masks)]
return debayer_bilinear_npp_masks(seq, (reds, greens, blues))
|
DALI-main
|
dali/test/python/debayer_test_utils.py
|
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. 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 torch
from torch.multiprocessing import Process
# we need this import to check if it is safe to import DALI and not touch the CUDA runtime
# that could crash forked process
import nvidia.dali as dali # noqa:F401
def task_function():
torch.cuda.set_device(0)
def test_actual_proc():
phase_process = Process(target=task_function)
# phase_process.daemon = True
phase_process.start()
phase_process.join()
assert phase_process.exitcode == 0
|
DALI-main
|
dali/test/python/test_dali_fork_torch.py
|
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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 copy
import numpy as np
import nvidia.dali.plugin.tf as dali_tf
import tensorflow as tf
from nvidia.dali import Pipeline, fn
from test_utils import RandomlyShapedDataIterator
def get_sample_one_arg_callback(dtype, iter_limit=1000, batch_size=None, dense=True):
def callback(x):
if x.iteration > iter_limit:
raise StopIteration()
size = x.idx_in_batch % 16 + 1, x.iteration % 16 + 4
result = np.full(size, x.idx_in_epoch, dtype=dtype)
result[0][0] = x.idx_in_epoch
result[0][1] = x.idx_in_batch
result[0][2] = x.iteration
result[0][3] = x.epoch_idx
return result
return callback
def get_batch_one_arg_callback(dtype, iter_limit=1000, batch_size=None, dense=True):
def callback(x):
if x > iter_limit:
raise StopIteration()
size = (x % 16 + 3,)
result = [np.full(size, x, dtype=dtype)] * batch_size
for i, elem in enumerate(result):
elem[0] = i
elem[1] = x
return np.stack(result) if dense else result
return callback
def get_batch_one_arg_callback_with_batch_info(dtype, iter_limit=1000, batch_size=None, dense=True):
def callback(x):
if x.iteration > iter_limit:
raise StopIteration()
size = (x.iteration % 16 + 4,)
result = [np.full(size, x.iteration, dtype=dtype)] * batch_size
for i, elem in enumerate(result):
elem[0] = i
elem[1] = x.iteration
elem[2] = x.epoch_idx
return np.stack(result) if dense else result
return callback
def get_no_arg_callback(dtype, iter_limit=1000, batch_size=None, dense=True):
class Callable:
def __init__(self):
self.counter = 0
def __call__(self):
size = (self.counter % 16 + 3,)
bs = 1 if batch_size is None else batch_size
if self.counter // bs > iter_limit:
self.counter = 0
raise StopIteration()
curr_counter = self.counter
self.counter += 1
if batch_size is None:
result = np.full(size, curr_counter, dtype=dtype)
return result
else:
result = [np.full(size, curr_counter, dtype=dtype)] * batch_size
for i, elem in enumerate(result):
elem[0] = i
return np.stack(result)
return Callable()
class UnwrapIterator:
def __init__(self, iterator):
self.iterator = iterator
def __iter__(self):
return self
def __next__(self):
return next(self.iterator)[0]
class DenseIterator:
def __init__(self, iterator):
self.iterator = iterator
def __iter__(self):
return self
def __next__(self):
return np.stack(next(self.iterator))
class FiniteIterator:
"""Used to wrap RandomlyShapedDataIterator to add iteration counts and finite data size
"""
def __init__(self, iterator, iter_limit):
self.iterator = iterator
self.iter_limit = iter_limit
def __iter__(self):
self.i = 0
return self
def __next__(self):
if self.i > self.iter_limit:
raise StopIteration()
result = next(self.iterator)
for i, elem in enumerate(result):
assert len(elem.shape) == (2), f"Got unexpected shape {elem.shape}"
assert elem.shape[1] >= 2, f"Got unexpected shape {elem.shape}"
elem[0][0] = i
elem[0][1] = self.i
self.i += 1
return result
def get_iterable(dtype, iter_limit=1000, batch_size=None, dense=True):
bs = 1 if batch_size is None else batch_size
max_shape = (20, 20)
min_shape = max_shape # if dense else None
result = FiniteIterator(iter(RandomlyShapedDataIterator(bs, min_shape, max_shape, 42, dtype)),
iter_limit)
if batch_size is None:
return UnwrapIterator(iter(result))
else:
return DenseIterator(iter(result)) if dense else result
def get_iterable_generator(dtype, iter_limit=1000, batch_size=None, dense=True):
def generator():
iterator = iter(get_iterable(dtype, iter_limit, batch_size, dense))
for example in iterator:
yield example
return generator
# generator, is_batched, cycle, batch_info
# TODO(klecki): cycle='raise' is currently not supported, and probably never will be
es_configurations = [
(get_sample_one_arg_callback, False, None, False),
(get_batch_one_arg_callback, True, None, False),
(get_batch_one_arg_callback_with_batch_info, True, None, True),
(get_no_arg_callback, False, None, False),
(get_no_arg_callback, True, None, False),
(get_iterable, False, False, False),
(get_iterable, False, True, False),
# (get_iterable, False, "raise", False),
(get_iterable, True, False, False),
(get_iterable, True, True, False),
# (get_iterable, True, "raise", False),
(get_iterable_generator, False, False, False),
(get_iterable_generator, False, True, False),
# (get_iterable_generator, False, "raise", False),
(get_iterable_generator, True, False, False),
(get_iterable_generator, True, True, False),
# (get_iterable_generator, True, "raise", False),
]
def get_external_source_pipe(es_args, dtype, es_device):
def get_pipeline_desc(batch_size, num_threads, device, device_id, shard_id, num_shards,
def_for_dataset):
pipe = Pipeline(batch_size, num_threads, device_id)
with pipe:
# Our callbacks may have state, to be able to run it twice, once in Dataset and once
# with baseline test, we need to make a copy to preserve that state.
es = fn.external_source(device=es_device, **copy.deepcopy(es_args))
if device == "gpu" and es_device == "cpu":
es = es.gpu()
pad = fn.pad(es, device=device)
pipe.set_outputs(pad)
return pipe, None, dtype
return get_pipeline_desc
def external_source_to_tf_dataset(pipe_desc, device_str): # -> tf.data.Dataset
pipe, _, dtypes = pipe_desc
with tf.device(device_str):
dali_dataset = dali_tf.experimental.DALIDatasetWithInputs(input_datasets=None,
pipeline=pipe,
batch_size=pipe.max_batch_size,
output_shapes=None,
output_dtypes=dtypes,
num_threads=pipe.num_threads,
device_id=pipe.device_id)
return dali_dataset
def get_dense_options(is_batched):
if is_batched:
return [True, False]
else:
return [True]
def gen_tf_with_dali_external_source(test_run):
for dtype in [np.uint8, np.int32, np.float32]:
for get_callback, is_batched, cycle, batch_info in es_configurations:
for dense in get_dense_options(is_batched):
for dev, es_dev in [("cpu", "cpu"), ("gpu", "cpu"), ("gpu", "gpu")]:
for iter_limit in [3, 9, 10, 11, 100]:
bs = 12 if is_batched else None
es_args = {'source': get_callback(dtype, iter_limit, bs, dense),
'batch': is_batched,
'cycle': cycle,
'batch_info': batch_info}
yield test_run, dev, es_args, es_dev, tf.dtypes.as_dtype(dtype), \
iter_limit, dense
|
DALI-main
|
dali/test/python/test_dali_tf_es_pipelines.py
|
# Copyright (c) 2019-2023, NVIDIA CORPORATION & AFFILIATES. 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 nvidia.dali as dali
import nvidia.dali.types as types
from nvidia.dali.backend_impl import TensorListGPU, TensorGPU, TensorListCPU
import inspect
import functools
import os
import random
import re
import subprocess
import sys
import tempfile
def get_arch(device_id=0):
compute_cap = 0
try:
import pynvml
pynvml.nvmlInit()
handle = pynvml.nvmlDeviceGetHandleByIndex(device_id)
compute_cap = pynvml.nvmlDeviceGetCudaComputeCapability(handle)
compute_cap = compute_cap[0] + compute_cap[1] / 10.
except ModuleNotFoundError:
print("NVML not found")
return compute_cap
def is_mulit_gpu():
try:
import pynvml
pynvml.nvmlInit()
is_mulit_gpu_var = pynvml.nvmlDeviceGetCount() != 1
except ModuleNotFoundError:
print("Python bindings for NVML not found")
return is_mulit_gpu_var
def get_device_memory_info(device_id=0):
try:
import pynvml
pynvml.nvmlInit()
handle = pynvml.nvmlDeviceGetHandleByIndex(device_id)
return pynvml.nvmlDeviceGetMemoryInfo(handle)
except ModuleNotFoundError:
print("Python bindings for NVML not found")
return None
def get_dali_extra_path():
try:
dali_extra_path = os.environ['DALI_EXTRA_PATH']
except KeyError:
print("WARNING: DALI_EXTRA_PATH not initialized.", file=sys.stderr)
dali_extra_path = "."
return dali_extra_path
# those functions import modules on demand to no impose additional dependency on numpy or matplot
# to test that are using these utilities
np = None
assert_array_equal = None
assert_allclose = None
cp = None
absdiff_checked = False
def import_numpy():
global np
global assert_array_equal
global assert_allclose
import numpy as np
from numpy.testing import assert_array_equal, assert_allclose
def import_cupy():
global cp
import cupy as cp
Image = None
def import_pil():
global Image
from PIL import Image
def save_image(image, file_name):
import_numpy()
import_pil()
if image.dtype == np.float32:
min = np.min(image)
max = np.max(image)
if min >= 0 and max <= 1:
image = image * 256
elif min >= -1 and max <= 1:
image = ((image + 1) * 128)
elif min >= -128 and max <= 127:
image = image + 128
else:
lo = np.iinfo(image.dtype).min
hi = np.iinfo(image.dtype).max
image = (image - lo) * (255.0 / (hi - lo))
image = image.astype(np.uint8)
Image.fromarray(image).save(file_name)
def get_gpu_num():
sp = subprocess.Popen(['nvidia-smi', '-L'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE, universal_newlines=True)
out_str = sp.communicate()
out_list = out_str[0].split('\n')
out_list = [elm for elm in out_list if len(elm) > 0]
return len(out_list)
def _get_absdiff(left, right):
def make_unsigned(dtype):
if not np.issubdtype(dtype, np.signedinteger):
return dtype
return {
np.dtype(np.int8): np.uint8,
np.dtype(np.int16): np.uint16,
np.dtype(np.int32): np.uint32,
np.dtype(np.int64): np.uint64,
}[dtype]
# np.abs of diff doesn't handle overflow for unsigned types
absdiff = np.maximum(left, right) - np.minimum(left, right)
# max - min can overflow for signed types, wrap them up
absdiff = absdiff.astype(make_unsigned(absdiff.dtype))
return absdiff
def _check_absdiff():
"""
In principle, overflow on signed int is UB (that we relied on so far anyway).
The following one-time check aims to verify the overflow wraps as expected.
"""
for i in range(-128, 127):
for j in range(-128, 127):
left = np.array([i, i], dtype=np.int8)
right = np.array([j, j], dtype=np.int8)
diff = _get_absdiff(left, right)
expected_diff = np.array([abs(i - j), abs(i - j)], dtype=np.uint8)
assert np.array_equal(diff, expected_diff), f"{diff} {expected_diff} {i} {j}"
for i in range(0, 255):
for j in range(0, 255):
left = np.array([i, i], dtype=np.uint8)
right = np.array([j, j], dtype=np.uint8)
diff = _get_absdiff(left, right)
expected_diff = np.array([abs(i - j), abs(i - j)], dtype=np.uint8)
assert np.array_equal(diff, expected_diff), f"{diff} {expected_diff} {i} {j}"
def get_absdiff(left, right):
# Make sanity checks, in particular, if wrapping signed integers works as expected
global absdiff_checked
if not absdiff_checked:
absdiff_checked = True
_check_absdiff()
return _get_absdiff(left, right)
# If the `max_allowed_error` is not None, it's checked instead of comparing mean error with `eps`.
def check_batch(batch1, batch2, batch_size=None,
eps=1e-07, max_allowed_error=None,
expected_layout=None, compare_layouts=True):
"""Compare two batches of data, be it dali TensorList or list of numpy arrays.
Args:
batch1: input batch
batch2: input batch
batch_size: reference batch size - if None, only equality is enforced
eps (float, optional): Used for mean error validation. Defaults to 1e-07.
max_allowed_error (int or float, optional): If provided the max diff between elements.
expected_layout (str, optional): If provided, the batches that are DALI types
will be checked to match this layout. If None, there will be no check
compare_layouts (bool, optional): Whether to compare layouts between two batches.
Checked only if both inputs are DALI types. Defaults to True.
"""
def is_error(mean_err, max_err, eps, max_allowed_error):
if max_allowed_error is not None:
if max_err > max_allowed_error:
return True
elif mean_err > eps:
return True
return False
import_numpy()
if isinstance(batch1, dali.backend_impl.TensorListGPU):
batch1 = batch1.as_cpu()
if isinstance(batch2, dali.backend_impl.TensorListGPU):
batch2 = batch2.as_cpu()
if batch_size is None:
batch_size = len(batch1)
def _verify_batch_size(batch):
if isinstance(batch, dali.backend.TensorListCPU) or isinstance(batch, list):
tested_batch_size = len(batch)
else:
tested_batch_size = batch.shape[0]
assert tested_batch_size == batch_size, \
"Incorrect batch size. Expected: {}, actual: {}".format(batch_size, tested_batch_size)
_verify_batch_size(batch1)
_verify_batch_size(batch2)
# Check layouts where possible
for batch in [batch1, batch2]:
if expected_layout is not None and isinstance(batch, dali.backend.TensorListCPU):
assert batch.layout() == expected_layout, \
'Unexpected layout, expected "{}", got "{}".'.format(expected_layout,
batch.layout())
if compare_layouts and \
isinstance(batch1, dali.backend.TensorListCPU) and \
isinstance(batch2, dali.backend.TensorListCPU):
assert batch1.layout() == batch2.layout(), \
'Layout mismatch "{}" != "{}"'.format(batch1.layout(), batch2.layout())
for i in range(batch_size):
# This allows to handle list of Tensors, list of np arrays and TensorLists
left = np.array(batch1[i])
right = np.array(batch2[i])
err_err = None
assert left.shape == right.shape, \
"Shape mismatch {} != {}".format(left.shape, right.shape)
assert left.size == right.size, \
"Size mismatch {} != {}".format(left.size, right.size)
if left.size != 0:
try:
# Do the difference calculation on a type that allows subtraction
if left.dtype == bool:
left = left.astype(int)
if right.dtype == bool:
right = right.astype(int)
absdiff = get_absdiff(left, right)
err = np.mean(absdiff)
max_err = np.max(absdiff)
min_err = np.min(absdiff)
total_errors = np.sum(absdiff != 0)
except Exception as e:
err_err = str(e)
if err_err or is_error(err, max_err, eps, max_allowed_error):
if err_err:
error_msg = f"Error calculation failed:\n{err_err}!\n"
else:
error_msg = (f"Mean error: [{err}], Min error: [{min_err}], "
f"Max error: [{max_err}]\n"
f"Total error count: [{total_errors}], "
f"Tensor size: [{absdiff.size}]\n"
f"Index in batch: {i}\n")
if hasattr(batch1[i], "source_info"):
error_msg += f"\nLHS data source: {batch1[i].source_info()}"
if hasattr(batch2[i], "source_info"):
error_msg += f"\nRHS data source: {batch2[i].source_info()}"
try:
save_image(left, "err_1.png")
save_image(right, "err_2.png")
except: # noqa:722
print("Batch at {} can't be saved as an image".format(i))
print(left)
print(right)
np.save("err_1.npy", left)
np.save("err_2.npy", right)
assert False, error_msg
def compare_pipelines(pipe1, pipe2, batch_size, N_iterations, eps=1e-07, max_allowed_error=None,
expected_layout=None, compare_layouts=True):
"""Compare the outputs of two pipelines across several iterations.
Args:
pipe1: input pipeline object.
pipe2: input pipeline object.
batch_size (int): batch size
N_iterations (int): Number of iterations used for comparison
eps (float, optional): Allowed mean error between samples. Defaults to 1e-07.
max_allowed_error (int or float, optional): If provided the max diff between elements.
expected_layout (str or tuple of str, optional): If provided the outputs of both pipelines
will be matched with provided layouts and error will be raised if there is mismatch.
Defaults to None.
compare_layouts (bool, optional): Whether to compare layouts of outputs between pipelines.
Defaults to True.
"""
pipe1.build()
pipe2.build()
for _ in range(N_iterations):
out1 = pipe1.run()
out2 = pipe2.run()
assert len(out1) == len(out2)
for i in range(len(out1)):
out1_data = out1[i].as_cpu() if isinstance(out1[i][0], dali.backend_impl.TensorGPU) \
else out1[i]
out2_data = out2[i].as_cpu() if isinstance(out2[i][0], dali.backend_impl.TensorGPU) \
else out2[i]
if isinstance(expected_layout, tuple):
current_expected_layout = expected_layout[i]
else:
current_expected_layout = expected_layout
check_batch(out1_data, out2_data, batch_size, eps, max_allowed_error,
expected_layout=current_expected_layout, compare_layouts=compare_layouts)
class RandomDataIterator(object):
def __init__(self, batch_size, shape=(10, 600, 800, 3), dtype=None, seed=0):
import_numpy()
# to avoid any numpy reference in the interface
if dtype is None:
dtype = np.uint8
self.batch_size = batch_size
self.test_data = []
self.np_rng = np.random.default_rng(seed=seed)
for _ in range(self.batch_size):
if dtype == np.float32:
self.test_data.append(
np.array(self.np_rng.random(shape) * (1.0), dtype=dtype) - 0.5)
else:
self.test_data.append(
np.array(self.np_rng.random(shape) * 255, dtype=dtype))
def __iter__(self):
self.i = 0
self.n = self.batch_size
return self
def __next__(self):
batch = self.test_data
self.i = (self.i + 1) % self.n
return (batch)
next = __next__
class RandomlyShapedDataIterator(object):
def __init__(
self, batch_size, min_shape=None, max_shape=(10, 600, 800, 3),
seed=12345, dtype=None):
import_numpy()
# to avoid any numpy reference in the interface
if dtype is None:
dtype = np.uint8
self.batch_size = batch_size
self.test_data = []
self.min_shape = min_shape
self.max_shape = max_shape
self.dtype = dtype
self.seed = seed
self.np_rng = np.random.default_rng(seed=seed)
self.rng = random.Random(seed)
def __iter__(self):
self.i = 0
self.n = self.batch_size
return self
def __next__(self):
import_numpy()
self.test_data = []
for _ in range(self.batch_size):
# Scale between 0.5 and 1.0
if self.min_shape is None:
shape = [
int(self.max_shape[dim] * (0.5 + self.rng.random() * 0.5))
for dim in range(len(self.max_shape))]
else:
shape = [self.rng.randint(min_s, max_s)
for min_s, max_s in zip(self.min_shape, self.max_shape)]
if self.dtype == np.float32:
self.test_data.append(
np.array(self.np_rng.random(shape) * (1.0), dtype=self.dtype) - 0.5)
else:
self.test_data.append(
np.array(self.np_rng.random(shape) * 255, dtype=self.dtype))
batch = self.test_data
self.i = (self.i + 1) % self.n
return (batch)
next = __next__
class ConstantDataIterator(object):
def __init__(self, batch_size, sample_data, dtype):
import_numpy()
self.batch_size = batch_size
self.test_data = []
for _ in range(self.batch_size):
self.test_data.append(np.array(sample_data, dtype=dtype))
def __iter__(self):
self.i = 0
self.n = self.batch_size
return self
def __next__(self):
batch = self.test_data
self.i = (self.i + 1) % self.n
return (batch)
next = __next__
def check_output(outputs, ref_out, ref_is_list_of_outputs=None):
"""Checks the outputs of the pipeline.
`outputs`
return value from pipeline `run`
`ref_out`
a batch or tuple of batches
`ref_is_list_of_outputs`
only meaningful when there's just one output - if True, ref_out is a one-lement
list containing a single batch for output 0; otherwise ref_out _is_ a batch
"""
import_numpy()
if ref_is_list_of_outputs is None:
ref_is_list_of_outputs = len(outputs) > 1
assert ref_is_list_of_outputs or (len(outputs) == 1)
for idx in range(len(outputs)):
out = outputs[idx]
ref = ref_out[idx] if ref_is_list_of_outputs else ref_out
if isinstance(out, dali.backend_impl.TensorListGPU):
out = out.as_cpu()
for i in range(len(out)):
if not np.array_equal(out[i], ref[i]):
print("Mismatch at sample", i)
print("Out: ", out.at(i))
print("Ref: ", ref[i])
assert np.array_equal(out[i], ref[i])
def dali_type(t):
import_numpy()
if t is None:
return None
if t is np.float16:
return types.FLOAT16
if t is np.float32:
return types.FLOAT
if t is np.uint8:
return types.UINT8
if t is np.int8:
return types.INT8
if t is np.uint16:
return types.UINT16
if t is np.int16:
return types.INT16
if t is np.uint32:
return types.UINT32
if t is np.int32:
return types.INT32
raise TypeError("Unsupported type: " + str(t))
def py_buffer_from_address(address, shape, dtype, gpu=False):
import_numpy()
buff = {'data': (address, False), 'shape': tuple(shape), 'typestr': np.dtype(dtype).str}
class py_holder(object):
pass
holder = py_holder()
holder.__array_interface__ = buff
holder.__cuda_array_interface__ = buff
if not gpu:
return np.array(holder, copy=False)
else:
import_cupy()
return cp.asanyarray(holder)
class check_output_pattern():
def __init__(self, pattern, is_regexp=True):
self.pattern_ = pattern
self.is_regexp_ = is_regexp
def __enter__(self):
self.bucket_out_ = tempfile.TemporaryFile(mode='w+')
self.bucket_err_ = tempfile.TemporaryFile(mode='w+')
self.stdout_fileno_ = 1
self.stderr_fileno_ = 2
self.old_stdout_ = os.dup(self.stdout_fileno_)
self.old_stderr_ = os.dup(self.stderr_fileno_)
os.dup2(self.bucket_out_.fileno(), self.stdout_fileno_)
os.dup2(self.bucket_err_.fileno(), self.stderr_fileno_)
def __exit__(self, exception_type, exception_value, traceback):
self.bucket_out_.seek(0)
self.bucket_err_.seek(0)
os.dup2(self.old_stdout_, self.stdout_fileno_)
os.dup2(self.old_stderr_, self.stderr_fileno_)
our_data = self.bucket_out_.read()
err_data = self.bucket_err_.read()
pattern_found = False
if self.is_regexp_:
pattern = re.compile(self.pattern_)
pattern_found = pattern.search(our_data) or pattern.search(err_data)
else:
pattern_found = self.pattern_ in our_data or self.pattern_ in err_data,
assert pattern_found, (f"Pattern: ``{self.pattern_}`` \n not found in out: \n"
f"``{our_data}`` \n and in err: \n ```{err_data}```")
def dali_type_to_np(type):
import_numpy()
dali_types_to_np_dict = {
types.BOOL: np.bool_,
types.INT8: np.int8,
types.INT16: np.int16,
types.INT32: np.int32,
types.INT64: np.int64,
types.UINT8: np.uint8,
types.UINT16: np.uint16,
types.UINT32: np.uint32,
types.UINT64: np.uint64,
types.FLOAT16: np.float16,
types.FLOAT: np.float32,
types.FLOAT64: np.float64,
}
return dali_types_to_np_dict[type]
def np_type_to_dali(type):
import_numpy()
np_types_to_dali_dict = {
np.bool_: types.BOOL,
np.int8: types.INT8,
np.int16: types.INT16,
np.int32: types.INT32,
np.int64: types.INT64,
np.uint8: types.UINT8,
np.uint16: types.UINT16,
np.uint32: types.UINT32,
np.uint64: types.UINT64,
np.float16: types.FLOAT16,
np.float32: types.FLOAT,
np.float64: types.FLOAT64,
}
return np_types_to_dali_dict[type]
def read_file_bin(filename):
"""
Read file as bytes and insert it into numpy array
:param filename: path to the file
:return: numpy array
"""
import_numpy()
return np.fromfile(filename, dtype='uint8')
def filter_files(dirpath, suffix, exclude_subdirs=[]):
"""
Read all file names recursively from a directory and filter those, which end with given suffix
:param dirpath: Path to directory, from which the file names will be read
:param suffix: String, which will be used to filter the files
:return: List of file names
"""
fnames = []
for dir_name, subdir_list, file_list in os.walk(dirpath):
for d in exclude_subdirs:
if d in subdir_list:
subdir_list.remove(d)
flist = filter(lambda fname: fname.endswith(suffix), file_list)
flist = map(lambda fname: os.path.join(dir_name, fname), flist)
fnames.extend(flist)
return fnames
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
self.avg_last_n = 0
self.max_val = 0
def update(self, val, n=1):
self.val = val
self.max_val = max(self.max_val, val)
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def to_array(dali_out):
import_numpy()
if isinstance(dali_out, (TensorGPU, TensorListGPU)):
dali_out = dali_out.as_cpu()
if isinstance(dali_out, TensorListCPU):
dali_out = dali_out.as_array()
return np.array(dali_out)
def module_functions(cls, prefix="", remove_prefix="", check_non_module=False,
allowed_private_modules=[]):
res = []
if hasattr(cls, '_schema_name'):
prefix = prefix.replace(remove_prefix, "")
prefix = prefix.lstrip('.')
if len(prefix):
prefix += '.'
else:
prefix = ""
res.append(prefix + cls.__name__)
elif check_non_module or inspect.ismodule(cls):
for c_name, c in inspect.getmembers(cls):
def public_or_allowed(c_name):
return not c_name.startswith("_") or c_name in allowed_private_modules
if public_or_allowed(c_name) and c_name not in sys.builtin_module_names:
res += module_functions(c, cls.__name__, remove_prefix=remove_prefix,
check_non_module=check_non_module,
allowed_private_modules=allowed_private_modules)
return res
def get_files(path, ext):
full_path = os.path.join(get_dali_extra_path(), path)
audio_files = [
os.path.join(full_path, f) for f in os.listdir(full_path)
if re.match(f".*\\.{ext}", f) is not None
]
return audio_files
def _test_skipped(reason=None):
print("Test skipped." if reason is None else f"Test skipped: {reason}")
def restrict_python_version(major, minor=None):
def decorator(test_case):
version_info = sys.version_info
if version_info.major > major or \
(version_info.major == major and (minor is None or version_info.minor >= minor)):
return test_case
return lambda: _test_skipped(
f"Insufficient Python version {version_info.major}.{version_info.minor} - "
f"required {major}.{minor}")
return decorator
def generator_random_data(batch_size, min_sh=(10, 10, 3), max_sh=(100, 100, 3),
dtype=None, val_range=[0, 255]):
import_numpy()
if dtype is None:
dtype = np.uint8
assert len(min_sh) == len(max_sh)
ndim = len(min_sh)
def gen():
out = []
for _ in range(batch_size):
shape = [np.random.randint(min_sh[d], max_sh[d] + 1, dtype=np.int32)
for d in range(ndim)]
arr = np.array(np.random.uniform(val_range[0], val_range[1], shape), dtype=dtype)
out += [arr]
return out
return gen
def generator_random_axes_for_3d_input(batch_size, use_negative=False, use_empty=False,
extra_out_desc=[]):
import_numpy()
def gen():
ndim = 3
options = [
np.array([0, 1], dtype=np.int32),
np.array([1, 0], dtype=np.int32),
np.array([0], dtype=np.int32),
np.array([1], dtype=np.int32),
]
if use_negative:
options += [
np.array([-2, -3], dtype=np.int32),
np.array([-2, 0], dtype=np.int32),
np.array([-3, 1], dtype=np.int32),
np.array([0, -2], dtype=np.int32),
np.array([1, -3], dtype=np.int32),
np.array([-2], dtype=np.int32),
np.array([-3], dtype=np.int32),
]
if use_empty:
# Add it 4 times to increase the probability to be choosen
options += 4 * [
np.array([], dtype=np.int32)
]
axes = []
for _ in range(batch_size):
axes.append(random.choice(options))
num_extra_outs = len(extra_out_desc)
extra_outputs = []
for out_idx in range(num_extra_outs):
extra_out = []
for i in range(batch_size):
axes_sh = axes[i].shape if axes[i].shape[0] > 0 else [ndim]
range_start, range_end, dtype = extra_out_desc[out_idx]
extra_out.append(
np.array(np.random.uniform(range_start, range_end, axes_sh), dtype=dtype)
)
extra_outputs.append(extra_out)
return tuple([axes] + extra_outputs)
return gen
def as_array(tensor):
import_numpy()
return np.array(tensor.as_cpu() if isinstance(tensor, TensorGPU) else tensor)
def python_function(*inputs, function, **kwargs):
"""
Convenience wrapper around fn.python_function.
If you need to pass to the fn.python_function mix of datanodes and parameters
that are not produced by the pipeline, you probably need to proceed along the lines of:
`dali.fn.python_function(data_node, function=lambda data:my_fun(data, non_pipeline_data))`.
This utility separates the data nodes from non data nodes automatically,
so that you can simply call `python_function(data_node, non_pipeline_data, function=my_fun)`.
"""
node_inputs = [inp for inp in inputs if isinstance(inp, dali.data_node.DataNode)]
const_inputs = [inp for inp in inputs if not isinstance(inp, dali.data_node.DataNode)]
def is_data_node(input):
return isinstance(input, dali.data_node.DataNode)
def wrapper(*exec_inputs):
iter_exec_inputs = (inp for inp in exec_inputs)
iter_const_inputs = (inp for inp in const_inputs)
iteration_inputs = [
next(iter_exec_inputs if is_data_node(inp) else iter_const_inputs)
for inp in inputs]
return function(*iteration_inputs)
return dali.fn.python_function(*node_inputs, function=wrapper, **kwargs)
def has_operator(operator):
def get_attr(obj, path):
attrs = path.split(".")
for attr in attrs:
obj = getattr(obj, attr)
return obj
def decorator(fun):
try:
get_attr(dali.fn, operator)
except AttributeError:
@functools.wraps(fun)
def dummy_case(*args, **kwargs):
print(f"Omitting test case for unsupported operator: `{operator}`")
return dummy_case
else:
return fun
return decorator
def restrict_platform(min_compute_cap=None, platforms=None):
spec = []
if min_compute_cap is not None:
compute_cap = get_arch()
cond = f"compute cap ({compute_cap}) >= {min_compute_cap}"
spec.append((cond, compute_cap >= min_compute_cap))
if platforms is not None:
import platform
cond = f"platform.machine() ({platform.machine()}) in {platforms}"
spec.append((cond, platform.machine() in platforms))
def decorator(fun):
if all(val for _, val in spec):
return fun
else:
@functools.wraps(fun)
def dummy_case(*args, **kwargs):
print(f"Omitting test case in unsupported env: `{spec}`")
return dummy_case
return decorator
|
DALI-main
|
dali/test/python/test_utils.py
|
# Copyright (c) 2020-2021, NVIDIA CORPORATION & AFFILIATES. 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 argparse
import cv2
import numpy as np
import nvidia.dali as dali
import nvidia.dali.types as types
import os
class FilesDataSet:
def __init__(self, data_path):
files = self.get_files_list(data_path)
self.data_path = data_path
self.classes_no = len(files)
self.files_map = {}
counter = 0
for class_no, (_, samples) in enumerate(files):
for sample in samples:
self.files_map[counter] = (sample, class_no)
counter += 1
self.size = counter
@classmethod
def get_files_list(cls, data_path):
dirs = [
(dir_name, [
file_path for file_path
in map(lambda name: os.path.join(dir_path, name), os.listdir(dir_path))
if os.path.isfile(file_path)
])
for (dir_name, dir_path)
in map(lambda name: (name, os.path.join(data_path, name)), os.listdir(data_path))
if os.path.isdir(dir_path)
]
dirs.sort(key=lambda dir_files: dir_files[0])
for _, files in dirs:
files.sort()
return dirs
def __len__(self):
return self.size
def get_sample(self, sample_idx, epoch_idx):
if sample_idx >= self.size:
raise StopIteration
return self.files_map[sample_idx]
class ShuffledFilesDataSet(FilesDataSet):
def __init__(self, data_path):
super().__init__(data_path)
self.rng = np.random.default_rng(seed=42)
self.epoch_idx = 0
self.perm = self.rng.permutation(self.size)
def get_sample(self, sample_idx, epoch_idx):
if self.epoch_idx != epoch_idx:
self.perm = self.rng.permutation(self.size)
self.epoch_idx = epoch_idx
if sample_idx >= self.size:
raise StopIteration
return super().get_sample(self.perm[sample_idx], epoch_idx)
class SampleLoader:
DATA_SET = ShuffledFilesDataSet
def __init__(self, data_path):
self.data_path = data_path
self.data_set = self.create_data_set()
def __getattr__(self, key):
if key == 'data_set':
self._data_set = self._data_set or self.create_data_set()
self.__dict__['data_set'] = self._data_set
return self._data_set
raise AttributeError
def create_data_set(self):
return self.DATA_SET(data_path=self.data_path)
def read_file(self, file_path):
return np.fromfile(file_path, dtype=np.uint8)
def __call__(self, sample_info):
file_path, class_no = self.data_set.get_sample(sample_info.idx_in_epoch,
sample_info.epoch_idx)
return self.read_file(file_path), np.array([class_no])
class BatchLoader(SampleLoader):
def __init__(self, data_path, batch_size):
super().__init__(data_path)
self.batch_size = batch_size
def __call__(self, batch_info):
assert isinstance(batch_info, types.BatchInfo), \
f"Expected batch info instance, got {type(batch_info)}"
batch_i = batch_info.iteration
epoch_idx = batch_info.epoch_idx
files_paths, labels = tuple(
zip(*[self.data_set.get_sample(self.batch_size * batch_i + i, epoch_idx) for i in
range(self.batch_size)]))
return [self.read_file(file_path) for file_path in files_paths], np.array(labels)
class CV2SampleLoader(SampleLoader):
def read_file(self, file_path):
img = cv2.imread(file_path)
return img
class CV2BatchLoader(BatchLoader):
def read_file(self, file_path):
img = cv2.imread(file_path)
return img
def create_dataset_generator(data_path, batch_size, read_encoded):
ds = ShuffledFilesDataSet(data_path)
epoch_i = -1
def create_epoch():
nonlocal epoch_i
epoch_i += 1
i = 0
try:
while True:
batch_imgs, batch_labels = [], []
for _ in range(batch_size):
jpeg_filename, label = ds.get_sample(i, epoch_i)
if read_encoded:
jpeg = np.fromfile(jpeg_filename, dtype=np.uint8)
else:
jpeg = cv2.imread(jpeg_filename)
batch_imgs.append(jpeg)
batch_labels.append(np.int32([label]))
i += 1
yield batch_imgs, batch_labels
except StopIteration:
pass
return create_epoch, len(ds)
def common_pipeline(images):
images = dali.fn.random_resized_crop(images, device="gpu", size=(224, 224))
rng = dali.fn.random.coin_flip(probability=0.5)
images = dali.fn.crop_mirror_normalize(
images, mirror=rng,
device="gpu",
dtype=types.FLOAT,
output_layout=types.NCHW,
crop=(224, 224),
mean=[125, 125, 125],
std=[255, 255, 255])
return images
def file_reader_pipeline(data_path, batch_size, num_threads, device_id, prefetch_queue_depth,
reader_queue_depth, read_encoded, **kwargs):
pipe = dali.pipeline.Pipeline(
batch_size=batch_size, num_threads=num_threads, device_id=device_id,
prefetch_queue_depth=prefetch_queue_depth)
with pipe:
images, labels = dali.fn.readers.file(
name="Reader",
file_root=data_path,
prefetch_queue_depth=reader_queue_depth,
random_shuffle=True)
dev = "mixed" if read_encoded else "cpu"
images = dali.fn.decoders.image(images, device=dev, output_type=types.RGB)
images = common_pipeline(images.gpu())
pipe.set_outputs(images, labels)
return pipe
class ExternalSourcePipeline(dali.pipeline.Pipeline):
def __init__(self, data_path, read_encoded, source_mode, **kwargs):
super().__init__(**kwargs)
if source_mode == "generator":
self.loader, self.data_set_len = create_dataset_generator(
data_path, batch_size=kwargs['batch_size'], read_encoded=read_encoded)
else:
self.data_set_len = None
if read_encoded:
loader_sample, loader_batch = SampleLoader, BatchLoader
else:
loader_sample, loader_batch = CV2SampleLoader, CV2BatchLoader
if source_mode == "batch":
self.loader = loader_batch(data_path, batch_size=kwargs['batch_size'])
else:
self.loader = loader_sample(data_path)
def epoch_size(self, *args, **kwargs):
return self.data_set_len if self.data_set_len is not None else len(self.loader.data_set)
def external_source_pipeline(data_path, batch_size, num_threads, device_id, prefetch_queue_depth,
reader_queue_depth, read_encoded, source_mode, **kwargs):
pipe = ExternalSourcePipeline(batch_size=batch_size,
num_threads=num_threads,
device_id=device_id,
prefetch_queue_depth=prefetch_queue_depth,
data_path=data_path,
source_mode=source_mode,
read_encoded=read_encoded)
with pipe:
images, labels = dali.fn.external_source(
pipe.loader, num_outputs=2,
batch=source_mode != "sample",
cycle="raise" if source_mode == "generator" else None,
batch_info=source_mode == "batch"
)
if read_encoded:
images = dali.fn.decoders.image(images, device="mixed", output_type=types.RGB)
images = common_pipeline(images.gpu())
pipe.set_outputs(images, labels)
return pipe
def external_source_parallel_pipeline(data_path, batch_size, num_threads, device_id,
prefetch_queue_depth, reader_queue_depth, read_encoded,
source_mode, py_num_workers=None, py_start_method="fork"):
pipe = ExternalSourcePipeline(batch_size=batch_size,
num_threads=num_threads,
device_id=device_id,
prefetch_queue_depth=prefetch_queue_depth,
py_start_method=py_start_method,
py_num_workers=py_num_workers,
data_path=data_path,
source_mode=source_mode,
read_encoded=read_encoded)
with pipe:
images, labels = dali.fn.external_source(
pipe.loader, num_outputs=2, parallel=True,
prefetch_queue_depth=reader_queue_depth,
batch=source_mode != "sample",
cycle="raise" if source_mode == "generator" else None,
batch_info=source_mode == "batch"
)
if read_encoded:
images = dali.fn.decoders.image(images, device="mixed", output_type=types.RGB)
images = common_pipeline(images.gpu())
pipe.set_outputs(images, labels)
return pipe
def get_pipe_factories(test_pipes, parallel_pipe, file_reader_pipe, scalar_pipe):
result = []
if "parallel" in test_pipes:
result.append(parallel_pipe)
if "file_reader" in test_pipes:
result.append(file_reader_pipe)
if "scalar" in test_pipes:
result.append(scalar_pipe)
return result
def parse_test_arguments(supports_distributed):
parser = argparse.ArgumentParser(
description='Compare external source vs filereader performance in RN50 data pipeline case')
parser.add_argument('data_path', type=str, help='Directory path of training dataset')
parser.add_argument('-b', '--batch_size', default=1024, type=int, metavar='N',
help='batch size')
parser.add_argument('-j', '--workers', default=3, type=int, metavar='N',
help='number of data loading workers (default: 3)')
parser.add_argument('--py_workers', default=3, type=int, metavar='N',
help='number of python external source workers (default: 3)')
parser.add_argument('--epochs', default=2, type=int, metavar='N',
help='Number of epochs to run')
parser.add_argument('--benchmark_iters', type=int, metavar='N',
help='Number of iterations to run in each epoch')
parser.add_argument('--worker_init', default='fork', choices=['fork', 'spawn'], type=str,
help='Python workers initialization method')
parser.add_argument('--prefetch', default=2, type=int, metavar='N',
help='Pipeline cpu/gpu prefetch queue depth')
parser.add_argument(
'--reader_queue_depth', default=1, type=int, metavar='N',
help='Depth of prefetching queue for file reading operators '
'(FileReader/parallel ExternalSource)')
parser.add_argument(
"--test_pipes", nargs="+", default=["parallel", "file_reader", "scalar"],
help="Pipelines to be tested, allowed values: 'parallel', 'file_reader', 'scalar'")
parser.add_argument('--source_mode', default="sample", choices=['sample', 'batch', 'generator'],
type=str,
help='Available modes: sample, batch, generator. First two run stateless '
'callbacks that return sample or batch given the index, the '
'generator mode iterates over a generator. '
'Parameter value has no effect on file reader pipeline.')
parser.add_argument('--dali_decode', default=False, type=bool,
help="If True decodes images with DALI's mixed decoder, otherwise decodes "
"on cpu (inside external source callback if applicable) and moves "
"with tensor.gpu()")
if supports_distributed:
parser.add_argument('--local_rank', default=0, type=int,
help="Id of the local rank in distributed scenario.")
else:
parser.add_argument('-g', '--gpus', default=1, type=int, metavar='N',
help='number of GPUs')
args = parser.parse_args()
if supports_distributed:
print(
"GPU ID: {}, batch: {}, epochs: {}, workers: {}, py_workers: {}, prefetch depth: {}, "
"reader_queue_depth: {}, worker_init: {}, test_pipes: {}".format(
args.local_rank, args.batch_size, args.epochs, args.workers, args.py_workers,
args.prefetch, args.reader_queue_depth, args.worker_init, args.test_pipes))
else:
print(
"GPUS: {}, batch: {}, epochs: {}, workers: {}, py_workers: {}, prefetch depth: {}, "
"reader_queue_depth: {}, worker_init: {}, test_pipes: {}".format(
args.gpus, args.batch_size, args.epochs, args.workers, args.py_workers,
args.prefetch, args.reader_queue_depth, args.worker_init, args.test_pipes))
return args
|
DALI-main
|
dali/test/python/test_RN50_external_source_parallel_utils.py
|
# Copyright (c) 2019-2022, NVIDIA CORPORATION & AFFILIATES. 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 argparse
import os
import nvidia.dali.ops as ops
import nvidia.dali.types as types
from nvidia.dali.pipeline import Pipeline
import nvidia.dali.tfrecord as tfrec
from test_detection_pipeline import coco_anchors
from test_utils import compare_pipelines, get_dali_extra_path
test_data_path = os.path.join(get_dali_extra_path(), 'db', 'coco')
test_dummy_data_path = os.path.join(get_dali_extra_path(), 'db', 'coco_dummy')
class TFRecordDetectionPipeline(Pipeline):
def __init__(self, args):
super(TFRecordDetectionPipeline, self).__init__(
args.batch_size, args.num_workers, 0, 0)
self.input = ops.readers.TFRecord(
path=os.path.join(test_dummy_data_path, 'small_coco.tfrecord'),
index_path=os.path.join(test_dummy_data_path, 'small_coco_index.idx'),
features={
'image/encoded': tfrec.FixedLenFeature((), tfrec.string, ""),
'image/object/class/label': tfrec.VarLenFeature([], tfrec.int64, 0),
'image/object/bbox': tfrec.VarLenFeature([4], tfrec.float32, 0.0),
},
shard_id=0,
num_shards=1,
random_shuffle=False)
self.decode_gpu = ops.decoders.Image(device="mixed", output_type=types.RGB)
self.cast = ops.Cast(dtype=types.INT32)
self.box_encoder = ops.BoxEncoder(
device="cpu",
criteria=0.5,
anchors=coco_anchors())
def define_graph(self):
inputs = self.input()
input_images = inputs["image/encoded"]
image_gpu = self.decode_gpu(input_images)
labels = self.cast(inputs['image/object/class/label'])
encoded_boxes, encoded_labels = self.box_encoder(inputs['image/object/bbox'], labels)
return (
image_gpu,
inputs['image/object/bbox'],
labels,
encoded_boxes,
encoded_labels)
class COCODetectionPipeline(Pipeline):
def __init__(self, args, data_path=test_data_path):
super(COCODetectionPipeline, self).__init__(
args.batch_size, args.num_workers, 0, 0)
self.input = ops.readers.COCO(
file_root=os.path.join(data_path, 'images'),
annotations_file=os.path.join(data_path, 'instances.json'),
shard_id=0,
num_shards=1,
ratio=True,
ltrb=True,
random_shuffle=False)
self.decode_gpu = ops.decoders.Image(device="mixed", output_type=types.RGB)
self.box_encoder = ops.BoxEncoder(
device="cpu",
criteria=0.5,
anchors=coco_anchors())
def define_graph(self):
inputs, boxes, labels = self.input(name="Reader")
image_gpu = self.decode_gpu(inputs)
encoded_boxes, encoded_labels = self.box_encoder(boxes, labels)
return (
image_gpu,
boxes,
labels,
encoded_boxes,
encoded_labels)
def print_args(args):
print('Args values:')
for arg in vars(args):
print('{0} = {1}'.format(arg, getattr(args, arg)))
print()
def run_test(args):
print_args(args)
pipe_tf = TFRecordDetectionPipeline(args)
pipe_coco = COCODetectionPipeline(args, test_dummy_data_path)
compare_pipelines(pipe_tf, pipe_coco, 1, 64)
def make_parser():
parser = argparse.ArgumentParser(description='COCO Tfrecord test')
parser.add_argument(
'-i', '--iters', default=None, type=int, metavar='N',
help='number of iterations to run (default: whole dataset)')
parser.add_argument(
'-w', '--num_workers', default=4, type=int, metavar='N',
help='number of worker threads (default: %(default)s)')
return parser
if __name__ == "__main__":
parser = make_parser()
args = parser.parse_args()
args.batch_size = 1
run_test(args)
|
DALI-main
|
dali/test/python/test_coco_tfrecord.py
|
# Copyright (c) 2019-2022, NVIDIA CORPORATION & AFFILIATES. 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 nvidia.dali.plugin.tf as dali_tf
import os
from nvidia.dali.pipeline import Pipeline
import nvidia.dali.fn as fn
import nvidia.dali.types as types
from test_utils_tensorflow import num_available_gpus
from shutil import rmtree as remove_directory
import tensorflow as tf
import tensorflow.compat.v1 as tf_v1
TARGET = 0.8
BATCH_SIZE = 64
DROPOUT = 0.2
IMAGE_SIZE = 28
NUM_CLASSES = 10
HIDDEN_SIZE = 128
EPOCHS = 5
ITERATIONS = 100
data_path = os.path.join(os.environ['DALI_EXTRA_PATH'], 'db/MNIST/training/')
def mnist_pipeline(
num_threads, path, device, device_id=0, shard_id=0, num_shards=1, seed=0):
pipeline = Pipeline(BATCH_SIZE, num_threads, device_id, seed)
with pipeline:
jpegs, labels = fn.readers.caffe2(
path=path, random_shuffle=True, shard_id=shard_id, num_shards=num_shards)
images = fn.decoders.image(
jpegs, device='mixed' if device == 'gpu' else 'cpu', output_type=types.GRAY)
if device == 'gpu':
labels = labels.gpu()
images = fn.crop_mirror_normalize(
images, dtype=types.FLOAT, mean=[0.], std=[255.], output_layout="CHW")
pipeline.set_outputs(images, labels)
return pipeline
def get_dataset(device='cpu', device_id=0, shard_id=0, num_shards=1, fail_on_device_mismatch=True):
pipeline = mnist_pipeline(
4, data_path, device, device_id, shard_id, num_shards)
shapes = (
(BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE),
(BATCH_SIZE,))
dtypes = (
tf.float32,
tf.int32)
daliset = dali_tf.DALIDataset(
pipeline=pipeline,
batch_size=BATCH_SIZE,
output_shapes=shapes,
output_dtypes=dtypes,
num_threads=4,
device_id=device_id,
fail_on_device_mismatch=fail_on_device_mismatch)
return daliset
def get_dataset_multi_gpu(strategy):
def dataset_fn(input_context):
with tf.device("/gpu:{}".format(input_context.input_pipeline_id)):
device_id = input_context.input_pipeline_id
return get_dataset('gpu', device_id, device_id, num_available_gpus())
input_options = tf.distribute.InputOptions(
experimental_place_dataset_on_device=True,
experimental_fetch_to_device=False,
experimental_replication_mode=tf.distribute.InputReplicationMode.PER_REPLICA)
train_dataset = strategy.distribute_datasets_from_function(dataset_fn, input_options)
return train_dataset
def keras_model():
model = tf.keras.models.Sequential([
tf.keras.layers.Input(shape=(IMAGE_SIZE, IMAGE_SIZE), name='images'),
tf.keras.layers.Flatten(input_shape=(IMAGE_SIZE, IMAGE_SIZE)),
tf.keras.layers.Dense(HIDDEN_SIZE, activation='relu'),
tf.keras.layers.Dropout(DROPOUT),
tf.keras.layers.Dense(NUM_CLASSES, activation='softmax')
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
def run_keras_single_device(device='cpu', device_id=0):
with tf.device('/{0}:{1}'.format(device, device_id)):
model = keras_model()
train_dataset = get_dataset(device, device_id)
model.fit(
train_dataset,
epochs=EPOCHS,
steps_per_epoch=ITERATIONS)
assert model.evaluate(
train_dataset,
steps=ITERATIONS)[1] > TARGET
def graph_model(images, reuse, is_training):
with tf_v1.variable_scope('mnist_net', reuse=reuse):
images = tf_v1.layers.flatten(images)
images = tf_v1.layers.dense(images, HIDDEN_SIZE, activation=tf_v1.nn.relu)
images = tf_v1.layers.dropout(images, rate=DROPOUT, training=is_training)
images = tf_v1.layers.dense(images, NUM_CLASSES, activation=tf_v1.nn.softmax)
return images
def train_graph(iterator_initializers, train_op, accuracy):
with tf_v1.Session() as sess:
sess.run(tf_v1.global_variables_initializer())
sess.run(iterator_initializers)
for i in range(EPOCHS * ITERATIONS):
sess.run(train_op)
if i % ITERATIONS == 0:
train_accuracy = accuracy.eval()
print("Step %d, accuracy: %g" % (i, train_accuracy))
final_accuracy = 0
for _ in range(ITERATIONS):
final_accuracy = final_accuracy + \
accuracy.eval()
final_accuracy = final_accuracy / ITERATIONS
print('Final accuracy: ', final_accuracy)
assert final_accuracy > TARGET
def run_graph_single_device(device='cpu', device_id=0):
with tf.device('/{0}:{1}'.format(device, device_id)):
daliset = get_dataset(device, device_id)
iterator = tf_v1.data.make_initializable_iterator(daliset)
images, labels = iterator.get_next()
# images = tf_v1.reshape(images, [BATCH_SIZE, IMAGE_SIZE*IMAGE_SIZE])
labels = tf_v1.reshape(
tf_v1.one_hot(labels, NUM_CLASSES),
[BATCH_SIZE, NUM_CLASSES])
logits_train = graph_model(images, reuse=False, is_training=True)
logits_test = graph_model(images, reuse=True, is_training=False)
loss_op = tf_v1.reduce_mean(tf_v1.nn.softmax_cross_entropy_with_logits(
logits=logits_train, labels=labels))
train_step = tf_v1.train.AdamOptimizer().minimize(loss_op)
correct_pred = tf_v1.equal(
tf_v1.argmax(logits_test, 1), tf_v1.argmax(labels, 1))
accuracy = tf_v1.reduce_mean(tf_v1.cast(correct_pred, tf_v1.float32))
train_graph([iterator.initializer], train_step, accuracy)
def clear_checkpoints():
remove_directory('/tmp/tensorflow-checkpoints', ignore_errors=True)
def _test_estimators_single_device(model, device='cpu', device_id=0):
def dataset_fn():
with tf.device('/{0}:{1}'.format(device, device_id)):
return get_dataset(device, device_id)
model.train(input_fn=dataset_fn, steps=EPOCHS * ITERATIONS)
evaluation = model.evaluate(
input_fn=dataset_fn,
steps=ITERATIONS)
final_accuracy = evaluation['acc'] if 'acc' in evaluation else evaluation['accuracy']
print('Final accuracy: ', final_accuracy)
assert final_accuracy > TARGET
def _run_config(device='cpu', device_id=0):
return tf.estimator.RunConfig(
model_dir='/tmp/tensorflow-checkpoints',
device_fn=lambda op: '/{0}:{1}'.format(device, device_id))
def run_estimators_single_device(device='cpu', device_id=0):
with tf.device('/{0}:{1}'.format(device, device_id)):
model = keras_model()
model = tf.keras.estimator.model_to_estimator(
keras_model=model,
config=_run_config(device, device_id))
_test_estimators_single_device(
model,
device,
device_id)
|
DALI-main
|
dali/test/python/test_dali_tf_dataset_mnist.py
|
# Copyright (c) 2019-2022, NVIDIA CORPORATION & AFFILIATES. 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
from nvidia.dali.pipeline import Pipeline, pipeline_def
from nvidia.dali.backend_impl import TensorCPU
import nvidia.dali.types as types
import nvidia.dali.fn as fn
import numpy as np
import os
from test_utils import get_dali_extra_path
from nose.tools import nottest
from nose_utils import raises, assert_raises
from nvidia.dali.plugin.base_iterator import LastBatchPolicy as LastBatchPolicy
import random
def create_coco_pipeline(data_paths, batch_size, num_threads, shard_id, num_gpus, random_shuffle,
stick_to_shard, shuffle_after_epoch, pad_last_batch, initial_fill=1024,
return_labels=False):
pipe = Pipeline(batch_size=batch_size, num_threads=num_threads,
device_id=0, prefetch_queue_depth=1)
with pipe:
_, _, labels, ids = fn.readers.coco(
file_root=data_paths[0], annotations_file=data_paths[1],
shard_id=shard_id, num_shards=num_gpus, random_shuffle=random_shuffle,
image_ids=True, stick_to_shard=stick_to_shard, shuffle_after_epoch=shuffle_after_epoch,
pad_last_batch=pad_last_batch, initial_fill=initial_fill, name="Reader"
)
if return_labels:
pipe.set_outputs(labels, ids)
else:
pipe.set_outputs(ids)
return pipe
test_data_root = get_dali_extra_path()
coco_folder = os.path.join(test_data_root, 'db', 'coco')
data_sets = [[os.path.join(coco_folder, 'images'),
os.path.join(coco_folder, 'instances.json')]]
image_data_set = os.path.join(test_data_root, 'db', 'single', 'jpeg')
def gather_ids(dali_train_iter, data_getter, pad_getter, data_size):
img_ids_list = []
batch_size = dali_train_iter.batch_size
pad = 0
for it in iter(dali_train_iter):
if not isinstance(it, dict):
it = it[0]
tmp = data_getter(it).copy()
pad += pad_getter(it)
img_ids_list.append(tmp)
img_ids_list = np.concatenate(img_ids_list)
img_ids_list_set = set(img_ids_list)
remainder = int(math.ceil(data_size / batch_size)) * batch_size - data_size
mirrored_data = img_ids_list[-remainder - 1:]
return img_ids_list, img_ids_list_set, mirrored_data, pad, remainder
def create_pipeline(creator, batch_size, num_gpus):
iters = 0
# make sure that data size and batch are not divisible
while iters % batch_size == 0:
while iters != 0 and iters % batch_size == 0:
batch_size += 1
pipes = [creator(gpu) for gpu in range(num_gpus)]
[pipe.build() for pipe in pipes]
iters = pipes[0].epoch_size("Reader")
iters = iters // num_gpus
return pipes, iters
def test_mxnet_iterator_model_fit():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
import mxnet as mx
num_gpus = 1
batch_size = 1
def create_test_pipeline(batch_size, num_threads, device_id, num_gpus, data_paths):
pipe = Pipeline(batch_size=batch_size, num_threads=num_threads, device_id=device_id)
with pipe:
_, labels = fn.readers.file(
file_root=data_paths, shard_id=device_id, num_shards=num_gpus, name="Reader")
pipe.set_outputs(labels)
return pipe
pipes, _ = create_pipeline(
lambda gpu: create_test_pipeline(batch_size=batch_size, num_threads=4, device_id=gpu,
num_gpus=num_gpus, data_paths=image_data_set),
batch_size, num_gpus
)
pipe = pipes[0]
class MXNetIteratorWrapper(MXNetIterator):
def __init__(self, iter):
self.iter = iter
def __getattr__(self, attr):
return getattr(self.iter, attr)
def __next__(self):
ret = self.iter.__next__()[0]
return ret
dali_train_iter = MXNetIterator(pipe, [("labels", MXNetIterator.LABEL_TAG)],
size=pipe.epoch_size("Reader"))
data = mx.symbol.Variable('labels')
# create a dummy model
_ = mx.model.FeedForward.create(data,
X=MXNetIteratorWrapper(dali_train_iter),
num_epoch=1,
learning_rate=0.01)
def test_mxnet_iterator_last_batch_no_pad_last_batch():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=False),
batch_size, num_gpus
)
dali_train_iter = MXNetIterator(pipes, [("ids", MXNetIterator.DATA_TAG)],
size=pipes[0].epoch_size("Reader"),
last_batch_policy=LastBatchPolicy.FILL)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(
dali_train_iter, lambda x: x.data[0].squeeze(-1).asnumpy(), lambda x: x.pad, data_size)
assert len(img_ids_list) > data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) != 1
def test_mxnet_iterator_empty_array():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
import mxnet as mx
batch_size = 4
size = 5
all_np_types = [np.bool_, np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64, np.float_, np.float32, np.float16,
np.short, np.long, np.longlong, np.ushort, np.ulonglong]
np_types = []
# store in np_types only types supported by MXNet
for t in all_np_types:
try:
mx.nd.zeros([2, 2, 2], ctx=None, dtype=t)
np_types.append(t)
except mx.base.MXNetError:
pass
test_data_shape = [1, 3, 0, 4]
def get_data():
# create batch of [type_a, type_a, type_b, type_b, ...]
out = [[np.empty(test_data_shape, dtype=t)] *
batch_size for t in np_types]
out = [val for pair in zip(out, out) for val in pair]
return out
pipe = Pipeline(batch_size=batch_size, num_threads=3, device_id=0)
outs = fn.external_source(source=get_data, num_outputs=len(np_types) * 2)
pipe.set_outputs(*outs)
pipe.build()
# create map of [(data, type_a), (label, type_a), ...]
data_map = [('data_{}'.format(i), MXNetIterator.DATA_TAG)
for i, t in enumerate(np_types)]
label_map = [('label_{}'.format(i), MXNetIterator.LABEL_TAG)
for i, t in enumerate(np_types)]
out_map = [val for pair in zip(data_map, label_map) for val in pair]
iterator = MXNetIterator(
pipe,
output_map=out_map,
size=size,
dynamic_shape=True)
for batch in iterator:
for d, t in zip(batch[0].data, np_types):
shape = d.asnumpy().shape
assert shape[0] == batch_size
assert np.array_equal(shape[1:], test_data_shape)
assert d.asnumpy().dtype == t
def test_mxnet_iterator_last_batch_pad_last_batch():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=True),
batch_size, num_gpus
)
dali_train_iter = MXNetIterator(pipes, [("ids", MXNetIterator.DATA_TAG)],
size=pipes[0].epoch_size("Reader"),
last_batch_policy=LastBatchPolicy.FILL)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(
dali_train_iter, lambda x: x.data[0].squeeze(-1).asnumpy(), lambda x: x.pad, data_size)
assert len(img_ids_list) > data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) == 1
dali_train_iter.reset()
next_img_ids_list, next_img_ids_list_set, next_mirrored_data, _, _ = \
gather_ids(
dali_train_iter, lambda x: x.data[0].squeeze(-1).asnumpy(), lambda x: x.pad, data_size)
assert len(next_img_ids_list) > data_size
assert len(next_img_ids_list_set) == data_size
assert len(set(next_mirrored_data)) == 1
def test_mxnet_iterator_not_fill_last_batch_pad_last_batch():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=True),
batch_size, num_gpus
)
dali_train_iter = MXNetIterator(pipes, [("ids", MXNetIterator.DATA_TAG)],
size=pipes[0].epoch_size("Reader"),
last_batch_policy=LastBatchPolicy.PARTIAL)
img_ids_list, img_ids_list_set, mirrored_data, pad, remainder = \
gather_ids(
dali_train_iter, lambda x: x.data[0].squeeze(-1).asnumpy(), lambda x: x.pad, data_size)
assert pad == remainder
assert len(img_ids_list) - pad == data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) == 1
dali_train_iter.reset()
next_img_ids_list, next_img_ids_list_set, next_mirrored_data, pad, remainder = \
gather_ids(
dali_train_iter, lambda x: x.data[0].squeeze(-1).asnumpy(), lambda x: x.pad, data_size)
assert pad == remainder
assert len(next_img_ids_list) - pad == data_size
assert len(next_img_ids_list_set) == data_size
assert len(set(next_mirrored_data)) == 1
def check_iterator_results(pad, pipes_number, shards_num, out_set, last_batch_policy, img_ids_list,
ids, data_set_size, sample_counter, per_gpu_counter, stick_to_shard,
epoch_counter, rounded_shard_size):
if pad and pipes_number == shards_num:
assert len(set.intersection(*out_set)
) == 0, "Shards should not overlaps in the epoch"
if last_batch_policy == LastBatchPolicy.DROP:
if pad:
assert len(set.union(*out_set)) <= sum([len(v) for v in img_ids_list]), \
"Data returned from shard should not duplicate values"
for id_list, id_set, id in zip(img_ids_list, out_set, ids):
shard_size = int((id + 1) * data_set_size /
shards_num) - int(id * data_set_size / shards_num)
assert len(id_list) <= shard_size
assert len(id_set) <= shard_size
elif last_batch_policy == LastBatchPolicy.PARTIAL:
if pad:
assert len(set.union(*out_set)) == sum([len(v) for v in img_ids_list]), \
"Data returned from shard should not duplicate values"
for id_list, id_set, id in zip(img_ids_list, out_set, ids):
shard_size = int((id + 1) * data_set_size /
shards_num) - int(id * data_set_size / shards_num)
assert len(id_list) == shard_size
assert len(id_set) == shard_size
else:
sample_counter -= min(per_gpu_counter)
per_gpu_counter = [v + sample_counter for v in per_gpu_counter]
if not stick_to_shard:
shard_id_mod = epoch_counter
else:
shard_id_mod = 0
shard_beg = [int(((id + shard_id_mod) % shards_num) *
data_set_size / shards_num) for id in range(shards_num)]
shard_end = [int((((id + shard_id_mod) % shards_num) + 1)
* data_set_size / shards_num) for id in range(shards_num)]
shard_sizes = [int((id + 1) * data_set_size / shards_num) -
int(id * data_set_size / shards_num) for id in ids]
per_gpu_counter = [
c - (e - b) for c, b, e in zip(per_gpu_counter, shard_beg, shard_end)]
if pad:
assert len(set.union(*out_set)) == sum(shard_sizes)
for id_list, id_set, size in zip(img_ids_list, out_set, shard_sizes):
if not pad:
assert len(id_list) == sample_counter
else:
assert len(id_list) == rounded_shard_size
if not stick_to_shard:
if not pad:
assert len(id_list) == len(id_set)
else:
assert len(id_list) == rounded_shard_size
assert len(id_set) == size
else:
assert len(id_set) == min(size, sample_counter)
if not pad:
sample_counter = min(per_gpu_counter)
else:
sample_counter = 0
if not stick_to_shard:
ids = [(id + 1) % shards_num for id in ids]
epoch_counter += 1
# these values are modified so return them
return (ids, sample_counter, per_gpu_counter, epoch_counter, rounded_shard_size)
def check_mxnet_iterator_pass_reader_name(shards_num, pipes_number, batch_size, stick_to_shard,
pad, iters, last_batch_policy, auto_reset=False):
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
pipes = [create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=id,
num_gpus=shards_num, data_paths=data_sets[0],
random_shuffle=False, stick_to_shard=stick_to_shard,
shuffle_after_epoch=False, pad_last_batch=pad)
for id in range(pipes_number)]
for p in pipes:
p.build()
data_set_size = pipes[0].reader_meta("Reader")["epoch_size"]
rounded_shard_size = math.ceil(
math.ceil(data_set_size / shards_num) / batch_size) * batch_size
ids = [pipe.reader_meta("Reader")["shard_id"] for pipe in pipes]
per_gpu_counter = [0] * shards_num
epoch_counter = 0
sample_counter = 0
if batch_size > data_set_size // shards_num and last_batch_policy == LastBatchPolicy.DROP:
assert_raises(AssertionError, MXNetIterator, pipes, [
("ids", MXNetIterator.DATA_TAG)], reader_name="Reader",
last_batch_policy=last_batch_policy,
glob="It seems that there is no data in the pipeline*last_batch_policy*")
return
else:
dali_train_iter = MXNetIterator(pipes, [("ids", MXNetIterator.DATA_TAG)],
reader_name="Reader", last_batch_policy=last_batch_policy,
auto_reset=auto_reset)
for _ in range(iters):
out_set = []
img_ids_list = [[] for _ in range(pipes_number)]
orig_length = length = len(dali_train_iter)
for it in iter(dali_train_iter):
for id in range(pipes_number):
tmp = it[id].data[0].squeeze(-1).asnumpy().copy()
if it[id].pad:
tmp = tmp[0:-it[id].pad]
img_ids_list[id].append(tmp)
sample_counter += batch_size
length -= 1
assert length == 0, \
f"The iterator has reported the length of {orig_length} " \
f"but provided {orig_length - length} iterations."
if not auto_reset:
dali_train_iter.reset()
for id in range(pipes_number):
img_ids_list[id] = np.concatenate(img_ids_list[id])
out_set.append(set(img_ids_list[id]))
ret = check_iterator_results(pad, pipes_number, shards_num, out_set, last_batch_policy,
img_ids_list, ids, data_set_size, sample_counter,
per_gpu_counter, stick_to_shard, epoch_counter,
rounded_shard_size)
(ids, sample_counter, per_gpu_counter, epoch_counter, rounded_shard_size) = ret
def test_mxnet_iterator_pass_reader_name():
for shards_num in [3, 5, 17]:
for batch_size in [3, 5, 7]:
for stick_to_shard in [False, True]:
for pad in [True, False]:
for last_batch_policy in [LastBatchPolicy.PARTIAL,
LastBatchPolicy.FILL,
LastBatchPolicy.DROP]:
for iters in [1, 2, 3, 2 * shards_num]:
for pipes_number in [1, shards_num]:
yield check_mxnet_iterator_pass_reader_name, shards_num, \
pipes_number, batch_size, stick_to_shard, pad, iters, \
last_batch_policy, False
def test_mxnet_iterator_pass_reader_name_autoreset():
for auto_reset in [True, False]:
yield check_mxnet_iterator_pass_reader_name, 3, 1, 3, False, True, 3, \
LastBatchPolicy.DROP, auto_reset
def test_gluon_iterator_last_batch_no_pad_last_batch():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4,
shard_id=gpu, num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=False),
batch_size, num_gpus
)
dali_train_iter = GluonIterator(pipes, size=pipes[0].epoch_size(
"Reader"), last_batch_policy=LastBatchPolicy.FILL)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(dali_train_iter,
lambda x: x[0].squeeze(-1).asnumpy(), lambda x: 0, data_size)
assert len(img_ids_list) > data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) != 1
def test_gluon_iterator_last_batch_pad_last_batch():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=True),
batch_size, num_gpus
)
dali_train_iter = GluonIterator(pipes,
size=pipes[0].epoch_size("Reader"),
last_batch_policy=LastBatchPolicy.FILL)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(dali_train_iter,
lambda x: x[0].squeeze(-1).asnumpy(), lambda x: 0, data_size)
assert len(img_ids_list) > data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) == 1
dali_train_iter.reset()
next_img_ids_list, next_img_ids_list_set, next_mirrored_data, _, _ = \
gather_ids(dali_train_iter,
lambda x: x[0].squeeze(-1).asnumpy(), lambda x: 0, data_size)
assert len(next_img_ids_list) > data_size
assert len(next_img_ids_list_set) == data_size
assert len(set(next_mirrored_data)) == 1
def test_gluon_iterator_not_fill_last_batch_pad_last_batch():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=False, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=True),
batch_size, num_gpus
)
dali_train_iter = GluonIterator(pipes, size=pipes[0].epoch_size("Reader"),
last_batch_policy=LastBatchPolicy.PARTIAL)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(dali_train_iter,
lambda x: x[0].squeeze(-1).asnumpy(), lambda x: 0, data_size)
assert len(img_ids_list) == data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) != 1
dali_train_iter.reset()
next_img_ids_list, next_img_ids_list_set, next_mirrored_data, pad, remainder = \
gather_ids(dali_train_iter,
lambda x: x[0].squeeze(-1).asnumpy(), lambda x: 0, data_size)
assert len(next_img_ids_list) == data_size
assert len(next_img_ids_list_set) == data_size
assert len(set(next_mirrored_data)) != 1
def test_gluon_iterator_sparse_batch():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
from mxnet.ndarray.ndarray import NDArray
num_gpus = 1
batch_size = 16
pipes, _ = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=True,
return_labels=True),
batch_size, num_gpus
)
dali_train_iter = GluonIterator(pipes, pipes[0].epoch_size("Reader"),
output_types=[GluonIterator.SPARSE_TAG,
GluonIterator.DENSE_TAG],
last_batch_policy=LastBatchPolicy.FILL)
for it in dali_train_iter:
labels, ids = it[0] # gpu 0
# labels should be a sparse batch: a list of per-sample NDArray's
# ids should be a dense batch: a single NDarray representing the batch
assert isinstance(labels, (tuple, list))
assert len(labels) == batch_size
assert isinstance(labels[0], NDArray)
assert isinstance(ids, NDArray)
def check_gluon_iterator_pass_reader_name(shards_num, pipes_number, batch_size, stick_to_shard,
pad, iters, last_batch_policy, auto_reset=False):
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
pipes = [create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=id,
num_gpus=shards_num, data_paths=data_sets[0],
random_shuffle=False, stick_to_shard=stick_to_shard,
shuffle_after_epoch=False, pad_last_batch=pad)
for id in range(pipes_number)]
for p in pipes:
p.build()
data_set_size = pipes[0].reader_meta("Reader")["epoch_size"]
rounded_shard_size = math.ceil(
math.ceil(data_set_size / shards_num) / batch_size) * batch_size
ids = [pipe.reader_meta("Reader")["shard_id"] for pipe in pipes]
per_gpu_counter = [0] * shards_num
epoch_counter = 0
sample_counter = 0
if batch_size > data_set_size // shards_num and last_batch_policy == LastBatchPolicy.DROP:
assert_raises(AssertionError, GluonIterator, pipes,
reader_name="Reader", last_batch_policy=last_batch_policy,
glob="It seems that there is no data in the pipeline. This may happen "
"if `last_batch_policy` is set to PARTIAL and the requested "
"batch size is greater than the shard size.")
return
else:
dali_train_iter = GluonIterator(
pipes, reader_name="Reader", last_batch_policy=last_batch_policy, auto_reset=auto_reset)
for _ in range(iters):
out_set = []
img_ids_list = [[] for _ in range(pipes_number)]
orig_length = length = len(dali_train_iter)
for it in iter(dali_train_iter):
for id in range(pipes_number):
if len(it[id][0]):
tmp = it[id][0].squeeze(-1).asnumpy().copy()
else:
tmp = np.empty([0])
img_ids_list[id].append(tmp)
sample_counter += batch_size
length -= 1
assert length == 0, \
f"The iterator has reported the length of {orig_length} " \
f"but provided {orig_length - length} iterations."
if not auto_reset:
dali_train_iter.reset()
for id in range(pipes_number):
assert (batch_size > data_set_size // shards_num and
last_batch_policy == LastBatchPolicy.DROP) or len(img_ids_list[id])
if len(img_ids_list[id]):
img_ids_list[id] = np.concatenate(img_ids_list[id])
out_set.append(set(img_ids_list[id]))
if len(out_set) == 0 and last_batch_policy == LastBatchPolicy.DROP:
return
ret = check_iterator_results(pad, pipes_number, shards_num, out_set, last_batch_policy,
img_ids_list, ids, data_set_size, sample_counter,
per_gpu_counter, stick_to_shard,
epoch_counter, rounded_shard_size)
(ids, sample_counter, per_gpu_counter, epoch_counter, rounded_shard_size) = ret
def test_gluon_iterator_pass_reader_name():
for shards_num in [3, 5, 17]:
for batch_size in [3, 5, 7]:
for stick_to_shard in [False, True]:
for pad in [True, False]:
for last_batch_policy in [LastBatchPolicy.PARTIAL,
LastBatchPolicy.FILL,
LastBatchPolicy.DROP]:
for iters in [1, 2, 3, 2 * shards_num]:
for pipes_number in [1, shards_num]:
yield check_gluon_iterator_pass_reader_name, shards_num, \
pipes_number, batch_size, stick_to_shard, pad, iters, \
last_batch_policy, False
def test_gluon_iterator_pass_reader_name_autoreset():
for auto_reset in [True, False]:
yield check_gluon_iterator_pass_reader_name, 3, 1, 3, False, True, 3, \
LastBatchPolicy.DROP, auto_reset
def test_pytorch_iterator_last_batch_no_pad_last_batch():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=False),
batch_size, num_gpus
)
dali_train_iter = PyTorchIterator(pipes, output_map=["data"], size=pipes[0].epoch_size(
"Reader"), last_batch_policy=LastBatchPolicy.FILL)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(
dali_train_iter, lambda x: x["data"].squeeze(-1).numpy(), lambda x: 0, data_size)
assert len(img_ids_list) > data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) != 1
def test_pytorch_iterator_last_batch_pad_last_batch():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=True),
batch_size, num_gpus
)
dali_train_iter = PyTorchIterator(pipes, output_map=["data"], size=pipes[0].epoch_size(
"Reader"), last_batch_policy=LastBatchPolicy.FILL)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(
dali_train_iter, lambda x: x["data"].squeeze(-1).numpy(), lambda x: 0, data_size)
assert len(img_ids_list) > data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) == 1
dali_train_iter.reset()
next_img_ids_list, next_img_ids_list_set, next_mirrored_data, _, _ = \
gather_ids(
dali_train_iter, lambda x: x["data"].squeeze(-1).numpy(), lambda x: 0, data_size)
assert len(next_img_ids_list) > data_size
assert len(next_img_ids_list_set) == data_size
assert len(set(next_mirrored_data)) == 1
def test_pytorch_iterator_not_fill_last_batch_pad_last_batch():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=False, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=True),
batch_size, num_gpus
)
dali_train_iter = PyTorchIterator(pipes, output_map=["data"], size=pipes[0].epoch_size(
"Reader"), last_batch_policy=LastBatchPolicy.PARTIAL, last_batch_padded=True)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(
dali_train_iter, lambda x: x["data"].squeeze(-1).numpy(), lambda x: 0, data_size)
assert len(img_ids_list) == data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) != 1
dali_train_iter.reset()
next_img_ids_list, next_img_ids_list_set, next_mirrored_data, _, _ = \
gather_ids(
dali_train_iter, lambda x: x["data"].squeeze(-1).numpy(), lambda x: 0, data_size)
# there is no mirroring as data in the output is just cut off,
# in the mirrored_data there is real data
assert len(next_img_ids_list) == data_size
assert len(next_img_ids_list_set) == data_size
assert len(set(next_mirrored_data)) != 1
def test_jax_iterator_last_batch_no_pad_last_batch():
from nvidia.dali.plugin.jax import DALIGenericIterator as JaxIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=False),
batch_size, num_gpus
)
dali_train_iter = JaxIterator(pipes, output_map=["data"], size=pipes[0].epoch_size(
"Reader"), last_batch_policy=LastBatchPolicy.FILL)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(
dali_train_iter, lambda x: x["data"].squeeze(-1), lambda x: 0, data_size)
assert len(img_ids_list) > data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) != 1
def test_jax_iterator_last_batch_pad_last_batch():
from nvidia.dali.plugin.jax import DALIGenericIterator as JaxIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=True),
batch_size, num_gpus
)
dali_train_iter = JaxIterator(pipes, output_map=["data"], size=pipes[0].epoch_size(
"Reader"), last_batch_policy=LastBatchPolicy.FILL)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(
dali_train_iter, lambda x: x["data"].squeeze(-1), lambda x: 0, data_size)
assert len(img_ids_list) > data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) == 1
dali_train_iter.reset()
next_img_ids_list, next_img_ids_list_set, next_mirrored_data, _, _ = \
gather_ids(
dali_train_iter, lambda x: x["data"].squeeze(-1), lambda x: 0, data_size)
assert len(next_img_ids_list) > data_size
assert len(next_img_ids_list_set) == data_size
assert len(set(next_mirrored_data)) == 1
def create_custom_pipeline(batch_size, num_threads, device_id, num_gpus, data_paths):
pipe = Pipeline(batch_size=batch_size, num_threads=num_threads,
device_id=0, prefetch_queue_depth=1)
with pipe:
jpegs, _ = fn.readers.file(
file_root=data_paths, shard_id=device_id, num_shards=num_gpus, name="Reader")
images = fn.decoders.image(jpegs, device="mixed", output_type=types.RGB)
images = fn.random_resized_crop(images, size=(224, 224))
images = fn.crop_mirror_normalize(images,
dtype=types.FLOAT,
output_layout=types.NCHW,
crop=(224, 224),
mean=[0.485 * 255, 0.456 *
255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
pipe.set_outputs(images)
return pipe
def test_pytorch_iterator_feed_ndarray():
from nvidia.dali.plugin.pytorch import feed_ndarray as feed_ndarray
import torch
num_gpus = 1
batch_size = 100
pipes, _ = create_pipeline(
lambda gpu: create_custom_pipeline(batch_size=batch_size, num_threads=4, device_id=gpu,
num_gpus=num_gpus, data_paths=image_data_set),
batch_size, num_gpus
)
for gpu_id in range(num_gpus):
pipe = pipes[gpu_id]
pipe.build()
outs = pipe.run()
out_data = outs[0].as_tensor()
device = torch.device('cuda', gpu_id)
arr = torch.zeros(out_data.shape(), dtype=torch.float32, device=device)
feed_ndarray(
out_data, arr, cuda_stream=torch.cuda.current_stream(device=device))
np.testing.assert_equal(arr.cpu().numpy(), outs[0].as_cpu().as_array())
def check_pytorch_iterator_feed_ndarray_types(data_type):
from nvidia.dali.plugin.pytorch import feed_ndarray as feed_ndarray
import torch
to_torch_type = {
np.float32: torch.float32,
np.float64: torch.float64,
np.float16: torch.float16,
np.uint8: torch.uint8,
np.int8: torch.int8,
np.bool_: torch.bool,
np.int16: torch.int16,
np.int32: torch.int32,
np.int64: torch.int64
}
shape = [3, 9]
if np.issubdtype(data_type, np.integer):
arr = np.random.randint(np.iinfo(data_type).min, high=np.iinfo(data_type).max,
size=shape, dtype=data_type)
elif data_type == np.bool_:
arr = np.random.randint(0, high=2, size=shape, dtype=data_type)
else:
arr = np.random.randn(*shape).astype(data_type)
tensor = TensorCPU(arr, "NHWC")
pyt = torch.empty(shape, dtype=to_torch_type[data_type])
feed_ndarray(tensor, pyt)
assert np.all(pyt.numpy() == arr)
def test_pytorch_iterator_feed_ndarray_types():
types = [np.float32, np.float64, np.float16, np.uint8, np.int8, np.bool_, np.int16,
np.int32, np.int64]
for data_type in types:
yield check_pytorch_iterator_feed_ndarray_types, data_type
def test_ragged_iterator_sparse_coo_batch():
from nvidia.dali.plugin.pytorch import DALIRaggedIterator as RaggedIterator
num_gpus = 1
batch_size = 16
pipes, _ = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=True,
return_labels=True),
batch_size, num_gpus
)
dali_train_iter = RaggedIterator(pipes, output_map=["labels", "ids"],
size=pipes[0].epoch_size("Reader"),
output_types=[RaggedIterator.SPARSE_COO_TAG,
RaggedIterator.DENSE_TAG],
last_batch_policy=LastBatchPolicy.FILL)
for it in dali_train_iter:
labels, ids = it[0]["labels"], it[0]["ids"] # gpu 0
# labels should be a sparse coo batch: a sparse coo tensor
# ids should be a dense batch: a single dense tensor
assert len(labels) == batch_size
assert labels.is_sparse is True
assert ids.is_sparse is False
def test_ragged_iterator_sparse_list_batch():
from nvidia.dali.plugin.pytorch import DALIRaggedIterator as RaggedIterator
num_gpus = 1
batch_size = 16
pipes, _ = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=True,
return_labels=True),
batch_size, num_gpus
)
dali_train_iter = RaggedIterator(pipes, output_map=["labels", "ids"],
size=pipes[0].epoch_size("Reader"),
output_types=[RaggedIterator.SPARSE_LIST_TAG,
RaggedIterator.DENSE_TAG],
last_batch_policy=LastBatchPolicy.FILL)
for it in dali_train_iter:
labels, ids = it[0]["labels"], it[0]["ids"] # gpu 0
# labels should be a sparse list batch: a list of dense tensor
# ids should be a dense batch: a single dense tensor
assert len(labels) == batch_size
assert isinstance(labels, list) is True
assert ids.is_sparse is False
def test_mxnet_iterator_feed_ndarray():
from nvidia.dali.plugin.mxnet import feed_ndarray as feed_ndarray
import mxnet as mx
num_gpus = 1
batch_size = 100
pipes, _ = create_pipeline(
lambda gpu: create_custom_pipeline(batch_size=batch_size, num_threads=4, device_id=gpu,
num_gpus=num_gpus, data_paths=image_data_set),
batch_size, num_gpus
)
for gpu_id in range(num_gpus):
pipe = pipes[gpu_id]
pipe.build()
outs = pipe.run()
out_data = outs[0].as_tensor()
with mx.Context(mx.gpu(gpu_id)):
arr = mx.nd.zeros(out_data.shape(), dtype=np.float32)
mx.base._LIB.MXNDArrayWaitToWrite(arr.handle)
# Using DALI's internal stream
feed_ndarray(out_data, arr, cuda_stream=None)
np.testing.assert_equal(arr.asnumpy(), outs[0].as_cpu().as_array())
arr2 = mx.nd.zeros(out_data.shape(), dtype=np.float32)
mx.base._LIB.MXNDArrayWaitToWrite(arr2.handle)
feed_ndarray(out_data, arr2, cuda_stream=0) # Using default stream
np.testing.assert_equal(
arr2.asnumpy(), outs[0].as_cpu().as_array())
def check_mxnet_iterator_feed_ndarray_types(data_type):
from nvidia.dali.plugin.mxnet import feed_ndarray as feed_ndarray
import mxnet as mx
shape = [3, 9]
if np.issubdtype(data_type, np.integer):
arr = np.random.randint(np.iinfo(data_type).min, high=np.iinfo(data_type).max,
size=shape, dtype=data_type)
elif data_type == np.bool_:
arr = np.random.randint(0, high=2, size=shape, dtype=data_type)
else:
arr = np.random.randn(*shape).astype(data_type)
tensor = TensorCPU(arr, "NHWC")
mnt = mx.nd.empty(shape, dtype=data_type)
feed_ndarray(tensor, mnt)
assert np.all(mnt.asnumpy() == arr)
def test_mxnet_iterator_feed_ndarray_types():
# MXNet doesn't support int16
types = [np.float32, np.float64, np.float16, np.uint8, np.int8, np.bool_,
np.int32, np.int64]
for data_type in types:
yield check_mxnet_iterator_feed_ndarray_types, data_type
def test_paddle_iterator_feed_ndarray():
from nvidia.dali.plugin.paddle import feed_ndarray as feed_ndarray
import paddle
num_gpus = 1
batch_size = 100
pipes, _ = create_pipeline(
lambda gpu: create_custom_pipeline(batch_size=batch_size, num_threads=4, device_id=gpu,
num_gpus=num_gpus, data_paths=image_data_set),
batch_size, num_gpus
)
for gpu_id in range(num_gpus):
pipe = pipes[gpu_id]
pipe.build()
outs = pipe.run()
out_data = outs[0].as_tensor()
lod_tensor = paddle.framework.core.LoDTensor()
lod_tensor._set_dims(out_data.shape())
gpu_place = paddle.CUDAPlace(gpu_id)
ptr = lod_tensor._mutable_data(
gpu_place, paddle.framework.core.VarDesc.VarType.FP32)
np.array(lod_tensor)
# Using DALI's internal stream
feed_ndarray(out_data, ptr, cuda_stream=None)
np.testing.assert_equal(np.array(lod_tensor),
outs[0].as_cpu().as_array())
lod_tensor2 = paddle.framework.core.LoDTensor()
lod_tensor2._set_dims(out_data.shape())
ptr2 = lod_tensor2._mutable_data(
gpu_place, paddle.framework.core.VarDesc.VarType.FP32)
np.array(lod_tensor2)
feed_ndarray(out_data, ptr2, cuda_stream=0) # Using default stream
np.testing.assert_equal(np.array(lod_tensor2),
outs[0].as_cpu().as_array())
def check_paddle_iterator_feed_ndarray_types(data_type):
from nvidia.dali.plugin.paddle import feed_ndarray as feed_ndarray
import paddle
dtype_map = {
np.bool_: paddle.framework.core.VarDesc.VarType.BOOL,
np.float32: paddle.framework.core.VarDesc.VarType.FP32,
np.float64: paddle.framework.core.VarDesc.VarType.FP64,
np.float16: paddle.framework.core.VarDesc.VarType.FP16,
np.uint8: paddle.framework.core.VarDesc.VarType.UINT8,
np.int8: paddle.framework.core.VarDesc.VarType.INT8,
np.int16: paddle.framework.core.VarDesc.VarType.INT16,
np.int32: paddle.framework.core.VarDesc.VarType.INT32,
np.int64: paddle.framework.core.VarDesc.VarType.INT64
}
shape = [3, 9]
if np.issubdtype(data_type, np.integer):
arr = np.random.randint(np.iinfo(data_type).min, high=np.iinfo(data_type).max,
size=shape, dtype=data_type)
elif data_type == np.bool_:
arr = np.random.randint(0, high=2, size=shape, dtype=data_type)
else:
arr = np.random.randn(*shape).astype(data_type)
tensor = TensorCPU(arr, "NHWC")
pddt = paddle.framework.core.LoDTensor()
pddt._set_dims(shape)
ptr = pddt._mutable_data(paddle.CPUPlace(), dtype_map[data_type])
feed_ndarray(tensor, ptr)
assert np.all(np.array(pddt) == arr)
def test_paddle_iterator_feed_ndarray_types():
types = [np.float32, np.float64, np.float16, np.uint8, np.int8, np.bool_, np.int16,
np.int32, np.int64]
for data_type in types:
yield check_paddle_iterator_feed_ndarray_types, data_type
def check_pytorch_iterator_pass_reader_name(shards_num, pipes_number, batch_size, stick_to_shard,
pad, iters, last_batch_policy, auto_reset=False):
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
pipes = [create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=id,
num_gpus=shards_num, data_paths=data_sets[0],
random_shuffle=False, stick_to_shard=stick_to_shard,
shuffle_after_epoch=False, pad_last_batch=pad)
for id in range(pipes_number)]
for p in pipes:
p.build()
data_set_size = pipes[0].reader_meta("Reader")["epoch_size"]
rounded_shard_size = math.ceil(
math.ceil(data_set_size / shards_num) / batch_size) * batch_size
ids = [pipe.reader_meta("Reader")["shard_id"] for pipe in pipes]
per_gpu_counter = [0] * shards_num
epoch_counter = 0
sample_counter = 0
if batch_size > data_set_size // shards_num and last_batch_policy == LastBatchPolicy.DROP:
assert_raises(AssertionError, PyTorchIterator, pipes, output_map=["data"],
reader_name="Reader", last_batch_policy=last_batch_policy,
glob="It seems that there is no data in the pipeline. This may happen "
"if `last_batch_policy` is set to PARTIAL and the requested batch size "
"is greater than the shard size.")
return
else:
dali_train_iter = PyTorchIterator(pipes, output_map=["data"], reader_name="Reader",
last_batch_policy=last_batch_policy,
auto_reset=auto_reset)
for _ in range(iters):
out_set = []
img_ids_list = [[] for _ in range(pipes_number)]
orig_length = length = len(dali_train_iter)
for it in iter(dali_train_iter):
for id in range(pipes_number):
tmp = it[id]["data"].squeeze(dim=1).numpy().copy()
img_ids_list[id].append(tmp)
sample_counter += batch_size
length -= 1
assert length == 0, \
f"The iterator has reported the length of {orig_length} " \
f"but provided {orig_length - length} iterations."
if not auto_reset:
dali_train_iter.reset()
for id in range(pipes_number):
img_ids_list[id] = np.concatenate(img_ids_list[id])
out_set.append(set(img_ids_list[id]))
ret = check_iterator_results(pad, pipes_number, shards_num, out_set, last_batch_policy,
img_ids_list, ids, data_set_size, sample_counter,
per_gpu_counter, stick_to_shard,
epoch_counter, rounded_shard_size)
(ids, sample_counter, per_gpu_counter,
epoch_counter, rounded_shard_size) = ret
def test_pytorch_iterator_pass_reader_name():
for shards_num in [3, 5, 17]:
for batch_size in [3, 5, 7]:
for stick_to_shard in [False, True]:
for pad in [True, False]:
for last_batch_policy in \
[LastBatchPolicy.PARTIAL, LastBatchPolicy.FILL, LastBatchPolicy.DROP]:
for iters in [1, 2, 3, 2 * shards_num]:
for pipes_number in [1, shards_num]:
yield check_pytorch_iterator_pass_reader_name, shards_num, \
pipes_number, batch_size, stick_to_shard, pad, iters, \
last_batch_policy, False
def test_pytorch_iterator_pass_reader_name_autoreset():
for auto_reset in [True, False]:
yield check_pytorch_iterator_pass_reader_name, 3, 1, 3, False, True, 3, \
LastBatchPolicy.DROP, auto_reset
def test_paddle_iterator_last_batch_no_pad_last_batch():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=False),
batch_size, num_gpus
)
dali_train_iter = PaddleIterator(pipes, output_map=["data"], size=pipes[0].epoch_size(
"Reader"), last_batch_policy=LastBatchPolicy.FILL)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(dali_train_iter, lambda x: np.array(
x["data"]).squeeze(), lambda x: 0, data_size)
assert len(img_ids_list) > data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) != 1
def test_paddle_iterator_last_batch_pad_last_batch():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=True),
batch_size, num_gpus
)
dali_train_iter = PaddleIterator(pipes, output_map=["data"], size=pipes[0].epoch_size(
"Reader"), last_batch_policy=LastBatchPolicy.FILL)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(dali_train_iter, lambda x: np.array(
x["data"]).squeeze(), lambda x: 0, data_size)
assert len(img_ids_list) > data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) == 1
dali_train_iter.reset()
next_img_ids_list, next_img_ids_list_set, next_mirrored_data, _, _ = \
gather_ids(dali_train_iter, lambda x: np.array(
x["data"]).squeeze(), lambda x: 0, data_size)
assert len(next_img_ids_list) > data_size
assert len(next_img_ids_list_set) == data_size
assert len(set(next_mirrored_data)) == 1
def test_paddle_iterator_not_fill_last_batch_pad_last_batch():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
num_gpus = 1
batch_size = 100
pipes, data_size = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=False, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=True),
batch_size, num_gpus
)
dali_train_iter = PaddleIterator(pipes, output_map=["data"], size=pipes[0].epoch_size(
"Reader"), last_batch_policy=LastBatchPolicy.PARTIAL, last_batch_padded=True)
img_ids_list, img_ids_list_set, mirrored_data, _, _ = \
gather_ids(dali_train_iter, lambda x: np.array(
x["data"]).squeeze(), lambda x: 0, data_size)
assert len(img_ids_list) == data_size
assert len(img_ids_list_set) == data_size
assert len(set(mirrored_data)) != 1
dali_train_iter.reset()
next_img_ids_list, next_img_ids_list_set, next_mirrored_data, _, _ = \
gather_ids(dali_train_iter, lambda x: np.array(
x["data"]).squeeze(), lambda x: 0, data_size)
# there is no mirroring as data in the output is just cut off,
# in the mirrored_data there is real data
assert len(next_img_ids_list) == data_size
assert len(next_img_ids_list_set) == data_size
assert len(set(next_mirrored_data)) != 1
def check_paddle_iterator_pass_reader_name(shards_num, pipes_number, batch_size, stick_to_shard,
pad, iters, last_batch_policy, auto_reset=False):
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
pipes = [create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=id,
num_gpus=shards_num, data_paths=data_sets[0],
random_shuffle=False, stick_to_shard=stick_to_shard,
shuffle_after_epoch=False, pad_last_batch=pad)
for id in range(pipes_number)]
for p in pipes:
p.build()
data_set_size = pipes[0].reader_meta("Reader")["epoch_size"]
rounded_shard_size = math.ceil(
math.ceil(data_set_size / shards_num) / batch_size) * batch_size
ids = [pipe.reader_meta("Reader")["shard_id"] for pipe in pipes]
per_gpu_counter = [0] * shards_num
epoch_counter = 0
sample_counter = 0
if batch_size > data_set_size // shards_num and last_batch_policy == LastBatchPolicy.DROP:
assert_raises(AssertionError, PaddleIterator, pipes, output_map=["data"],
reader_name="Reader", last_batch_policy=last_batch_policy,
glob="It seems that there is no data in the pipeline. This may happen "
"if `last_batch_policy` is set to PARTIAL and the requested batch size "
"is greater than the shard size.")
return
else:
dali_train_iter = PaddleIterator(pipes, output_map=["data"], reader_name="Reader",
last_batch_policy=last_batch_policy, auto_reset=auto_reset)
for _ in range(iters):
out_set = []
img_ids_list = [[] for _ in range(pipes_number)]
orig_length = length = len(dali_train_iter)
for it in iter(dali_train_iter):
for id in range(pipes_number):
tmp = np.array(it[id]["data"]).squeeze(axis=1).copy()
img_ids_list[id].append(tmp)
sample_counter += batch_size
length -= 1
assert length == 0, \
f"The iterator has reported the length of {orig_length} " \
f"but provided {orig_length - length} iterations."
if not auto_reset:
dali_train_iter.reset()
for id in range(pipes_number):
img_ids_list[id] = np.concatenate(img_ids_list[id])
out_set.append(set(img_ids_list[id]))
ret = check_iterator_results(pad, pipes_number, shards_num, out_set, last_batch_policy,
img_ids_list, ids, data_set_size, sample_counter,
per_gpu_counter, stick_to_shard, epoch_counter,
rounded_shard_size)
(ids, sample_counter, per_gpu_counter,
epoch_counter, rounded_shard_size) = ret
def test_paddle_iterator_pass_reader_name():
for shards_num in [3, 5, 17]:
for batch_size in [3, 5, 7]:
for stick_to_shard in [False, True]:
for pad in [True, False]:
for last_batch_policy in \
[LastBatchPolicy.PARTIAL, LastBatchPolicy.FILL, LastBatchPolicy.DROP]:
for iters in [1, 2, 3, 2 * shards_num]:
for pipes_number in [1, shards_num]:
yield check_paddle_iterator_pass_reader_name, shards_num, \
pipes_number, batch_size, stick_to_shard, pad, iters, \
last_batch_policy, False
def test_paddle_iterator_pass_reader_name_autoreset():
for auto_reset in [True, False]:
yield check_paddle_iterator_pass_reader_name, 3, 1, 3, False, True, 3, \
LastBatchPolicy.DROP, auto_reset
class TestIterator():
def __init__(self, iters_per_epoch, batch_size, total_iter_num=-1):
self.n = iters_per_epoch
self.total_n = total_iter_num
self.batch_size = batch_size
def __iter__(self):
self.i = 0
return self
def __next__(self):
batch = []
# setting -1 means that no total iteration limit is set
if self.i < self.n and self.total_n != 0:
batch = [np.arange(0, 10, dtype=np.uint8)
for _ in range(self.batch_size)]
self.i += 1
self.total_n -= 1
return batch
else:
self.i = 0
raise StopIteration
next = __next__
@property
def size(self,):
return self.n * self.batch_size
@nottest
def create_test_iter_pipeline(batch_size, device_id, data_source, num_threads=4):
pipe = Pipeline(batch_size=batch_size, num_threads=num_threads,
device_id=0, prefetch_queue_depth=1)
with pipe:
outs = fn.external_source(source=data_source)
pipe.set_outputs(outs)
return pipe
def check_stop_iter(fw_iter, iterator_name, batch_size, epochs, iter_num,
total_iter_num, auto_reset, infinite):
it = TestIterator(iter_num, batch_size, total_iter_num)
pipe = create_test_iter_pipeline(batch_size, 0, it)
if infinite:
iter_size = -1
else:
iter_size = it.size
loader = fw_iter(pipe, iter_size, auto_reset)
count = 0
for _ in range(epochs):
for _ in enumerate(loader):
count += 1
if not auto_reset:
loader.reset()
if total_iter_num < 0:
# infinite source of data
assert count == iter_num * epochs
else:
# at most total_iter_num should be returned by the iterator
assert count == min(total_iter_num, iter_num * epochs)
@raises(Exception, glob="Negative size is supported only for a single pipeline")
def check_stop_iter_fail_multi(fw_iter):
batch_size = 1
iter_num = 1
pipes = [create_test_iter_pipeline(
batch_size, 0, TestIterator(iter_num, batch_size)) for _ in range(2)]
fw_iter(pipes, -1, False)
@raises(Exception, glob="Size cannot be 0")
def check_stop_iter_fail_single(fw_iter):
batch_size = 1
iter_num = 1
pipes = [create_test_iter_pipeline(
batch_size, 0, TestIterator(iter_num, batch_size)) for _ in range(1)]
fw_iter(pipes, 0, False)
def stop_iteration_case_generator():
for epochs in [1, 3, 6]:
for iter_num in [1, 2, 5, 9]:
for total_iters in [-1, iter_num - 1, 2 * iter_num - 1]:
if total_iters == 0 or total_iters > epochs * iter_num:
continue
for batch_size in [1, 10, 100]:
for auto_reset in [True, False]:
for infinite in [False, True]:
yield batch_size, epochs, iter_num, total_iters, auto_reset, infinite
def check_iterator_wrapper_first_iteration(BaseIterator, *args, **kwargs):
# This wrapper is used to test that the base class iterator doesn't invoke
# the wrapper self.__next__ function accidentally
class IteratorWrapper(BaseIterator):
def __init__(self, *args, **kwargs):
self._allow_next = False
super(IteratorWrapper, self).__init__(*args, **kwargs)
# Asserting if __next__ is called, unless self._allow_next has been set to True explicitly
def __next__(self):
assert self._allow_next
_ = super(IteratorWrapper, self).__next__()
pipe = Pipeline(batch_size=16, num_threads=1, device_id=0)
with pipe:
data = fn.random.uniform(range=(-1, 1), shape=(2, 2, 2), seed=1234)
pipe.set_outputs(data)
iterator_wrapper = IteratorWrapper([pipe], *args, **kwargs)
# Only now, we allow the wrapper __next__ to run
iterator_wrapper._allow_next = True
for i, _ in enumerate(iterator_wrapper):
if i == 2:
break
def check_external_source_autoreset(Iterator, *args, to_np=None, **kwargs):
max_batch_size = 4
iter_limit = 4
runs = 3
test_data_shape = [2, 3, 4]
i = 0
dataset = [[[np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8)
for _ in range(max_batch_size)]] for _ in range(iter_limit)]
def get_data():
nonlocal i
if i == iter_limit:
i = 0
raise StopIteration
out = dataset[i]
i += 1
return out
pipe = Pipeline(batch_size=max_batch_size, num_threads=1, device_id=0)
with pipe:
outs = fn.external_source(source=get_data, num_outputs=1)
pipe.set_outputs(*outs)
it = Iterator([pipe], *args, auto_reset=True, **kwargs)
counter = 0
for _ in range(runs):
for j, data in enumerate(it):
assert (to_np(data) == np.concatenate(dataset[j])).all()
counter += 1
assert counter == iter_limit * runs
def check_external_source_variable_size(Iterator, *args, iter_size=-1, to_np=None, **kwargs):
max_batch_size = 1
iter_limit = 4
runs = 3
test_data_shape = [2, 3, 4]
i = 0
dataset = [[[np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8) for _ in range(
random.randint(1, max_batch_size))]] for _ in range(iter_limit)]
def get_data():
nonlocal i
if i == iter_limit:
i = 0
raise StopIteration
out = dataset[i]
i += 1
return out
pipe = Pipeline(batch_size=max_batch_size, num_threads=1, device_id=0)
with pipe:
outs = fn.external_source(source=get_data, num_outputs=1)
pipe.set_outputs(*outs)
it = Iterator([pipe], *args, auto_reset=True, size=iter_size, **kwargs)
counter = 0
for _ in range(runs):
for j, data in enumerate(it):
assert (to_np(data[0]) == np.concatenate(dataset[j])).all()
counter += 1
assert counter == iter_limit * runs
# MXNet
def test_stop_iteration_mxnet():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
def fw_iter(pipe, size, auto_reset): return MXNetIterator(
pipe, [("data", MXNetIterator.DATA_TAG)], size=size, auto_reset=auto_reset)
iter_name = "MXNetIterator"
for batch_size, epochs, iter_num, total_iter_num, auto_reset, infinite \
in stop_iteration_case_generator():
check_stop_iter(fw_iter, iter_name, batch_size, epochs,
iter_num, total_iter_num, auto_reset, infinite)
def test_stop_iteration_mxnet_fail_multi():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
def fw_iter(pipe, size, auto_reset): return MXNetIterator(
pipe, [("data", MXNetIterator.DATA_TAG)], size=size, auto_reset=auto_reset)
check_stop_iter_fail_multi(fw_iter)
def test_stop_iteration_mxnet_fail_single():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
def fw_iter(pipe, size, auto_reset): return MXNetIterator(
pipe, [("data", MXNetIterator.DATA_TAG)], size=size, auto_reset=auto_reset)
check_stop_iter_fail_single(fw_iter)
def test_mxnet_iterator_wrapper_first_iteration():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
check_iterator_wrapper_first_iteration(
MXNetIterator, [("data", MXNetIterator.DATA_TAG)], size=100)
def test_mxnet_external_source_autoreset():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
check_external_source_autoreset(MXNetIterator, [(
"data", MXNetIterator.DATA_TAG)], to_np=lambda x: x[0].data[0].asnumpy())
def test_mxnet_external_source_do_not_prepare():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
check_external_source_autoreset(MXNetIterator, [("data", MXNetIterator.DATA_TAG)],
to_np=lambda x: x[0].data[0].asnumpy(),
prepare_first_batch=False)
def check_mxnet_iterator_properties(prepare_ahead):
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
def data_to_np(x):
return x.data[0].asnumpy()
def label_to_np(x):
return x.label[0].asnumpy()
max_batch_size = 4
iter_limit = 4
runs = 3
test_data_shape = [2, 3, 4]
test_label_shape = [2, 7, 5]
i = 0
dataset = [
[
[np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8)
for _ in range(max_batch_size)],
[np.random.randint(0, 255, size=test_label_shape, dtype=np.uint8)
for _ in range(max_batch_size)]
]
for _ in range(iter_limit)
]
def get_data():
nonlocal i
if i == iter_limit:
i = 0
raise StopIteration
out = dataset[i]
i += 1
return out
pipe = Pipeline(batch_size=max_batch_size, num_threads=1, device_id=0)
with pipe:
outs = fn.external_source(source=get_data, num_outputs=2)
pipe.set_outputs(*outs)
it = MXNetIterator([pipe], [("data", MXNetIterator.DATA_TAG),
("label", MXNetIterator.LABEL_TAG)], auto_reset=True,
prepare_first_batch=prepare_ahead)
counter = 0
assert getattr(it, 'provide_data')[0].shape == tuple([max_batch_size] + test_data_shape)
assert getattr(it, 'provide_label')[0].shape == tuple([max_batch_size] + test_label_shape)
for _ in range(runs):
for j, data in enumerate(it):
assert (data_to_np(data[0]) == np.stack(dataset[j][0])).all()
assert (label_to_np(data[0]) == np.stack(dataset[j][1])).all()
assert getattr(it, 'provide_data')[0].shape == \
tuple([max_batch_size] + test_data_shape)
assert getattr(it, 'provide_label')[0].shape == \
tuple([max_batch_size] + test_label_shape)
counter += 1
assert counter == iter_limit * runs
def test_mxnet_iterator_properties():
for prep in [True, False]:
yield check_mxnet_iterator_properties, prep
def test_mxnet_external_source_variable_size_pass():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
check_external_source_variable_size(MXNetIterator, [(
"data", MXNetIterator.DATA_TAG)], to_np=lambda x: x.data[0].asnumpy(), dynamic_shape=True)
def test_mxnet_external_source_variable_size_fail():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
assert_raises(AssertionError, check_external_source_variable_size, MXNetIterator,
[("data", MXNetIterator.DATA_TAG)], to_np=lambda x: x.data[0].asnumpy(),
iter_size=5, dynamic_shape=True)
# Gluon
def test_stop_iteration_gluon():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
def fw_iter(pipe, size, auto_reset): return GluonIterator(
pipe, size, output_types=[GluonIterator.DENSE_TAG], auto_reset=auto_reset)
iter_name = "GluonIterator"
for batch_size, epochs, iter_num, total_iter_num, auto_reset, infinite \
in stop_iteration_case_generator():
yield check_stop_iter, fw_iter, iter_name, batch_size, epochs, iter_num, \
total_iter_num, auto_reset, infinite
def test_stop_iteration_gluon_fail_multi():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
def fw_iter(pipe, size, auto_reset): return GluonIterator(
pipe, size, auto_reset=auto_reset)
check_stop_iter_fail_multi(fw_iter)
def test_stop_iteration_gluon_fail_single():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
def fw_iter(pipe, size, auto_reset): return GluonIterator(
pipe, size=size, auto_reset=auto_reset)
check_stop_iter_fail_single(fw_iter)
def test_gluon_iterator_wrapper_first_iteration():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
check_iterator_wrapper_first_iteration(GluonIterator, output_types=[
GluonIterator.DENSE_TAG], size=100)
def test_gluon_external_source_autoreset():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
check_external_source_autoreset(GluonIterator, output_types=[
GluonIterator.DENSE_TAG], to_np=lambda x: x[0][0].asnumpy())
def test_gluon_external_source_do_not_prepare():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
check_external_source_autoreset(GluonIterator, output_types=[
GluonIterator.DENSE_TAG], to_np=lambda x: x[0][0].asnumpy(),
prepare_first_batch=False)
def test_gluon_external_source_variable_size_pass():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
check_external_source_variable_size(GluonIterator, output_types=[
GluonIterator.DENSE_TAG], to_np=lambda x: x[0].asnumpy())
def test_gluon_external_source_variable_size_fail():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
assert_raises(AssertionError, check_external_source_variable_size, GluonIterator, output_types=[
GluonIterator.DENSE_TAG], to_np=lambda x: x[0].asnumpy(), iter_size=5)
# PyTorch
def test_stop_iteration_pytorch():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
def fw_iter(pipe, size, auto_reset): return PyTorchIterator(
pipe, output_map=["data"], size=size, auto_reset=auto_reset)
iter_name = "PyTorchIterator"
for batch_size, epochs, iter_num, total_iter_num, auto_reset, infinite \
in stop_iteration_case_generator():
yield check_stop_iter, fw_iter, iter_name, batch_size, epochs, iter_num, \
total_iter_num, auto_reset, infinite
def test_stop_iteration_pytorch_fail_multi():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
def fw_iter(pipe, size, auto_reset): return PyTorchIterator(
pipe, output_map=["data"], size=size, auto_reset=auto_reset)
check_stop_iter_fail_multi(fw_iter)
def test_stop_iteration_pytorch_fail_single():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
def fw_iter(pipe, size, auto_reset): return PyTorchIterator(
pipe, output_map=["data"], size=size, auto_reset=auto_reset)
check_stop_iter_fail_single(fw_iter)
def test_pytorch_iterator_wrapper_first_iteration():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
check_iterator_wrapper_first_iteration(
PyTorchIterator, output_map=["data"], size=100)
def test_pytorch_external_source_autoreset():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
check_external_source_autoreset(PyTorchIterator, output_map=["data"],
to_np=lambda x: x[0]["data"].numpy())
def test_pytorch_external_source_do_not_prepare():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
check_external_source_autoreset(PyTorchIterator, output_map=["data"],
to_np=lambda x: x[0]["data"].numpy(), prepare_first_batch=False)
def test_pytorch_external_source_variable_size_pass():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
check_external_source_variable_size(PyTorchIterator, output_map=["data"],
to_np=lambda x: x["data"].numpy(), dynamic_shape=True)
def test_pytorch_external_source_variable_size_fail():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
assert_raises(AssertionError, check_external_source_variable_size, PyTorchIterator, output_map=[
"data"], to_np=lambda x: x["data"].numpy(), iter_size=5, dynamic_shape=True)
# PaddlePaddle
def test_stop_iteration_paddle():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
def fw_iter(pipe, size, auto_reset): return PaddleIterator(
pipe, output_map=["data"], size=size, auto_reset=auto_reset)
iter_name = "PaddleIterator"
for batch_size, epochs, iter_num, total_iter_num, auto_reset, infinite \
in stop_iteration_case_generator():
yield check_stop_iter, fw_iter, iter_name, batch_size, epochs, iter_num, \
total_iter_num, auto_reset, infinite
def test_stop_iteration_paddle_fail_multi():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
def fw_iter(pipe, size, auto_reset): return PaddleIterator(
pipe, output_map=["data"], size=size, auto_reset=auto_reset)
check_stop_iter_fail_multi(fw_iter)
def test_stop_iteration_paddle_fail_single():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
def fw_iter(pipe, size, auto_reset): return PaddleIterator(
pipe, output_map=["data"], size=size, auto_reset=auto_reset)
check_stop_iter_fail_single(fw_iter)
def test_paddle_iterator_wrapper_first_iteration():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
check_iterator_wrapper_first_iteration(
PaddleIterator, output_map=["data"], size=100)
def test_paddle_external_source_autoreset():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
check_external_source_autoreset(PaddleIterator, output_map=["data"],
to_np=lambda x: np.array(x[0]["data"]))
def test_paddle_external_source_do_not_prepare():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
check_external_source_autoreset(PaddleIterator, output_map=["data"],
to_np=lambda x: np.array(x[0]["data"]),
prepare_first_batch=False)
def test_paddle_external_source_variable_size_pass():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
check_external_source_variable_size(PaddleIterator, output_map=["data"],
to_np=lambda x: np.array(x["data"]), dynamic_shape=True)
def test_paddle_external_source_variable_size_fail():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
assert_raises(AssertionError, check_external_source_variable_size, PaddleIterator, output_map=[
"data"], to_np=lambda x: np.array(x["data"]), iter_size=5, dynamic_shape=True)
# JAX
def test_stop_iteration_jax():
from nvidia.dali.plugin.jax import DALIGenericIterator as JaxIterator
def fw_iter(pipe, size, auto_reset): return JaxIterator(
pipe, output_map=["data"], size=size, auto_reset=auto_reset)
iter_name = "JaxIterator"
for batch_size, epochs, iter_num, total_iter_num, auto_reset, infinite \
in stop_iteration_case_generator():
yield check_stop_iter, fw_iter, iter_name, batch_size, epochs, iter_num, \
total_iter_num, auto_reset, infinite
def test_stop_iteration_jax_fail_multi():
from nvidia.dali.plugin.jax import DALIGenericIterator as JaxIterator
def fw_iter(pipe, size, auto_reset): return JaxIterator(
pipe, output_map=["data"], size=size, auto_reset=auto_reset)
check_stop_iter_fail_multi(fw_iter)
def test_stop_iteration_jax_fail_single():
from nvidia.dali.plugin.jax import DALIGenericIterator as JaxIterator
def fw_iter(pipe, size, auto_reset): return JaxIterator(
pipe, output_map=["data"], size=size, auto_reset=auto_reset)
check_stop_iter_fail_single(fw_iter)
def test_jax_iterator_wrapper_first_iteration():
from nvidia.dali.plugin.jax import DALIGenericIterator as JaxIterator
check_iterator_wrapper_first_iteration(
JaxIterator, output_map=["data"], size=100)
def test_jax_external_source_autoreset():
from nvidia.dali.plugin.jax import DALIGenericIterator as JaxIterator
check_external_source_autoreset(JaxIterator, output_map=["data"],
to_np=lambda x: x["data"])
def test_jax_external_source_do_not_prepare():
from nvidia.dali.plugin.jax import DALIGenericIterator as JaxIterator
check_external_source_autoreset(JaxIterator, output_map=["data"],
to_np=lambda x: x["data"], prepare_first_batch=False)
def check_prepare_first_batch(Iterator, *args, to_np=None, **kwargs):
max_batch_size = 4
iter_limit = 4
runs = 3
test_data_shape = [2, 3, 4]
i = 0
dataset = [[[np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8)
for _ in range(max_batch_size)]] for _ in range(iter_limit)]
def get_data():
nonlocal i
if i == iter_limit:
i = 0
raise StopIteration
out = dataset[i]
i += 1
return out
pipe = Pipeline(batch_size=max_batch_size, num_threads=1, device_id=0)
with pipe:
outs = fn.external_source(source=get_data, num_outputs=1)
pipe.set_outputs(*outs)
it = Iterator([pipe], *args, auto_reset=True, prepare_first_batch=False, **kwargs)
counter = 0
for r in range(runs):
if r == 0:
# when prepare_first_batch=False pipeline should not be run until first call to next(it)
assert i == 0, "external_source should not be run yet"
for j, data in enumerate(it):
if not isinstance(data, dict):
data = data[0]
assert (to_np(data) == np.concatenate(dataset[j])).all()
counter += 1
assert counter == iter_limit * runs
def test_mxnet_prepare_first_batch():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
check_prepare_first_batch(MXNetIterator, [("data", MXNetIterator.DATA_TAG)],
to_np=lambda x: x.data[0].asnumpy(), dynamic_shape=True)
def test_gluon_prepare_first_batch():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
check_prepare_first_batch(GluonIterator, output_types=[GluonIterator.DENSE_TAG],
to_np=lambda x: x[0].asnumpy())
def test_pytorch_prepare_first_batch():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
check_prepare_first_batch(PyTorchIterator, output_map=["data"],
to_np=lambda x: x["data"].numpy())
def test_paddle_prepare_first_batch():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
check_prepare_first_batch(PaddleIterator, output_map=["data"],
to_np=lambda x: np.array(x["data"]))
def test_jax_prepare_first_batch():
from nvidia.dali.plugin.jax import DALIGenericIterator as JaxIterator
check_prepare_first_batch(JaxIterator, output_map=["data"],
to_np=lambda x: np.array(x["data"]))
@pipeline_def
def feed_ndarray_test_pipeline():
return np.array([1], dtype=np.float)
def test_mxnet_feed_ndarray():
from nvidia.dali.plugin.mxnet import feed_ndarray
import mxnet
pipe = feed_ndarray_test_pipeline(batch_size=1, num_threads=1, device_id=0)
pipe.build()
out = pipe.run()[0]
mxnet_tensor = mxnet.nd.empty([1], None, np.int8)
assert_raises(AssertionError, feed_ndarray, out, mxnet_tensor,
glob="The element type of DALI Tensor/TensorList doesn't match "
"the element type of the target MXNet NDArray")
def test_pytorch_feed_ndarray():
from nvidia.dali.plugin.pytorch import feed_ndarray
import torch
pipe = feed_ndarray_test_pipeline(batch_size=1, num_threads=1, device_id=0)
pipe.build()
out = pipe.run()[0]
torch_tensor = torch.empty((1), dtype=torch.int8, device='cpu')
assert_raises(AssertionError, feed_ndarray, out, torch_tensor,
glob="The element type of DALI Tensor/TensorList doesn't match "
"the element type of the target PyTorch Tensor:")
# last_batch_policy type check
def check_iterator_build_error(ErrorType, Iterator, glob, *args, **kwargs):
batch_size = 4
num_gpus = 1
pipes, _ = create_pipeline(
lambda gpu: create_coco_pipeline(batch_size=batch_size, num_threads=4, shard_id=gpu,
num_gpus=num_gpus, data_paths=data_sets[0],
random_shuffle=True, stick_to_shard=False,
shuffle_after_epoch=False, pad_last_batch=False),
batch_size, num_gpus
)
with assert_raises(ErrorType, glob=glob):
Iterator(pipes, size=pipes[0].epoch_size("Reader"), *args, **kwargs)
def test_pytorch_wrong_last_batch_policy_type():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
check_iterator_build_error(ValueError, PyTorchIterator,
glob="Wrong type for `last_batch_policy`.",
output_map=["data"], last_batch_policy='FILL')
def test_paddle_wrong_last_batch_policy_type():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
check_iterator_build_error(ValueError, PaddleIterator,
glob="Wrong type for `last_batch_policy`.",
output_map=["data"], last_batch_policy='FILL')
def test_mxnet_wrong_last_batch_policy_type():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
check_iterator_build_error(ValueError, MXNetIterator,
glob="Wrong type for `last_batch_policy`.",
output_map=[("data", MXNetIterator.DATA_TAG)],
last_batch_policy='FILL')
def test_gluon_wrong_last_batch_policy_type():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
check_iterator_build_error(ValueError, GluonIterator,
glob="Wrong type for `last_batch_policy`.",
output_types=[GluonIterator.DENSE_TAG], last_batch_policy='FILL')
def test_jax_wrong_last_batch_policy_type():
from nvidia.dali.plugin.jax import DALIGenericIterator as JaxIterator
check_iterator_build_error(ValueError, JaxIterator,
glob="Wrong type for `last_batch_policy`.",
output_map=["data"],
last_batch_policy='FILL')
def test_jax_unsupported_last_batch_policy_type():
from nvidia.dali.plugin.jax import DALIGenericIterator as JaxIterator
check_iterator_build_error(AssertionError, JaxIterator,
glob="JAX iterator does not support partial last batch policy.",
output_map=["data"],
last_batch_policy=LastBatchPolicy.PARTIAL)
def check_autoreset_iter(fw_iterator, extract_data, auto_reset_op, policy):
batch_size = 2
number_of_samples = 11
images_files = [__file__]*number_of_samples
labels = list(range(number_of_samples))
@pipeline_def
def BoringPipeline():
_, ls = fn.readers.file(files=images_files, labels=labels,
stick_to_shard=True, name="reader", pad_last_batch=True)
return ls
pipeline = BoringPipeline(batch_size=batch_size, device_id=0, num_threads=1)
loader = fw_iterator(pipeline, reader_name="reader", auto_reset=auto_reset_op,
last_batch_policy=policy)
for _ in range(2):
loader_iter = iter(loader)
for i in range(len(loader_iter)):
data = next(loader_iter)
if not isinstance(data, dict):
data = data[0]
for j, d in enumerate(extract_data(data)):
if policy is LastBatchPolicy.FILL:
if i * batch_size + j >= number_of_samples:
assert d[0] == number_of_samples - 1, f"{d[0]} {number_of_samples - 1}"
else:
assert d[0] == i * batch_size + j, f"{d[0]} {i * batch_size + j}"
else:
assert d[0] == i * batch_size + j, f"{d[0]} {i * batch_size + j}"
def test_mxnet_autoreset_iter():
from nvidia.dali.plugin.mxnet import DALIGenericIterator as MXNetIterator
for auto_reset_op in ["yes", "no"]:
for policy in [LastBatchPolicy.FILL, LastBatchPolicy.DROP, LastBatchPolicy.PARTIAL]:
def fw_iterator(pipeline, reader_name, auto_reset, last_batch_policy):
return MXNetIterator(pipeline, [("data", MXNetIterator.DATA_TAG)],
reader_name=reader_name, auto_reset=auto_reset,
last_batch_policy=last_batch_policy)
def extract_data(x):
data = x.data[0].asnumpy()
data = data[0:-x.pad]
return data
yield check_autoreset_iter, fw_iterator, extract_data, auto_reset_op, policy
def test_gluon_autoreset_iter():
from nvidia.dali.plugin.mxnet import DALIGluonIterator as GluonIterator
for auto_reset_op in ["yes", "no"]:
for policy in [LastBatchPolicy.FILL, LastBatchPolicy.DROP, LastBatchPolicy.PARTIAL]:
def fw_iterator(pipeline, reader_name, auto_reset, last_batch_policy):
return GluonIterator(pipeline, reader_name=reader_name, auto_reset=auto_reset,
last_batch_policy=last_batch_policy)
def extract_data(x):
return x[0].asnumpy()
yield check_autoreset_iter, fw_iterator, extract_data, auto_reset_op, policy
def test_pytorch_autoreset_iter():
from nvidia.dali.plugin.pytorch import DALIGenericIterator as PyTorchIterator
for auto_reset_op in ["yes", "no"]:
for policy in [LastBatchPolicy.FILL, LastBatchPolicy.DROP, LastBatchPolicy.PARTIAL]:
def fw_iterator(pipeline, reader_name, auto_reset, last_batch_policy):
return PyTorchIterator(pipeline, output_map=["data"], reader_name=reader_name,
auto_reset=auto_reset,
last_batch_policy=last_batch_policy)
def extract_data(x):
return x["data"].numpy()
yield check_autoreset_iter, fw_iterator, extract_data, auto_reset_op, policy
def test_paddle_autoreset_iter():
from nvidia.dali.plugin.paddle import DALIGenericIterator as PaddleIterator
for auto_reset_op in ["yes", "no"]:
for policy in [LastBatchPolicy.FILL, LastBatchPolicy.DROP, LastBatchPolicy.PARTIAL]:
def fw_iterator(pipeline, reader_name, auto_reset, last_batch_policy):
return PaddleIterator(pipeline, output_map=["data"], reader_name=reader_name,
auto_reset=auto_reset,
last_batch_policy=last_batch_policy)
def extract_data(x):
return np.array(x["data"])
yield check_autoreset_iter, fw_iterator, extract_data, auto_reset_op, policy
def test_jax_autoreset_iter():
from nvidia.dali.plugin.jax import DALIGenericIterator as JaxIterator
for auto_reset_op in ["yes", "no"]:
for policy in [LastBatchPolicy.FILL, LastBatchPolicy.DROP]:
def fw_iterator(pipeline, reader_name, auto_reset, last_batch_policy):
return JaxIterator(
pipeline,
output_map=["data"],
reader_name=reader_name,
auto_reset=auto_reset,
last_batch_policy=last_batch_policy)
def extract_data(x):
return np.array(x["data"])
yield check_autoreset_iter, fw_iterator, extract_data, auto_reset_op, policy
|
DALI-main
|
dali/test/python/test_fw_iterators.py
|
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. 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 os
from nvidia.dali import fn
from nvidia.dali import pipeline_def
from nvidia.dali import ops
from nvidia.dali import tensors
from nvidia.dali.experimental import eager
from nose_utils import assert_raises, raises
from test_utils import get_dali_extra_path
@raises(RuntimeError, glob="Argument '*' is not supported by eager operator 'crop'.")
def _test_disqualified_argument(key):
tl = tensors.TensorListCPU(np.zeros((8, 256, 256, 3)))
eager.crop(tl, crop=[64, 64], **{key: 0})
def test_disqualified_arguments():
for arg in ['bytes_per_sample_hint', 'preserve', 'seed']:
yield _test_disqualified_argument, arg
@raises(TypeError, glob="unsupported operand type*")
def test_arithm_op_context_manager_disabled():
tl_1 = tensors.TensorListCPU(np.ones((8, 16, 16)))
tl_2 = tensors.TensorListCPU(np.ones((8, 16, 16)))
tl_1 + tl_2
def test_arithm_op_context_manager_enabled():
eager.arithmetic(True)
tl_1 = tensors.TensorListCPU(np.ones((8, 16, 16)))
tl_2 = tensors.TensorListCPU(np.ones((8, 16, 16)))
assert np.array_equal((tl_1 + tl_2).as_array(), np.full(shape=(8, 16, 16), fill_value=2))
eager.arithmetic(False)
def test_arithm_op_context_manager_nested():
tl_1 = tensors.TensorListCPU(np.ones((8, 16, 16)))
tl_2 = tensors.TensorListCPU(np.ones((8, 16, 16)))
expected_sum = np.full(shape=(8, 16, 16), fill_value=2)
with eager.arithmetic():
assert np.array_equal((tl_1 + tl_2).as_array(), expected_sum)
with eager.arithmetic(False):
with assert_raises(TypeError, glob="unsupported operand type*"):
tl_1 + tl_2
assert np.array_equal((tl_1 + tl_2).as_array(), expected_sum)
def test_arithm_op_context_manager_deep_nested():
tl_1 = tensors.TensorListCPU(np.ones((8, 16, 16)))
tl_2 = tensors.TensorListCPU(np.ones((8, 16, 16)))
expected_sum = np.full(shape=(8, 16, 16), fill_value=2)
eager.arithmetic(True)
assert np.array_equal((tl_1 + tl_2).as_array(), expected_sum)
with eager.arithmetic(False):
with assert_raises(TypeError, glob="unsupported operand type*"):
tl_1 + tl_2
with eager.arithmetic(True):
np.array_equal((tl_1 + tl_2).as_array(), expected_sum)
with eager.arithmetic(False):
with assert_raises(TypeError, glob="unsupported operand type*"):
tl_1 + tl_2
with assert_raises(TypeError, glob="unsupported operand type*"):
tl_1 + tl_2
assert np.array_equal((tl_1 + tl_2).as_array(), expected_sum)
eager.arithmetic(False)
def test_identical_rng_states():
eager_state_1 = eager.rng_state(seed=42)
eager_state_2 = eager.rng_state(seed=42)
out_1_1 = eager_state_1.random.normal(shape=[5, 5], batch_size=8)
out_1_2 = eager_state_1.noise.gaussian(out_1_1)
out_1_3 = eager_state_1.random.normal(shape=[5, 5], batch_size=8)
out_2_1 = eager_state_2.random.normal(shape=[5, 5], batch_size=8)
out_2_2 = eager_state_2.noise.gaussian(out_2_1)
out_2_3 = eager_state_2.random.normal(shape=[5, 5], batch_size=8)
assert np.allclose(out_1_1.as_tensor(), out_2_1.as_tensor())
assert np.allclose(out_1_2.as_tensor(), out_2_2.as_tensor())
assert np.allclose(out_1_3.as_tensor(), out_2_3.as_tensor())
def test_identical_rng_states_interleaved():
eager_state_1 = eager.rng_state(seed=42)
eager_state_2 = eager.rng_state(seed=42)
out_1_1 = eager_state_1.random.normal(shape=[5, 5], batch_size=8)
eager_state_1.random.normal(shape=[6, 6], batch_size=8)
eager_state_1.noise.gaussian(out_1_1)
out_1_2 = eager_state_1.random.normal(shape=[5, 5], batch_size=8)
out_2_1 = eager_state_2.random.normal(shape=[5, 5], batch_size=8)
out_2_2 = eager_state_2.random.normal(shape=[5, 5], batch_size=8)
assert np.allclose(out_1_1.as_tensor(), out_2_1.as_tensor())
assert np.allclose(out_1_2.as_tensor(), out_2_2.as_tensor())
def test_objective_eager_resize():
from nvidia.dali._utils import eager_utils
resize_class = eager_utils._eager_op_object_factory(ops.python_op_factory('Resize'), 'Resize')
tl = tensors.TensorListCPU(np.random.default_rng().integers(
256, size=(8, 200, 200, 3), dtype=np.uint8))
obj_resize = resize_class(resize_x=50, resize_y=50)
out_obj = obj_resize(tl)
out_fun = eager.resize(tl, resize_x=50, resize_y=50)
assert np.array_equal(out_obj.as_tensor(), out_fun.as_tensor())
@pipeline_def(num_threads=3, device_id=0)
def mixed_image_decoder_pipeline(file_root, seed):
jpeg, _ = fn.readers.file(file_root=file_root, seed=seed)
out = fn.decoders.image(jpeg, device="mixed")
return out
def test_mixed_devices_decoder():
""" Tests hidden functionality of exposing eager operators as classes. """
seed = 42
batch_size = 8
file_root = os.path.join(get_dali_extra_path(), 'db/single/jpeg')
pipe = mixed_image_decoder_pipeline(file_root, seed, batch_size=batch_size)
pipe.build()
pipe_out, = pipe.run()
jpeg, _ = next(eager.readers.file(file_root=file_root, batch_size=batch_size, seed=seed))
eager_out = eager.decoders.image(jpeg, device="gpu")
assert len(pipe_out) == len(eager_out)
with eager.arithmetic():
for comp_tensor in (pipe_out == eager_out):
assert np.all(comp_tensor.as_cpu())
|
DALI-main
|
dali/test/python/test_eager_operators.py
|
# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. 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.
def failure_test_trigger():
raise RuntimeError("This test is intended to always fail to allow for verification"
" of CI scripting.")
|
DALI-main
|
dali/test/python/test_trigger_failure.py
|
# Copyright (c) 2017-2018, NVIDIA CORPORATION. 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 nvidia.dali.pipeline import Pipeline
import nvidia.dali as dali
import nvidia.dali.ops as ops
import nvidia.dali.plugin_manager as plugin_manager
import unittest
import os
import numpy as np
import tempfile
test_bin_dir = os.path.dirname(dali.__file__) + "/test"
batch_size = 4
W = 800
H = 600
C = 3
class ExternalInputIterator(object):
def __init__(self, batch_size):
self.batch_size = batch_size
def __iter__(self):
self.i = 0
self.n = self.batch_size
return self
def __next__(self):
batch = []
labels = []
for _ in range(self.batch_size):
batch.append(np.array(np.random.rand(H, W, C) * 255, dtype=np.uint8))
labels.append(np.array(np.random.rand(1) * 10, dtype=np.uint8))
self.i = (self.i + 1) % self.n
return (batch, labels)
next = __next__
eii = ExternalInputIterator(batch_size)
iterator = iter(eii)
class CustomPipeline(Pipeline):
def __init__(self, batch_size, num_threads, device_id):
super(CustomPipeline, self).__init__(batch_size, num_threads, device_id)
self.inputs = ops.ExternalSource()
self.custom_dummy = ops.CustomDummy(device="gpu")
def define_graph(self):
self.images = self.inputs()
custom_dummy_out = self.custom_dummy(self.images.gpu())
return (self.images, custom_dummy_out)
def iter_setup(self):
(images, labels) = iterator.next()
self.feed_input(self.images, images)
class TestLoadedPlugin(unittest.TestCase):
def test_sysconfig_provides_non_empty_flags(self):
import nvidia.dali.sysconfig as dali_sysconfig
assert "" != dali_sysconfig.get_include_flags()
assert "" != dali_sysconfig.get_compile_flags()
assert "" != dali_sysconfig.get_link_flags()
assert "" != dali_sysconfig.get_include_dir()
assert "" != dali_sysconfig.get_lib_dir()
def test_load_unexisting_library(self):
with self.assertRaises(RuntimeError):
plugin_manager.load_library("not_a_dali_plugin.so")
def test_load_existing_but_not_a_library(self):
tmp = tempfile.NamedTemporaryFile(delete=False)
for _ in range(10):
tmp.write(b"0xdeadbeef\n")
tmp.close()
with self.assertRaises(RuntimeError):
plugin_manager.load_library(tmp.name)
os.remove(tmp.name)
def test_load_custom_operator_plugin(self):
with self.assertRaises(AttributeError):
print(ops.CustomDummy)
plugin_manager.load_library(test_bin_dir + "/libcustomdummyplugin.so")
print(ops.CustomDummy)
def test_pipeline_including_custom_plugin(self):
plugin_manager.load_library(test_bin_dir + "/libcustomdummyplugin.so")
pipe = CustomPipeline(batch_size, 1, 0)
pipe.build()
pipe_out = pipe.run()
print(pipe_out)
images, output = pipe_out
output_cpu = output.as_cpu()
assert len(images) == batch_size
assert len(output_cpu) == batch_size
for i in range(len(images)):
img = images.at(i)
out = output_cpu.at(i)
assert img.shape == out.shape
np.testing.assert_array_equal(img, out)
def test_python_operator_and_custom_plugin(self):
plugin_manager.load_library(test_bin_dir + "/libcustomdummyplugin.so")
ops.readers.TFRecord(path="dummy", index_path="dummy", features={})
if __name__ == '__main__':
unittest.main()
|
DALI-main
|
dali/test/python/test_plugin_manager.py
|
# Copyright (c) 2019-2021, NVIDIA CORPORATION & AFFILIATES. 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 numpy as np
import nvidia.dali.fn as fn
import nvidia.dali.plugin.tf as dali_tf
import nvidia.dali.types as types
import os
import tensorflow as tf
from contextlib import contextmanager
from nose import SkipTest
from nvidia.dali.pipeline import Pipeline
from tensorflow.python.client import device_lib
from test_utils import to_array, get_dali_extra_path
def skip_for_incompatible_tf():
if not dali_tf.dataset_distributed_compatible_tensorflow():
raise SkipTest('This feature is enabled for TF 2.5.0 and higher')
def skip_inputs_for_incompatible_tf():
if not dali_tf.dataset_inputs_compatible_tensorflow():
raise SkipTest('This feature is enabled for TF 2.4.1 and higher')
def num_available_gpus():
local_devices = device_lib.list_local_devices()
num_gpus = sum(1 for device in local_devices if device.device_type == 'GPU')
if not math.log2(num_gpus).is_integer():
raise RuntimeError('Unsupported number of GPUs. This test can run on: 2^n GPUs.')
return num_gpus
def available_gpus():
devices = []
for device_id in range(num_available_gpus()):
devices.append('/gpu:{0}'.format(device_id))
return devices
@contextmanager
def expect_iter_end(should_raise, exception_type):
try:
yield
except exception_type:
if should_raise:
raise
# ################################################################################################ #
#
# To test custom DALI pipeline and DALIDataset wrapper for it all the `run_tf_dataset_*`
# routines accept two arguments:
# * get_pipeline_desc
# * to_dataset
# Both are callbacks, examples of those are respectively:
# * get_image_pipeline
# * to_image_dataset
#
# Respective signatures:
# get_pipeline_desc(batch_size, num_threads, device, device_id, shard_id, num_shards,
# def_for_dataset) -> nvidia.dali.pipeline, shapes, dtypes
# `def_for_dataset` - indicates if this function is invoked to create a baseline standalone
# pipeline (False), or it will be wrapped into TF dataset (True)
# It is supposed to return a tuple that also describes the shapes and dtypes returned by the pipe.
#
#
# to_image_dataset(image_pipeline_desc, device_str) -> tf.data.Dataset
# image_pipeline_desc will be the tuple returned by the `get_pipeline_desc`, device_str
# is the expected placement of the tested DALIDataset
#
# ################################################################################################ #
def get_mix_size_image_pipeline(batch_size, num_threads, device, device_id=0, shard_id=0,
num_shards=1, def_for_dataset=False):
test_data_root = get_dali_extra_path()
file_root = os.path.join(test_data_root, 'db', 'coco_dummy', 'images')
annotations_file = os.path.join(test_data_root, 'db', 'coco_dummy', 'instances.json')
pipe = Pipeline(batch_size, num_threads, device_id)
with pipe:
jpegs, _, _, image_ids = fn.readers.coco(
file_root=file_root,
annotations_file=annotations_file,
shard_id=shard_id,
num_shards=num_shards,
ratio=False,
image_ids=True)
images = fn.decoders.image(
jpegs,
device=('mixed' if device == 'gpu' else 'cpu'),
output_type=types.RGB)
pipe.set_outputs(images)
shapes = ((batch_size, None, None, None),)
dtypes = (tf.float32,)
return pipe, shapes, dtypes
def get_image_pipeline(batch_size, num_threads, device, device_id=0, shard_id=0, num_shards=1,
def_for_dataset=False):
test_data_root = get_dali_extra_path()
file_root = os.path.join(test_data_root, 'db', 'coco_dummy', 'images')
annotations_file = os.path.join(test_data_root, 'db', 'coco_dummy', 'instances.json')
pipe = Pipeline(batch_size, num_threads, device_id)
with pipe:
jpegs, _, _, image_ids = fn.readers.coco(
file_root=file_root,
annotations_file=annotations_file,
shard_id=shard_id,
num_shards=num_shards,
ratio=False,
image_ids=True)
images = fn.decoders.image(
jpegs,
device=('mixed' if device == 'gpu' else 'cpu'),
output_type=types.RGB)
images = fn.resize(
images,
resize_x=224,
resize_y=224,
interp_type=types.INTERP_LINEAR)
images = fn.crop_mirror_normalize(
images,
dtype=types.FLOAT,
mean=[128., 128., 128.],
std=[1., 1., 1.])
if device == 'gpu':
image_ids = image_ids.gpu()
ids_reshaped = fn.reshape(image_ids, shape=[1, 1])
ids_int16 = fn.cast(image_ids, dtype=types.INT16)
pipe.set_outputs(images, ids_reshaped, ids_int16)
shapes = (
(batch_size, 3, 224, 224),
(batch_size, 1, 1),
(batch_size, 1))
dtypes = (
tf.float32,
tf.int32,
tf.int16)
return pipe, shapes, dtypes
def to_image_dataset(image_pipeline_desc, device_str):
dataset_pipeline, shapes, dtypes = image_pipeline_desc
with tf.device(device_str):
dali_dataset = dali_tf.DALIDataset(
pipeline=dataset_pipeline,
batch_size=dataset_pipeline.batch_size,
output_shapes=shapes,
output_dtypes=dtypes,
num_threads=dataset_pipeline.num_threads,
device_id=dataset_pipeline.device_id)
return dali_dataset
def get_dali_dataset_from_pipeline(pipeline_desc, device, device_id, to_dataset=to_image_dataset):
dali_dataset = to_dataset(pipeline_desc, '/{0}:{1}'.format(device, device_id))
return dali_dataset
def get_dali_dataset(batch_size, num_threads, device, device_id, num_devices=1,
get_pipeline_desc=get_image_pipeline, to_dataset=to_image_dataset):
shard_id = 0 if num_devices == 1 else device_id
dataset_pipeline = get_pipeline_desc(batch_size, num_threads, device, device_id, shard_id,
num_devices, def_for_dataset=True)
return get_dali_dataset_from_pipeline(dataset_pipeline, device, device_id, to_dataset)
def get_pipe_dataset(batch_size,
num_threads,
device,
device_id,
num_devices=1,
*,
dali_on_dev_0=True,
get_pipeline_desc=get_image_pipeline,
to_dataset=to_image_dataset):
shard_id = 0 if num_devices == 1 else device_id
tf_dataset = get_dali_dataset(batch_size, num_threads, device, device_id,
num_devices=num_devices, get_pipeline_desc=get_pipeline_desc,
to_dataset=to_dataset)
dali_pipeline, _, _ = get_pipeline_desc(batch_size, num_threads, device,
0 if dali_on_dev_0 else device_id, shard_id,
num_devices, def_for_dataset=False)
return dali_pipeline, tf_dataset
def run_dataset_in_graph(dali_datasets, iterations, to_stop_iter=False):
if not isinstance(dali_datasets, list):
dali_datasets = [dali_datasets]
dataset_results = []
initializers = [tf.compat.v1.global_variables_initializer()]
ops_to_run = []
for dali_dataset in dali_datasets:
iterator = tf.compat.v1.data.make_initializable_iterator(dali_dataset)
initializers.append(iterator.initializer)
ops_to_run.append(iterator.get_next())
with tf.compat.v1.Session() as sess:
sess.run(initializers)
with expect_iter_end(not to_stop_iter, tf.errors.OutOfRangeError):
for _ in range(iterations):
dataset_results.append(sess.run(ops_to_run))
return dataset_results
def run_dataset_eager_mode(dali_datasets, iterations, to_stop_iter=False):
if not isinstance(dali_datasets, list):
dali_datasets = [dali_datasets]
results = []
with expect_iter_end(not to_stop_iter, StopIteration):
for i, batch in zip(range(iterations), zip(*dali_datasets)):
results.append(batch)
return results
def run_pipeline(pipelines, iterations, device, to_stop_iter=False):
if not isinstance(pipelines, list):
pipelines = [pipelines]
for pipeline in pipelines:
pipeline.build()
results = []
with expect_iter_end(not to_stop_iter, StopIteration):
for _ in range(iterations):
shard_outputs = []
for pipeline in pipelines:
pipe_outputs = pipeline.run()
shard_outputs.append(tuple(to_array(result) for result in pipe_outputs))
results.append(tuple(shard_outputs))
return results
def compare(dataset_results, standalone_results, iterations=-1, num_devices=1):
if iterations == -1:
iterations = len(standalone_results)
# list [iterations] of tuple [devices] of tuple [outputs] of tensors representing batch
assert len(dataset_results) == iterations, \
f'Got {len(dataset_results)} dataset results for {iterations} iterations'
for it in range(iterations):
for device_id in range(num_devices):
for tf_data, dali_data in zip(dataset_results[it][device_id],
standalone_results[it][device_id]):
np.testing.assert_array_equal(tf_data, dali_data,
f'Iteration {it}, x = tf_data, y = DALI baseline')
def run_tf_dataset_graph(device, device_id=0, get_pipeline_desc=get_image_pipeline,
to_dataset=to_image_dataset, to_stop_iter=False):
tf.compat.v1.reset_default_graph()
batch_size = 12
num_threads = 4
iterations = 10
standalone_pipeline, dali_dataset = get_pipe_dataset(batch_size, num_threads, device, device_id,
get_pipeline_desc=get_pipeline_desc,
to_dataset=to_dataset)
dataset_results = run_dataset_in_graph(dali_dataset, iterations, to_stop_iter=to_stop_iter)
standalone_results = run_pipeline(standalone_pipeline, iterations, device,
to_stop_iter=to_stop_iter)
compare(dataset_results, standalone_results)
def run_tf_dataset_eager_mode(device, device_id=0, get_pipeline_desc=get_image_pipeline,
to_dataset=to_image_dataset, to_stop_iter=False):
batch_size = 12
num_threads = 4
iterations = 10
standalone_pipeline, dali_dataset = get_pipe_dataset(batch_size, num_threads, device, device_id,
get_pipeline_desc=get_pipeline_desc,
to_dataset=to_dataset)
dataset_results = run_dataset_eager_mode(dali_dataset, iterations, to_stop_iter=to_stop_iter)
standalone_results = run_pipeline(standalone_pipeline, iterations, device,
to_stop_iter=to_stop_iter)
compare(dataset_results, standalone_results)
def run_tf_dataset_multigpu_graph_manual_placement(get_pipeline_desc=get_image_pipeline,
to_dataset=to_image_dataset):
num_devices = num_available_gpus()
batch_size = 8
num_threads = 4
iterations = 8
dali_datasets = []
standalone_pipelines = []
for device_id in range(num_devices):
standalone_pipeline, dali_dataset = get_pipe_dataset(batch_size, num_threads, 'gpu',
device_id, num_devices,
get_pipeline_desc=get_pipeline_desc,
to_dataset=to_dataset,
dali_on_dev_0=False)
dali_datasets.append(dali_dataset)
standalone_pipelines.append(standalone_pipeline)
dataset_results = run_dataset_in_graph(dali_datasets, iterations)
standalone_results = run_pipeline(standalone_pipelines, iterations, 'gpu')
compare(dataset_results, standalone_results, iterations, num_devices)
def run_tf_dataset_multigpu_eager_manual_placement(get_pipeline_desc=get_image_pipeline,
to_dataset=to_image_dataset):
num_devices = num_available_gpus()
batch_size = 8
num_threads = 4
iterations = 8
dali_datasets = []
standalone_pipelines = []
for device_id in range(num_devices):
standalone_pipeline, dali_dataset = get_pipe_dataset(batch_size, num_threads, 'gpu',
device_id, num_devices,
get_pipeline_desc=get_pipeline_desc,
to_dataset=to_dataset,
dali_on_dev_0=False)
dali_datasets.append(dali_dataset)
standalone_pipelines.append(standalone_pipeline)
dataset_results = run_dataset_eager_mode(dali_datasets, iterations)
standalone_results = run_pipeline(standalone_pipelines, iterations, 'gpu')
compare(dataset_results, standalone_results, iterations, num_devices)
def per_replica_to_numpy(dataset_results, num_devices):
results = []
for sample in dataset_results:
new_sample = []
for device_id in range(num_devices):
new_batch = []
for output in range(len(sample[0])):
new_batch.append(sample[0][output].values[device_id].numpy())
new_sample.append(new_batch)
results.append(new_sample)
return results
def run_tf_dataset_multigpu_eager_mirrored_strategy(get_pipeline_desc=get_image_pipeline,
to_dataset=to_image_dataset):
num_devices = num_available_gpus()
batch_size = 8
num_threads = 4
iterations = 8
strategy = tf.distribute.MirroredStrategy(devices=available_gpus())
input_options = tf.distribute.InputOptions(
experimental_place_dataset_on_device=True,
experimental_fetch_to_device=False,
experimental_replication_mode=tf.distribute.InputReplicationMode.PER_REPLICA)
def dataset_fn(input_context):
return get_dali_dataset(batch_size, num_threads, 'gpu', input_context.input_pipeline_id,
num_devices, get_pipeline_desc=get_pipeline_desc,
to_dataset=to_dataset)
dali_datasets = [
strategy.distribute_datasets_from_function(dataset_fn, input_options)]
dataset_results = run_dataset_eager_mode(dali_datasets, iterations)
standalone_pipelines = []
for device_id in range(num_devices):
pipeline, _, _ = get_pipeline_desc(batch_size, num_threads, device='gpu',
device_id=device_id, shard_id=device_id,
num_shards=num_devices)
standalone_pipelines.append(pipeline)
standalone_results = run_pipeline(standalone_pipelines, iterations, 'gpu')
dataset_results = per_replica_to_numpy(dataset_results, num_devices)
compare(dataset_results, standalone_results, iterations, num_devices)
|
DALI-main
|
dali/test/python/test_utils_tensorflow.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION & AFFILIATES. 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 numpy as np
from typing import List, Union, Callable, Optional
from dataclasses import dataclass, field
from nvidia.dali import pipeline_def
import nvidia.dali.fn as fn
from nvidia.dali import types
import nvidia.dali.tensors as _Tensors
from test_utils import get_dali_extra_path, check_batch
data_root = get_dali_extra_path()
vid_file = os.path.join(data_root, 'db', 'video',
'sintel', 'sintel_trailer-720p.mp4')
@dataclass
class SampleDesc:
"""Context that the argument provider callback receives when prompted for parameter"""
rng: random.Random
frame_idx: int
sample_idx: int
batch_idx: int
sample: np.ndarray
@dataclass
class ArgDesc:
name: Union[str, int]
expandable_prefix: str
dest_device: str
layout: Optional[str] = None
def __post_init__(self):
assert self.is_positional_arg or self.dest_device != "gpu", \
"Named arguments on GPU are not supported"
assert not self.layout or self.layout.startswith(self.expandable_prefix)
@property
def is_positional_arg(self):
return isinstance(self.name, int)
class ArgCb:
"""
Describes a callback to be used as a per-sample/per-frame argument to the operator.
----------
`name` : Union[str, int]
String with the name of a named argument of the operator or an int if the data
should be passed as a positional input.
`cb` : Callable[[SampleDesc], np.ndarray]
Callback that based on the SampleDesc instance produces a single parameter for
specific sample/frame.
`is_per_frame` : bool
Flag if the cb should be run for every sample (sequence) or for every frame.
In the latter case, the argument is passed wrapped
in per-frame call to the operator.
`dest_device` : str
Controls whether the produced data should be passed to the operator in cpu or gpu memory.
If set to "gpu", the copy to gpu is added in the pipeline.
Applicable only to positional inputs.
"""
def __init__(self, name: Union[str, int], cb: Callable[[SampleDesc], np.ndarray],
is_per_frame: bool, dest_device: str = "cpu"):
self.desc = ArgDesc(name, "F" if is_per_frame else "", dest_device)
self.cb = cb
def __repr__(self):
return "ArgCb{}".format((self.cb, self.desc))
@dataclass
class ArgData:
desc: ArgDesc
data: List[List[np.ndarray]] = field(repr=False)
class ParamsProviderBase:
"""
Computes data to be passed as argument inputs in sequence processing tests, the `compute_params`
params should return a lists of ArgData describing inputs of the operator, while `expand_params`
should return corresponding unfolded/expanded ArgData to be used in the baseline pipeline.
"""
def __init__(self):
self.input_data = None
self.fixed_params = None
self.rng = None
self.unfolded_input = None
def setup(self, input_data: ArgData, fixed_params, rng):
self.input_data = input_data
self.fixed_params = fixed_params
self.rng = rng
def unfold_output(self, batches):
num_expand = len(self.input_data.desc.expandable_prefix)
return unfold_batch(batches, num_expand)
def unfold_output_layout(self, layout):
num_expand = len(self.input_data.desc.expandable_prefix)
return layout if not layout else layout[num_expand:]
def unfold_input(self) -> ArgData:
input_desc = self.input_data.desc
num_expand = len(input_desc.expandable_prefix)
unfolded_input = unfold_batches(self.input_data.data, num_expand)
if input_desc.layout:
unfolded_layout = input_desc.layout[num_expand:]
else:
unfolded_layout = input_desc.layout
self.unfolded_input = ArgData(
desc=ArgDesc(input_desc.name, "", input_desc.dest_device, unfolded_layout),
data=unfolded_input)
return self.unfolded_input
def compute_params(self) -> List[ArgData]:
raise NotImplementedError
def expand_params(self) -> List[ArgData]:
raise NotImplementedError
class ParamsProvider(ParamsProviderBase):
def __init__(self, input_params: List[ArgCb]):
super().__init__()
self.input_params = input_params
self.arg_input_data = None
self.expanded_params_data = None
def compute_params(self) -> List[ArgData]:
self.arg_input_data = compute_input_params_data(
self.input_data, self.rng, self.input_params)
return self.arg_input_data
def expand_params(self) -> List[ArgData]:
self.expanded_params_data = [
ArgData(
desc=ArgDesc(arg_data.desc.name, "", arg_data.desc.dest_device),
data=expand_arg_input(self.input_data, arg_data))
for arg_data in self.arg_input_data
]
return self.expanded_params_data
def __repr__(self):
class_name = repr(self.__class__.__name__).strip("'")
return f"{class_name}({repr(self.input_params)})"
def arg_data_node(arg_data: ArgData):
node = fn.external_source(dummy_source(arg_data.data), layout=arg_data.desc.layout)
if arg_data.desc.dest_device == "gpu":
node = node.gpu()
expandable_prefix = arg_data.desc.expandable_prefix
if expandable_prefix and expandable_prefix[0] == "F":
node = fn.per_frame(node)
return node
def as_batch(tensor):
if isinstance(tensor, _Tensors.TensorListGPU):
tensor = tensor.as_cpu()
return [np.array(sample, dtype=types.to_numpy_type(sample.dtype)) for sample in tensor]
def dummy_source(batches):
def inner():
while True:
for batch in batches:
yield batch
return inner
def unfold_batch(batch, num_expand):
assert num_expand >= 0
if num_expand == 0:
return batch
if num_expand > 1:
batch = [sample.reshape((-1,) + sample.shape[num_expand:])
for sample in batch]
return [frame for sample in batch for frame in sample]
def unfold_batches(batches, num_expand):
return [unfold_batch(batch, num_expand) for batch in batches]
def get_layout_prefix_len(layout, prefix):
for i, c in enumerate(layout):
if c not in prefix:
return i
return len(layout)
def expand_arg(expandable_layout, arg_has_frames, input_batch, arg_batch):
num_expand = len(expandable_layout)
assert 1 <= num_expand <= 2
assert all(c in "FC" for c in expandable_layout)
assert len(input_batch) == len(arg_batch)
expanded_batch = []
for input_sample, arg_sample in zip(input_batch, arg_batch):
if not arg_has_frames or len(arg_sample) == 1:
arg_sample = arg_sample if not arg_has_frames else arg_sample[0]
num_frames = np.prod(input_sample.shape[:num_expand])
expanded_batch.extend(arg_sample for _ in range(num_frames))
else:
frame_idx = expandable_layout.find("F")
assert frame_idx >= 0
assert len(arg_sample) == input_sample.shape[frame_idx]
if num_expand == 1:
expanded_batch.extend(
arg_frame for arg_frame in arg_sample)
else:
channel_idx = 1 - frame_idx
assert expandable_layout[channel_idx] == "C"
if channel_idx > frame_idx:
expanded_batch.extend(frame_arg for frame_arg in arg_sample for _ in range(
input_sample.shape[channel_idx]))
else:
expanded_batch.extend(frame_arg for _ in range(
input_sample.shape[channel_idx]) for frame_arg in arg_sample)
return expanded_batch
def expand_arg_input(input_data: ArgData, arg_data: ArgData):
"""
Expands the `arg_data` to match the sequence shape of input_data.
"""
assert arg_data.desc.expandable_prefix in ["F", ""]
assert len(input_data.data) == len(arg_data.data)
arg_has_frames = arg_data.desc.expandable_prefix == "F"
return [expand_arg(input_data.desc.expandable_prefix, arg_has_frames, input_batch, arg_batch)
for input_batch, arg_batch in zip(input_data.data, arg_data.data)]
def _test_seq_input(num_iters, operator_fn, fixed_params, input_params, input_data: ArgData, rng):
@pipeline_def
def pipeline(args_data: List[ArgData]):
pos_args = [
arg_data for arg_data in args_data if arg_data.desc.is_positional_arg]
pos_nodes = [None] * len(pos_args)
for arg_data in pos_args:
assert 0 <= arg_data.desc.name < len(pos_nodes)
assert pos_nodes[arg_data.desc.name] is None
pos_nodes[arg_data.desc.name] = arg_data_node(arg_data)
named_args = [
arg_data for arg_data in args_data if not arg_data.desc.is_positional_arg]
arg_nodes = {
arg_data.desc.name: arg_data_node(arg_data)
for arg_data in named_args}
output = operator_fn(*pos_nodes, **fixed_params, **arg_nodes)
return output
assert num_iters >= len(input_data.data)
max_batch_size = max(len(batch) for batch in input_data.data)
params_provider = input_params if isinstance(
input_params, ParamsProviderBase) else ParamsProvider(input_params)
params_provider.setup(input_data, fixed_params, rng)
args_data = params_provider.compute_params()
seq_pipe = pipeline(args_data=[input_data, *args_data],
batch_size=max_batch_size, num_threads=4,
device_id=0)
unfolded_input = params_provider.unfold_input()
expanded_args_data = params_provider.expand_params()
max_uf_batch_size = max(len(batch) for batch in unfolded_input.data)
baseline_pipe = pipeline(args_data=[unfolded_input, *expanded_args_data],
batch_size=max_uf_batch_size, num_threads=4,
device_id=0)
seq_pipe.build()
baseline_pipe.build()
for _ in range(num_iters):
(seq_batch,) = seq_pipe.run()
(baseline_batch,) = baseline_pipe.run()
assert params_provider.unfold_output_layout(seq_batch.layout()) == baseline_batch.layout()
batch = params_provider.unfold_output(as_batch(seq_batch))
baseline_batch = as_batch(baseline_batch)
assert len(batch) == len(baseline_batch)
check_batch(batch, baseline_batch, len(batch))
def get_input_arg_per_sample(input_data, param_cb, rng):
return [[
param_cb(SampleDesc(rng, None, sample_idx, batch_idx, sample))
for sample_idx, sample in enumerate(batch)]
for batch_idx, batch in enumerate(input_data.data)]
def get_input_arg_per_frame(input_data: ArgData, param_cb, rng, check_broadcasting):
frame_idx = input_data.desc.expandable_prefix.find("F")
assert frame_idx >= 0
def arg_for_sample(sample_idx, batch_idx, sample):
if check_broadcasting and rng.randint(1, 4) == 1:
return np.array([param_cb(SampleDesc(rng, 0, sample_idx, batch_idx, sample))])
num_frames = sample.shape[frame_idx]
return np.array([
param_cb(SampleDesc(rng, frame_idx, sample_idx, batch_idx, sample))
for frame_idx in range(num_frames)])
return [[
arg_for_sample(sample_idx, batch_idx, sample)
for sample_idx, sample in enumerate(batch)]
for batch_idx, batch in enumerate(input_data.data)]
def compute_input_params_data(input_data: ArgData, rng, input_params: List[ArgCb]):
def input_param_data(arg_cb):
assert arg_cb.desc.expandable_prefix in ["", "F"]
if arg_cb.desc.expandable_prefix == "F":
return get_input_arg_per_frame(
input_data, arg_cb.cb, rng, not arg_cb.desc.is_positional_arg)
return get_input_arg_per_sample(input_data, arg_cb.cb, rng)
return [
ArgData(desc=arg_cb.desc, data=input_param_data(arg_cb))
for arg_cb in input_params]
def sequence_suite_helper(rng, input_cases: List[ArgData], ops_test_cases, num_iters=4):
"""
Generates suite of test cases for a sequence processing operator.
The operator should meet the SequenceOperator assumptions, i.e.
1. process frames (and possibly channels) independently,
2. support per-frame tensor arguments.
Each test case consists of two pipelines, one fed with the batch of sequences
and one fed with the batch of frames, the test compares if the processing of
corresponding frames in both pipelines gives the same result. In other words, if
given batch = [sequence, ...], the following holds:
fn.op([frame for sequence in batch for frame in sequence])
== [frame for sequence in fn.op(batch) for frame in sequence]
----------
`input_cases`: List[ArgData].
Each ArgData instance describes a single parameter (positional or named) that will be
passed to the pipeline and serve as a source of truth (regarding the number of expandable
dimensions and sequence shape). Based on it, all other inputs defined through ArgCb
in `ops_test_cases` will be computed.
Note the `.desc.device` argument is ignored in favour of `ops_test_case` devices list.
`ops_test_cases` : List[Tuple[
Operator,
Dict[str, Any],
ParamProviderBase|List[ArgCb]]
]]
List of operators and their parameters that should be tested.
Each element is expected to be a tuple of the form: (
fn.operator,
{fixed_param_name: fixed_param_value},
[ArgCb(tensor_arg_name, single_arg_cb, is_per_frame, dest_device)]
)
where the first element is ``fn.operator``, the second one is a dictionary of fixed
arguments that should be passed to the operator and the third one is a list of ArgCb
instances describing tensor input arguments or custom params provider instance
(see `ParamsProvider`). The tuple can optionally have fourth element: a list of devices
where the main input (from `input_cases`) should be placed.
"""
class OpTestCase:
def __init__(self, operator_fn, fixed_params, input_params, devices=None, input_name=0):
self.operator_fn = operator_fn
self.fixed_params = fixed_params
self.input_params = input_params
self.devices = ["cpu", "gpu"] if devices is None else devices
for test_case_args in ops_test_cases:
test_case = OpTestCase(*test_case_args)
for device in test_case.devices:
for input_case in input_cases:
input_desc = input_case.desc
arg_desc = ArgDesc(
input_desc.name, input_desc.expandable_prefix,
device, input_desc.layout)
arg_data = ArgData(arg_desc, input_case.data)
yield _test_seq_input, num_iters, test_case.operator_fn, test_case.fixed_params, \
test_case.input_params, arg_data, rng
def get_video_input_cases(seq_layout, rng, larger_shape=(512, 288), smaller_shape=(384, 216)):
max_batch_size = 8
max_num_frames = 16
cases = []
w, h = larger_shape
larger = vid_source(max_batch_size, 1, max_num_frames,
w, h, seq_layout)
w, h = smaller_shape
smaller = vid_source(max_batch_size, 2, max_num_frames,
w, h, seq_layout)
cases.append(smaller)
samples = [sample for batch in [smaller[0], larger[0], smaller[1]]
for sample in batch]
rng.shuffle(samples)
# test variable batch size
case2 = [
samples[0:1], samples[1:1 + max_batch_size],
samples[1 + max_batch_size:2 * max_batch_size],
samples[2 * max_batch_size:3 * max_batch_size]]
cases.append(case2)
frames_idx = seq_layout.find("F")
if frames_idx == 0:
# test variadic number of frames in different sequences
case3 = [[sample[:rng.randint(1, sample.shape[0])]
for sample in batch] for batch in case2]
cases.append(case3)
return cases
@pipeline_def
def vid_pipeline(num_frames, width, height, seq_layout):
vid, _ = fn.readers.video_resize(
filenames=[vid_file],
labels=[],
name='video reader',
sequence_length=num_frames,
file_list_include_preceding_frame=True,
device='gpu',
seed=42,
resize_x=width,
resize_y=height)
if seq_layout == "FCHW":
vid = fn.transpose(vid, perm=[0, 3, 1, 2])
elif seq_layout == "CFHW":
vid = fn.transpose(vid, perm=[3, 0, 1, 2])
else:
assert seq_layout == "FHWC"
return vid
def vid_source(batch_size, num_batches, num_frames, width, height, seq_layout):
pipe = vid_pipeline(
num_threads=4, batch_size=batch_size, num_frames=num_frames,
width=width, height=height, device_id=0, seq_layout=seq_layout,
prefetch_queue_depth=1)
pipe.build()
batches = []
for _ in range(num_batches):
(pipe_out,) = pipe.run()
batches.append(as_batch(pipe_out))
return batches
def video_suite_helper(ops_test_cases, test_channel_first=True, expand_channels=False, rng=None):
"""
Generates suite of video test cases for a sequence processing operator.
The function prepares video input to be passed as a main input for `sequence_suite_helper`.
For testing operator with different input than the video,
consider using `sequence_suite_helper` directly.
----------
`ops_test_cases` : (see `sequence_suite_helper`).
`test_channel_first` : bool
If True, the "FCHW" layout is tested.
`expand_channels` : bool
If True, for the "FCHW" layout the first two (and not just one) dims are expanded,
and "CFHW" layout is tested. Requires `test_channel_first` to be True.
"""
rng = rng or random.Random(42)
expandable_extents = "FC" if expand_channels else "F"
layouts = ["FHWC"]
if not test_channel_first:
assert not expand_channels
else:
layouts.append("FCHW")
if expand_channels:
layouts.append("CFHW")
def input_data_desc(layout, input_data):
num_expand = get_layout_prefix_len(layout, expandable_extents)
return ArgData(
desc=ArgDesc(0, layout[:num_expand], "", layout),
data=input_data
)
input_cases = [
input_data_desc(input_layout, input_data)
for input_layout in layouts
for input_data in get_video_input_cases(input_layout, rng)]
yield from sequence_suite_helper(rng, input_cases, ops_test_cases)
|
DALI-main
|
dali/test/python/sequences_test_utils.py
|
# Copyright (c) 2019-2022, NVIDIA CORPORATION & AFFILIATES. 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 nvidia.dali.pipeline import Pipeline
import nvidia.dali.ops as ops
import nvidia.dali.types as types
import nvidia.dali.tfrecord as tfrec
import os
import glob
import argparse
import time
from test_utils import get_dali_extra_path, AverageMeter
class CommonPipeline(Pipeline):
def __init__(self, data_paths, num_shards, batch_size, num_threads, device_id,
prefetch, fp16, random_shuffle, nhwc, dont_use_mmap, decoder_type,
decoder_cache_params, reader_queue_depth, shard_id):
super(CommonPipeline, self).__init__(
batch_size, num_threads, device_id, random_shuffle, prefetch_queue_depth=prefetch)
if decoder_type == 'roi':
print('Using nvJPEG with ROI decoding')
self.decode_gpu = ops.decoders.ImageRandomCrop(device="mixed", output_type=types.RGB)
self.res = ops.Resize(device="gpu", resize_x=224, resize_y=224)
elif decoder_type == 'cached':
assert decoder_cache_params['cache_enabled']
cache_size = decoder_cache_params['cache_size']
cache_threshold = decoder_cache_params['cache_threshold']
cache_type = decoder_cache_params['cache_type']
print(f'Using nvJPEG with cache (size : {cache_size} '
f'threshold: {cache_threshold}, type: {cache_type})')
self.decode_gpu = ops.decoders.Image(
device="mixed", output_type=types.RGB,
cache_size=cache_size, cache_threshold=cache_threshold,
cache_type=cache_type, cache_debug=False)
self.res = ops.RandomResizedCrop(device="gpu", size=(224, 224))
else:
print('Using nvJPEG')
self.decode_gpu = ops.decoders.Image(device="mixed", output_type=types.RGB)
self.res = ops.RandomResizedCrop(device="gpu", size=(224, 224))
layout = types.NHWC if nhwc else types.NCHW
out_type = types.FLOAT16 if fp16 else types.FLOAT
self.cmnp = ops.CropMirrorNormalize(device="gpu",
dtype=out_type,
output_layout=layout,
crop=(224, 224),
mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
self.coin = ops.random.CoinFlip(probability=0.5)
def base_define_graph(self, inputs, labels):
rng = self.coin()
images = self.decode_gpu(inputs)
images = self.res(images)
output = self.cmnp(images.gpu(), mirror=rng)
return (output, labels)
class MXNetReaderPipeline(CommonPipeline):
def __init__(self, **kwargs):
super(MXNetReaderPipeline, self).__init__(**kwargs)
cache_enabled = kwargs['decoder_cache_params']['cache_enabled']
self.input = ops.readers.MXNet(
path=kwargs['data_paths'][0],
index_path=kwargs['data_paths'][1],
shard_id=kwargs['shard_id'],
num_shards=kwargs['num_shards'],
random_shuffle=kwargs['random_shuffle'],
stick_to_shard=cache_enabled,
prefetch_queue_depth=kwargs['reader_queue_depth'])
def define_graph(self):
images, labels = self.input(name="Reader")
return self.base_define_graph(images, labels)
class CaffeReadPipeline(CommonPipeline):
def __init__(self, **kwargs):
super(CaffeReadPipeline, self).__init__(**kwargs)
cache_enabled = kwargs['decoder_cache_params']['cache_enabled']
self.input = ops.readers.Caffe(
path=kwargs['data_paths'][0],
shard_id=kwargs['shard_id'],
num_shards=kwargs['num_shards'],
stick_to_shard=cache_enabled,
random_shuffle=kwargs['random_shuffle'],
dont_use_mmap=kwargs['dont_use_mmap'],
prefetch_queue_depth=kwargs['reader_queue_depth'])
def define_graph(self):
images, labels = self.input(name="Reader")
return self.base_define_graph(images, labels)
class Caffe2ReadPipeline(CommonPipeline):
def __init__(self, **kwargs):
super(Caffe2ReadPipeline, self).__init__(**kwargs)
cache_enabled = kwargs['decoder_cache_params']['cache_enabled']
self.input = ops.readers.Caffe2(
path=kwargs['data_paths'][0],
shard_id=kwargs['shard_id'],
num_shards=kwargs['num_shards'],
random_shuffle=kwargs['random_shuffle'],
dont_use_mmap=kwargs['dont_use_mmap'],
stick_to_shard=cache_enabled,
prefetch_queue_depth=kwargs['reader_queue_depth'])
def define_graph(self):
images, labels = self.input(name="Reader")
return self.base_define_graph(images, labels)
class FileReadPipeline(CommonPipeline):
def __init__(self, **kwargs):
super(FileReadPipeline, self).__init__(**kwargs)
cache_enabled = kwargs['decoder_cache_params']['cache_enabled']
self.input = ops.readers.File(
file_root=kwargs['data_paths'][0],
shard_id=kwargs['shard_id'],
num_shards=kwargs['num_shards'],
random_shuffle=kwargs['random_shuffle'],
dont_use_mmap=kwargs['dont_use_mmap'],
stick_to_shard=cache_enabled,
prefetch_queue_depth=kwargs['reader_queue_depth'])
def define_graph(self):
images, labels = self.input(name="Reader")
return self.base_define_graph(images, labels)
class TFRecordPipeline(CommonPipeline):
def __init__(self, **kwargs):
super(TFRecordPipeline, self).__init__(**kwargs)
tfrecord = sorted(glob.glob(kwargs['data_paths'][0]))
tfrecord_idx = sorted(glob.glob(kwargs['data_paths'][1]))
cache_enabled = kwargs['decoder_cache_params']['cache_enabled']
self.input = ops.readers.TFRecord(
path=tfrecord,
index_path=tfrecord_idx,
shard_id=kwargs['shard_id'],
num_shards=kwargs['num_shards'],
random_shuffle=kwargs['random_shuffle'],
dont_use_mmap=kwargs['dont_use_mmap'],
stick_to_shard=cache_enabled,
features={
"image/encoded": tfrec.FixedLenFeature((), tfrec.string, ""),
"image/class/label": tfrec.FixedLenFeature([1], tfrec.int64, -1)})
def define_graph(self):
inputs = self.input(name="Reader")
images = inputs["image/encoded"]
labels = inputs["image/class/label"]
return self.base_define_graph(images, labels)
class WebdatasetPipeline(CommonPipeline):
def __init__(self, data_paths, decoder_cache_params, shard_id, num_shards,
random_shuffle, dont_use_mmap, **kwargs):
super(WebdatasetPipeline, self).__init__(
data_paths=data_paths,
decoder_cache_params=decoder_cache_params,
shard_id=shard_id,
num_shards=num_shards,
random_shuffle=random_shuffle,
dont_use_mmap=dont_use_mmap,
**kwargs)
wds, wds_idx = data_paths[:2]
cache_enabled = decoder_cache_params['cache_enabled']
self.input = ops.readers.Webdataset(
paths=wds,
index_paths=wds_idx,
ext=["jpg", "cls"],
shard_id=shard_id,
num_shards=num_shards,
random_shuffle=random_shuffle,
dont_use_mmap=dont_use_mmap,
stick_to_shard=cache_enabled)
def define_graph(self):
return self.base_define_graph(*self.input(name="Reader"))
test_data = {
FileReadPipeline: [["/data/imagenet/train-jpeg"],
["/data/imagenet/val-jpeg"]],
MXNetReaderPipeline: [["/data/imagenet/train-480-val-256-recordio/train.rec",
"/data/imagenet/train-480-val-256-recordio/train.idx"],
["/data/imagenet/train-480-val-256-recordio/val.rec",
"/data/imagenet/train-480-val-256-recordio/val.idx"]],
CaffeReadPipeline: [["/data/imagenet/train-lmdb-256x256"],
["/data/imagenet/val-lmdb-256x256"]],
Caffe2ReadPipeline: [["/data/imagenet/train-c2lmdb-480"],
["/data/imagenet/val-c2lmdb-256"]],
TFRecordPipeline: [["/data/imagenet/train-val-tfrecord-480/train-*",
"/data/imagenet/train-val-tfrecord-480.idx/train-*"]],
}
data_root = get_dali_extra_path()
small_test_data = {
FileReadPipeline: [[os.path.join(data_root, "db/single/jpeg/")]],
MXNetReaderPipeline: [[os.path.join(data_root, "db/recordio/train.rec"),
os.path.join(data_root, "db/recordio/train.idx")]],
CaffeReadPipeline: [[os.path.join(data_root, "db/lmdb")]],
Caffe2ReadPipeline: [[os.path.join(data_root, "db/c2lmdb")]],
TFRecordPipeline: [[os.path.join(data_root, "db/tfrecord/train"),
os.path.join(data_root, "db/tfrecord/train.idx")]],
WebdatasetPipeline: [[os.path.join(data_root, "db/webdataset/train.tar"),
os.path.join(data_root, "db/webdataset/train.idx")]]
}
parser = argparse.ArgumentParser(
description='Test nvJPEG based RN50 augmentation pipeline with different datasets')
parser.add_argument(
'-g', '--gpus', default=1, type=int, metavar='N',
help='number of GPUs run in parallel by this test (default: 1)')
parser.add_argument(
'-b', '--batch', default=512, type=int, metavar='N',
help='batch size (default: 512)')
parser.add_argument(
'-p', '--print-freq', default=10, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument(
'-j', '--workers', default=3, type=int, metavar='N',
help='number of data loading workers (default: 3)')
parser.add_argument(
'--prefetch', default=2, type=int, metavar='N',
help='prefetch queue depth (default: 2)')
parser.add_argument(
'--separate_queue', action='store_true',
help='Use separate queues executor')
parser.add_argument(
'--cpu_size', default=2, type=int, metavar='N',
help='cpu prefetch queue depth (default: 2)')
parser.add_argument(
'--gpu_size', default=2, type=int, metavar='N',
help='gpu prefetch queue depth (default: 2)')
parser.add_argument(
'--fp16', action='store_true',
help='Run fp16 pipeline')
parser.add_argument(
'--nhwc', action='store_true',
help='Use NHWC data instead of default NCHW')
parser.add_argument(
'-i', '--iters', default=-1, type=int, metavar='N',
help='Number of iterations to run (default: -1 - whole data set)')
parser.add_argument(
'--epochs', default=2, type=int, metavar='N',
help='Number of epochs to run')
parser.add_argument(
'--decoder_type', default='', type=str, metavar='N',
help='roi, cached (default: regular nvjpeg)')
parser.add_argument(
'--cache_size', default=0, type=int, metavar='N',
help='Cache size (in MB)')
parser.add_argument(
'--cache_threshold', default=0, type=int, metavar='N',
help='Cache threshold')
parser.add_argument(
'--cache_type', default='none', type=str, metavar='N',
help='Cache type')
parser.add_argument(
'--reader_queue_depth', default=1, type=int, metavar='N',
help='prefetch queue depth (default: 1)')
parser.add_argument(
'--read_shuffle', action='store_true',
help='Shuffle data when reading')
parser.add_argument(
'--disable_mmap', action='store_true',
help='Disable mmap for DALI readers. Used for network filesystem tests.')
parser.add_argument(
'-s', '--small', action='store_true',
help='use small dataset, DALI_EXTRA_PATH needs to be set')
parser.add_argument(
'--number_of_shards', default=None, type=int, metavar='N',
help='Number of shards in the dataset')
parser.add_argument(
'--assign_gpu', default=None, type=int, metavar='N',
help='Assign a given GPU. Cannot be used with --gpus')
parser.add_argument(
'--assign_shard', default=0, type=int, metavar='N',
help='Assign a given shard id. If used with --gpus, it assigns '
'the first GPU to this id and next GPUs get consecutive ids')
parser.add_argument(
'--simulate_N_gpus', default=None, type=int, metavar='N',
help='Used to simulate small shard as it would be in a multi gpu setup '
'with this number of gpus. If provided, each gpu will see a shard '
'size as if we were in a multi gpu setup with this number of gpus',
dest='number_of_shards')
parser.add_argument(
'--remove_default_pipeline_paths', action='store_true',
help="For all data pipeline types, remove the default values")
parser.add_argument(
'--file_read_pipeline_paths', default=None, type=str, metavar='N',
help='Add custom FileReadPipeline paths. Separate multiple paths by commas')
parser.add_argument(
'--mxnet_reader_pipeline_paths', default=None, type=str, metavar='N',
help='Add custom MXNetReaderPipeline paths. For a given path, a .rec and .idx '
'extension will be appended. Separate multiple paths by commas')
parser.add_argument(
'--caffe_read_pipeline_paths', default=None, type=str, metavar='N',
help='Add custom CaffeReadPipeline paths. Separate multiple paths by commas')
parser.add_argument(
'--caffe2_read_pipeline_paths', default=None, type=str, metavar='N',
help='Add custom Caffe2ReadPipeline paths. Separate multiple paths by commas')
parser.add_argument(
'--tfrecord_pipeline_paths', default=None, type=str, metavar='N',
help='Add custom TFRecordPipeline paths. For a given path, a second path with '
'an .idx extension will be added for the required idx file(s). Separate '
'multiple paths by commas')
parser.add_argument(
'--webdataset_pipeline_paths', default=None, type=str, metavar='N',
help='Add custom WebdatasetPipeline paths. For a given path, a second path '
'with an .idx extension will be added for the required idx file(s). '
'Separate multiple paths by commas')
parser.add_argument(
'--system_id', default="localhost", type=str, metavar='N',
help='Add a system id to denote a unique identifier for the performance output. '
'Defaults to localhost')
args = parser.parse_args()
N = args.gpus # number of GPUs
GPU_ID = args.assign_gpu
DALI_SHARD = args.assign_shard
BATCH_SIZE = args.batch # batch size
LOG_INTERVAL = args.print_freq
WORKERS = args.workers
PREFETCH = args.prefetch
if args.separate_queue:
PREFETCH = {'cpu_size': args.cpu_size, 'gpu_size': args.gpu_size}
FP16 = args.fp16
NHWC = args.nhwc
SYS_ID = args.system_id
if args.remove_default_pipeline_paths:
for pipe_name in test_data.keys():
test_data[pipe_name] = []
if args.file_read_pipeline_paths:
paths = args.file_read_pipeline_paths.split(',')
for path in paths:
test_data[FileReadPipeline].append([path])
if args.mxnet_reader_pipeline_paths:
paths = args.mxnet_reader_pipeline_paths.split(',')
for path in paths:
path_expanded = [path + '.rec', path + '.idx']
test_data[MXNetReaderPipeline].append(path_expanded)
if args.caffe_read_pipeline_paths:
paths = args.caffe_read_pipeline_paths.split(',')
for path in paths:
test_data[CaffeReadPipeline].append([path])
if args.caffe2_read_pipeline_paths:
paths = args.caffe2_read_pipeline_paths.split(',')
for path in paths:
test_data[Caffe2ReadPipeline].append([path])
if args.tfrecord_pipeline_paths:
paths = args.tfrecord_pipeline_paths.split(',')
for path in paths:
idx_split_path, idx_split_file = os.path.split(path)
idx_split_path = idx_split_path + '.idx'
idx_path = os.path.join(idx_split_path, idx_split_file)
path_expanded = [path, idx_path]
test_data[TFRecordPipeline].append(path_expanded)
if args.webdataset_pipeline_paths:
paths = args.webdataset_pipeline_paths.split(',')
for path in paths:
idx_split_path, idx_split_file = os.path.split(path)
idx_split_path = idx_split_path + '.idx'
idx_path = os.path.join(idx_split_path, idx_split_file)
path_expanded = [path, idx_path]
test_data[WebdatasetPipeline].append(path_expanded)
DECODER_TYPE = args.decoder_type
CACHED_DECODING = DECODER_TYPE == 'cached'
DECODER_CACHE_PARAMS = {}
DECODER_CACHE_PARAMS['cache_enabled'] = CACHED_DECODING
if CACHED_DECODING:
DECODER_CACHE_PARAMS['cache_type'] = args.cache_type
DECODER_CACHE_PARAMS['cache_size'] = args.cache_size
DECODER_CACHE_PARAMS['cache_threshold'] = args.cache_threshold
READER_QUEUE_DEPTH = args.reader_queue_depth
NUMBER_OF_SHARDS = N if args.number_of_shards is None else args.number_of_shards
STICK_TO_SHARD = True if CACHED_DECODING else False
SKIP_CACHED_IMAGES = True if CACHED_DECODING else False
READ_SHUFFLE = args.read_shuffle
DISABLE_MMAP = args.disable_mmap
SMALL_DATA_SET = args.small
if SMALL_DATA_SET:
test_data = small_test_data
print("GPUs: {N}, batch: {BATCH_SIZE}, workers: {WORKERS}, prefetch depth: {PREFETCH}, "
f"loging interval: {LOG_INTERVAL}, fp16: {FP16}, NHWC: {NHWC}, READ_SHUFFLE: {READ_SHUFFLE}, "
f"DISABLE_MMAP: {DISABLE_MMAP}, small dataset: {SMALL_DATA_SET}, GPU ID: {GPU_ID}, "
f"shard number: {DALI_SHARD}, number of shards {NUMBER_OF_SHARDS}")
for pipe_name in test_data.keys():
data_set_len = len(test_data[pipe_name])
for i, data_set in enumerate(test_data[pipe_name]):
if GPU_ID is None:
pipes = [
pipe_name(batch_size=BATCH_SIZE, num_threads=WORKERS, device_id=n,
num_shards=NUMBER_OF_SHARDS, data_paths=data_set,
prefetch=PREFETCH, fp16=FP16, random_shuffle=READ_SHUFFLE,
dont_use_mmap=DISABLE_MMAP, nhwc=NHWC, decoder_type=DECODER_TYPE,
decoder_cache_params=DECODER_CACHE_PARAMS,
reader_queue_depth=READER_QUEUE_DEPTH,
shard_id=DALI_SHARD + n) for n in range(N)]
else:
pipes = [
pipe_name(batch_size=BATCH_SIZE, num_threads=WORKERS, device_id=GPU_ID,
num_shards=NUMBER_OF_SHARDS, data_paths=data_set,
prefetch=PREFETCH, fp16=FP16, random_shuffle=READ_SHUFFLE,
dont_use_mmap=DISABLE_MMAP, nhwc=NHWC, decoder_type=DECODER_TYPE,
decoder_cache_params=DECODER_CACHE_PARAMS,
reader_queue_depth=READER_QUEUE_DEPTH,
shard_id=DALI_SHARD)]
[pipe.build() for pipe in pipes]
if args.iters < 0:
iters = pipes[0].epoch_size("Reader")
assert all(pipe.epoch_size("Reader") == iters for pipe in pipes)
iters_tmp = iters
iters = iters // BATCH_SIZE
if iters_tmp != iters * BATCH_SIZE:
iters += 1
iters_tmp = iters
iters = iters // NUMBER_OF_SHARDS
if iters_tmp != iters * NUMBER_OF_SHARDS:
iters += 1
else:
iters = args.iters
print("RUN {0}/{1}: {2}".format(i + 1, data_set_len, pipe_name.__name__))
print(data_set)
end = time.time()
for i in range(args.epochs):
if i == 0:
print("Warm up")
data_time = AverageMeter()
for j in range(iters):
for pipe in pipes:
pipe.run()
data_time.update(time.time() - end)
if j % LOG_INTERVAL == 0:
print(f"System {SYS_ID}, GPU {GPU_ID}, run {i}: "
f" {pipe_name.__name__} {j + 1}/ {iters}, "
f"avg time: {data_time.avg} [s], "
f"worst time: {data_time.max_val} [s], "
f"speed: {N * BATCH_SIZE / data_time.avg} [img/s]")
end = time.time()
print("OK {0}/{1}: {2}".format(i + 1, data_set_len, pipe_name.__name__))
|
DALI-main
|
dali/test/python/test_RN50_data_pipeline.py
|
# Copyright (c) 2018-2022, NVIDIA CORPORATION & AFFILIATES. 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
class TestDaliTfPluginLoadOk(unittest.TestCase):
def test_import_dali_tf_ok(self):
import nvidia.dali.plugin.tf as dali_tf # noqa: F401
assert True
class TestDaliTfPluginLoadFail(unittest.TestCase):
def test_import_dali_tf_load_fail(self):
with self.assertRaises(Exception):
import nvidia.dali.plugin.tf as dali_tf # noqa: F401
if __name__ == '__main__':
unittest.main()
|
DALI-main
|
dali/test/python/test_dali_tf_plugin.py
|
# Copyright (c) 2021-2022, NVIDIA CORPORATION & AFFILIATES. 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 nvidia.dali.fn as fn
from nvidia.dali import pipeline_def, Pipeline
import numpy as np
from nose_utils import raises
@pipeline_def(batch_size=8, num_threads=3, device_id=0)
def pipeline():
output = fn.external_source(source=np.zeros((8, 8)), name='input')
return output
@raises(RuntimeError, glob="Cannot use `feed_input` on the external source 'input' with a `source`"
" argument specified.")
def test_feed_input_with_source():
pipe = pipeline()
pipe.build()
pipe.feed_input('input', np.zeros((8, 8)))
pipe.run()
def test_external_source_with_callback():
"""Test if using external_source with 'source' doesn't raise exceptions."""
pipe = pipeline()
pipe.build()
pipe.run()
def test_external_source_with_serialized_pipe():
@pipeline_def
def serialized_pipe():
return fn.external_source(name="es")
pipe = serialized_pipe(batch_size=10, num_threads=3, device_id=0)
serialized_str = pipe.serialize()
deserialized_pipe = Pipeline(10, 4, 0)
deserialized_pipe.deserialize_and_build(serialized_str)
deserialized_pipe.feed_input("es", np.zeros([10, 10]))
|
DALI-main
|
dali/test/python/test_external_source_multiple_sources.py
|
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. 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 nvidia.dali.plugin.tf as dali_tf
import nvidia.dali.types as types
import random
import tensorflow as tf
from nvidia.dali.pipeline import pipeline_def
try:
from tensorflow.compat.v1 import Session
except Exception:
# Older TF versions don't have compat.v1 layer
from tensorflow import Session
@pipeline_def()
def get_dali_pipe(value):
data = types.Constant(value)
return data
def get_data(batch_size, value):
pipe = get_dali_pipe(batch_size=batch_size, device_id=types.CPU_ONLY_DEVICE_ID, num_threads=1,
value=value)
daliop = dali_tf.DALIIterator()
out = []
with tf.device('/cpu'):
data = daliop(pipeline=pipe,
shapes=[(batch_size)],
dtypes=[tf.int32],
device_id=types.CPU_ONLY_DEVICE_ID)
out.append(data)
return [out]
def test_dali_tf_op_cpu_only():
try:
tf.compat.v1.disable_eager_execution()
except Exception:
pass
value = random.randint(0, 1000)
batch_size = 3
test_batch = get_data(batch_size, value)
with Session() as sess:
data = sess.run(test_batch)
assert (data == np.array([value] * batch_size)).all()
|
DALI-main
|
dali/test/python/test_dali_tf_plugin_cpu_only.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. 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.
# it is enough to just import all functions from test_internals_operator_external_source
# nose will query for the methods available and will run them
# the test_internals_operator_external_source is 99% the same for cupy and numpy tests
# so it is better to store everything in one file and just call `use_cupy`
# to switch between the default numpy and cupy
from test_external_source_impl import * # noqa: F403
use_torch(False) # noqa: F405
|
DALI-main
|
dali/test/python/test_external_source_pytorch_cpu.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION & AFFILIATES. 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 nose
import numpy as np
import nvidia.dali.fn as fn
import nvidia.dali.math as dmath
import nvidia.dali.types as types
import os
import random
import re
from functools import partial
from nose.plugins.attrib import attr
from nose.tools import nottest
from nvidia.dali.pipeline import Pipeline, pipeline_def
from nvidia.dali.pipeline.experimental import pipeline_def as experimental_pipeline_def
from nvidia.dali.plugin.numba.fn.experimental import numba_function
import test_utils
from segmentation_test_utils import make_batch_select_masks
from test_detection_pipeline import coco_anchors
from test_optical_flow import load_frames, is_of_supported
from test_utils import module_functions, has_operator, restrict_platform
"""
How to test variable (iter-to-iter) batch size for a given op?
-------------------------------------------------------------------------------
The idea is to create a Pipeline that assumes i2i variability, run 2 iterations
and compare them with ad-hoc created Pipelines for given (constant) batch sizes.
This can be easily done using `check_batch` function below.
On top of that, there are some utility functions and routines to help with some
common cases:
1. If the operator is typically processing image-like data (i.e. 3-dim, uint8,
0-255, with shape like [640, 480, 3]) and you want to test default arguments
only, please add a record to the `ops_image_default_args` list
2. If the operator is typically processing image-like data (i.e. 3-dim, uint8,
0-255, with shape like [640, 480, 3]) and you want to specify any number of
its arguments, please add a record to the `ops_image_custom_args` list
3. If the operator is typically processing audio-like data (i.e. 1-dim, float,
0.-1.) please add a record to the `float_array_ops` list
4. If the operator supports sequences, please add a record to the
`sequence_ops` list
5. If your operator case doesn't fit any of the above, please create a nosetest
function, in which you can define a function, that returns not yet built
pipeline, and pass it to the `check_batch` function.
6. If your operator performs random operation, this approach won't provide
a comparable result. In this case, the best thing you can do is to check
whether the operator works, without qualitative comparison. Use `run_pipeline`
instead of `check_pipeline`.
"""
def generate_data(max_batch_size, n_iter, sample_shape, lo=0., hi=1., dtype=np.float32):
"""
Generates an epoch of data, that will be used for variable batch size verification.
:param max_batch_size: Actual sizes of every batch in the epoch will be less or equal
to max_batch_size
:param n_iter: Number of iterations in the epoch
:param sample_shape: If sample_shape is callable, shape of every sample will be determined by
calling sample_shape. In this case, every call to sample_shape has to
return a tuple of integers. If sample_shape is a tuple, this will be a
shape of every sample.
:param lo: Begin of the random range
:param hi: End of the random range
:param dtype: Numpy data type
:return: An epoch of data
"""
batch_sizes = np.array([max_batch_size // 2, max_batch_size // 4, max_batch_size])
if isinstance(sample_shape, tuple):
def sample_shape_wrapper():
return sample_shape
size_fn = sample_shape_wrapper
elif inspect.isfunction(sample_shape):
size_fn = sample_shape
else:
raise RuntimeError("`sample_shape` shall be either a tuple or a callable. "
"Provide `(val,)` tuple for 1D shape")
if np.issubdtype(dtype, np.integer):
return [
np.random.randint(lo, hi, size=(bs, ) + size_fn(), dtype=dtype)
for bs in batch_sizes]
elif np.issubdtype(dtype, np.float32):
ret = (np.random.random_sample(size=(bs, ) + size_fn()) for bs in batch_sizes)
ret = map(lambda batch: (hi - lo) * batch + lo, ret)
ret = map(lambda batch: batch.astype(dtype), ret)
return list(ret)
elif np.issubdtype(dtype, bool):
assert isinstance(lo, bool)
assert isinstance(hi, bool)
return [np.random.choice(a=[lo, hi], size=(bs, ) + size_fn()) for bs in batch_sizes]
else:
raise RuntimeError(f"Invalid type argument: {dtype}")
def single_op_pipeline(max_batch_size, input_data, device, *, input_layout=None,
operator_fn=None, needs_input=True, **opfn_args):
pipe = Pipeline(batch_size=max_batch_size, num_threads=1, device_id=0)
with pipe:
input = fn.external_source(source=input_data, cycle=False, device=device,
layout=input_layout)
if operator_fn is None:
output = input
else:
if needs_input:
output = operator_fn(input, **opfn_args)
else:
output = operator_fn(**opfn_args)
if needs_input:
pipe.set_outputs(output)
else:
# set input as an output to make sure it is not pruned from the graph
pipe.set_outputs(output, input)
return pipe
def get_batch_size(batch):
"""
Returns the batch size in samples
:param batch: List of input batches, if there is one input a batch can be either
a numpy array or a list, for multiple inputs it can be tuple of lists or
numpy arrays.
"""
if isinstance(batch, tuple):
return get_batch_size(batch[0])
else:
if isinstance(batch, list):
return len(batch)
else:
return batch.shape[0]
def run_pipeline(input_epoch, pipeline_fn, *, devices: list = ['cpu', 'gpu'], **pipeline_fn_args):
"""
Verifies, if given pipeline supports iter-to-iter variable batch size
This function verifies only if given pipeline runs without crashing.
There is no qualitative verification. Use this for checking pipelines
based on random operators (as they can't be verifies against one another).
:param input_epoch: List of input batches, if there is one input a batch can be either
a numpy array or a list, for multiple inputs it can be tuple of lists or
numpy arrays.
:param pipeline_fn: Function, that returns created (but not built) pipeline.
Its signature should be (at least):
pipeline_fn(max_batch_size, input_data, device, ...)
:param devices: Devices to run the check on
:param pipeline_fn_args: Additional args to pipeline_fn
"""
for device in devices:
n_iter = len(input_epoch)
max_bs = max(get_batch_size(batch) for batch in input_epoch)
var_pipe = pipeline_fn(max_bs, input_epoch, device, **pipeline_fn_args)
var_pipe.build()
for _ in range(n_iter):
var_pipe.run()
def check_pipeline(input_epoch, pipeline_fn, *, devices: list = ['cpu', 'gpu'], eps=1e-7,
**pipeline_fn_args):
"""
Verifies, if given pipeline supports iter-to-iter variable batch size
This function conducts qualitative verification. It compares the result of
running multiple iterations of the same pipeline (with possible varying batch sizes,
according to `input_epoch`) with results of the ad-hoc created pipelines per iteration
:param input_epoch: List of input batches, if there is one input a batch can be either
a numpy array or a list, for multiple inputs it can be tuple of lists or
numpy arrays.
:param pipeline_fn: Function, that returns created (but not built) pipeline.
Its signature should be (at least):
pipeline_fn(max_batch_size, input_data, device, ...)
:param devices: Devices to run the check on
:param eps: Epsilon for mean error
:param pipeline_fn_args: Additional args to pipeline_fn
"""
for device in devices:
n_iter = len(input_epoch)
max_bs = max(get_batch_size(batch) for batch in input_epoch)
var_pipe = pipeline_fn(max_bs, input_epoch, device, **pipeline_fn_args)
var_pipe.build()
for iter_idx in range(n_iter):
iter_input = input_epoch[iter_idx]
batch_size = get_batch_size(iter_input)
const_pipe = pipeline_fn(batch_size, [iter_input], device, **pipeline_fn_args)
const_pipe.build()
test_utils.compare_pipelines(var_pipe, const_pipe, batch_size=batch_size,
N_iterations=1, eps=eps)
def image_like_shape_generator():
return random.randint(160, 161), random.randint(80, 81), 3
def array_1d_shape_generator():
return random.randint(300, 400), # The coma is important
def custom_shape_generator(*args):
"""
Fully configurable shape generator.
Returns a callable which serves as a non-uniform & random shape generator to generate_epoch
Usage:
custom_shape_generator(dim1_lo, dim1_hi, dim2_lo, dim2_hi, etc...)
"""
assert len(args) % 2 == 0, "Incorrect number of arguments"
ndims = len(args) // 2
gen_conf = [[args[2 * i], args[2 * i + 1]] for i in range(ndims)]
return lambda: tuple([random.randint(lohi[0], lohi[1]) for lohi in gen_conf])
def image_data_helper(operator_fn, opfn_args={}):
data = generate_data(31, 13, image_like_shape_generator, lo=0, hi=255, dtype=np.uint8)
check_pipeline(data, pipeline_fn=single_op_pipeline, input_layout="HWC",
operator_fn=operator_fn, **opfn_args)
def float_array_helper(operator_fn, opfn_args={}):
data = generate_data(31, 13, array_1d_shape_generator)
check_pipeline(data, pipeline_fn=single_op_pipeline, operator_fn=operator_fn, **opfn_args)
def sequence_op_helper(operator_fn, opfn_args={}):
data = generate_data(31, 13, custom_shape_generator(3, 7, 160, 200, 80, 100, 3, 3),
lo=0, hi=255, dtype=np.uint8)
check_pipeline(data, pipeline_fn=single_op_pipeline, input_layout="FHWC",
operator_fn=operator_fn, **opfn_args)
def random_op_helper(operator_fn, opfn_args={}):
run_pipeline(generate_data(31, 13, image_like_shape_generator, lo=0, hi=255, dtype=np.uint8),
pipeline_fn=single_op_pipeline, operator_fn=operator_fn, **opfn_args)
def test_external_source():
check_pipeline(generate_data(31, 13, custom_shape_generator(2, 4, 2, 4)), single_op_pipeline)
ops_image_default_args = [
fn.brightness,
fn.brightness_contrast,
fn.cat,
fn.color_twist,
fn.contrast,
fn.copy,
fn.crop_mirror_normalize,
fn.dump_image,
fn.hsv,
fn.hue,
fn.jpeg_compression_distortion,
fn.reductions.mean,
fn.reductions.mean_square,
fn.reductions.rms,
fn.reductions.min,
fn.reductions.max,
fn.reductions.sum,
fn.saturation,
fn.shapes,
fn.sphere,
fn.stack,
fn.water
]
def test_ops_image_default_args():
for op in ops_image_default_args:
yield image_data_helper, op, {}
def numba_set_all_values_to_255_batch(out0, in0):
out0[0][:] = 255
def numba_setup_out_shape(out_shape, in_shape):
out_shape[0] = in_shape[0]
ops_image_custom_args = [
(fn.cast, {'dtype': types.INT32}),
(fn.color_space_conversion, {'image_type': types.BGR, 'output_type': types.RGB}),
(fn.coord_transform, {'M': .5, 'T': 2}),
(fn.coord_transform, {'T': 2}),
(fn.coord_transform, {'M': .5}),
(fn.crop, {'crop': (5, 5)}),
(fn.experimental.equalize, {'devices': ['gpu']}),
(fn.erase, {'anchor': [0.3], 'axis_names': "H", 'normalized_anchor': True,
'shape': [0.1], 'normalized_shape': True}),
(fn.fast_resize_crop_mirror, {'crop': [5, 5], 'resize_shorter': 10, 'devices': ['cpu']}),
(fn.flip, {'horizontal': True}),
(fn.gaussian_blur, {'window_size': 5}),
(fn.get_property, {'key': "layout"}),
(fn.laplacian, {'window_size': 3}),
(fn.laplacian, {'window_size': 3, 'smoothing_size': 1}),
(fn.laplacian, {'window_size': 3, 'normalized_kernel': True}),
(fn.normalize, {'batch': True}),
(fn.pad, {'fill_value': -1, 'axes': (0,), 'shape': (10,)}),
(fn.pad, {'fill_value': -1, 'axes': (0,), 'align': 16}),
(fn.paste, {'fill_value': 69, 'ratio': 1, 'devices': ['gpu']}),
(fn.per_frame, {'replace': True, 'devices': ['cpu']}),
(fn.resize, {'resize_x': 50, 'resize_y': 50}),
(fn.resize_crop_mirror, {'crop': [5, 5], 'resize_shorter': 10, 'devices': ['cpu']}),
(fn.experimental.tensor_resize, {'sizes': [50, 50], 'axes': [0, 1]}),
(fn.rotate, {'angle': 25}),
(fn.transpose, {'perm': [2, 0, 1]}),
(fn.warp_affine, {'matrix': (.1, .9, 10, .8, -.2, -20)}),
(fn.expand_dims, {'axes': 1, 'new_axis_names': "Z"}),
(fn.grid_mask, {'angle': 2.6810782, 'ratio': 0.38158387, 'tile': 51}),
(numba_function, {
'batch_processing': True, 'devices': ['cpu'],
'in_types': [types.UINT8], 'ins_ndim': [3],
'out_types': [types.UINT8], 'outs_ndim': [3],
'run_fn': numba_set_all_values_to_255_batch,
'setup_fn': numba_setup_out_shape
}),
(numba_function, {
'batch_processing': False, 'devices': ['cpu'],
'in_types': [types.UINT8], 'ins_ndim': [3],
'out_types': [types.UINT8], 'outs_ndim': [3],
'run_fn': numba_set_all_values_to_255_batch,
'setup_fn': numba_setup_out_shape
}),
(fn.multi_paste, {'in_ids': np.zeros([31], dtype=np.int32), 'output_size': [300, 300, 3]}),
(fn.experimental.median_blur, {'devices': ['gpu']})
]
def test_ops_image_custom_args():
for op, args in ops_image_custom_args:
yield image_data_helper, op, args
float_array_ops = [
(fn.power_spectrum, {'devices': ['cpu']}),
(fn.preemphasis_filter, {}),
(fn.spectrogram, {'nfft': 60, 'window_length': 50, 'window_step': 25}),
(fn.to_decibels, {}),
(fn.audio_resample, {'devices': ['cpu'], 'scale': 1.2}),
]
def test_float_array_ops():
for op, args in float_array_ops:
yield float_array_helper, op, args
random_ops = [
(fn.jitter, {'devices': ['gpu']}),
(fn.random_resized_crop, {'size': 69}),
(fn.noise.gaussian, {}),
(fn.noise.shot, {}),
(fn.noise.salt_and_pepper, {}),
(fn.segmentation.random_mask_pixel, {'devices': ['cpu']}),
(fn.roi_random_crop, {'devices': ['cpu'], 'crop_shape': [10, 15, 3], 'roi_start': [25, 20, 0],
'roi_shape': [40, 30, 3]})
]
def test_random_ops():
for op, args in random_ops:
yield random_op_helper, op, args
sequence_ops = [
(fn.cast, {'dtype': types.INT32}),
(fn.copy, {}),
(fn.crop, {'crop': (5, 5)}),
(fn.crop_mirror_normalize, {'mirror': 1, 'output_layout': 'FCHW'}),
(fn.erase, {'anchor': [0.3], 'axis_names': "H", 'normalized_anchor': True,
'shape': [0.1], 'normalized_shape': True}),
(fn.flip, {'horizontal': True}),
(fn.gaussian_blur, {'window_size': 5}),
(fn.normalize, {'batch': True}),
(fn.per_frame, {'devices': ['cpu']}),
(fn.resize, {'resize_x': 50, 'resize_y': 50}),
]
def test_sequence_ops():
for op, args in sequence_ops:
yield sequence_op_helper, op, args
def test_batch_permute():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
perm = fn.batch_permutation(seed=420)
data = fn.external_source(source=input_data, cycle=False, device=device)
processed = fn.permute_batch(data, indices=perm)
pipe.set_outputs(processed)
return pipe
run_pipeline(generate_data(31, 13, image_like_shape_generator), pipeline_fn=pipe)
def test_coin_flip():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
depthwise = fn.random.coin_flip()
horizontal = fn.random.coin_flip()
vertical = fn.random.coin_flip()
data = fn.external_source(source=input_data, cycle=False, device=device)
processed = fn.flip(data, depthwise=depthwise, horizontal=horizontal, vertical=vertical)
pipe.set_outputs(processed)
return pipe
run_pipeline(generate_data(31, 13, image_like_shape_generator), pipeline_fn=pipe,
devices=['cpu'])
def test_uniform():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
dist = fn.random.uniform()
data = fn.external_source(source=input_data, cycle=False, device=device)
processed = data * dist
pipe.set_outputs(processed)
return pipe
run_pipeline(generate_data(31, 13, array_1d_shape_generator), pipeline_fn=pipe)
def test_random_normal():
def pipe_input(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(source=input_data, cycle=False, device=device)
dist = fn.random.normal(data)
pipe.set_outputs(dist)
return pipe
def pipe_no_input(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(source=input_data, cycle=False, device=device)
dist = data + fn.random.normal()
pipe.set_outputs(dist)
return pipe
run_pipeline(generate_data(31, 13, image_like_shape_generator), pipeline_fn=pipe_input)
run_pipeline(generate_data(31, 13, image_like_shape_generator), pipeline_fn=pipe_no_input)
def no_input_op_helper(operator_fn, opfn_args={}):
data = generate_data(31, 13, image_like_shape_generator, lo=0, hi=255, dtype=np.uint8)
check_pipeline(data, pipeline_fn=single_op_pipeline, input_layout="HWC",
operator_fn=operator_fn, needs_input=False, **opfn_args)
no_input_ops = [
(fn.constant, {
'fdata': 3.1415,
'shape': (10, 10)
}),
(fn.transforms.translation, {
'offset': (2, 3),
'devices': ['cpu']
}),
(fn.transforms.scale, {
'scale': (2, 3),
'devices': ['cpu']
}),
(fn.transforms.rotation, {
'angle': 30.0,
'devices': ['cpu']
}),
(fn.transforms.shear, {
'shear': (2., 1.),
'devices': ['cpu']
}),
(fn.transforms.crop, {
'from_start': (0., 1.),
'from_end': (1., 1.),
'to_start': (0.2, 0.3),
'to_end': (0.8, 0.5),
'devices': ['cpu']
}),
]
def test_no_input_ops():
for op, args in no_input_ops:
yield no_input_op_helper, op, args
def test_combine_transforms():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
with pipe:
# just to drive the variable batch size.
batch_size_setter = fn.external_source(source=input_data, cycle=False, device=device)
t = fn.transforms.translation(offset=(1, 2))
r = fn.transforms.rotation(angle=30.0)
s = fn.transforms.scale(scale=(2, 3))
out = fn.transforms.combine(t, r, s)
pipe.set_outputs(out, batch_size_setter)
return pipe
check_pipeline(
generate_data(31, 13, custom_shape_generator(2, 4), lo=1, hi=255, dtype=np.uint8),
pipeline_fn=pipe, devices=['cpu'])
@attr('pytorch')
def test_dl_tensor_python_function():
import torch.utils.dlpack as torch_dlpack
def dl_tensor_operation(tensor):
tensor = torch_dlpack.from_dlpack(tensor)
tensor_n = tensor.double() / 255
ret = tensor_n.sin()
ret = torch_dlpack.to_dlpack(ret)
return ret
def batch_dl_tensor_operation(tensors):
out = [dl_tensor_operation(t) for t in tensors]
return out
def pipe(max_batch_size, input_data, device, input_layout=None):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0,
exec_async=False, exec_pipelined=False)
with pipe:
input = fn.external_source(source=input_data, cycle=False, device=device,
layout=input_layout)
output_batch = fn.dl_tensor_python_function(
input, function=batch_dl_tensor_operation, batch_processing=True)
output_sample = fn.dl_tensor_python_function(
input, function=dl_tensor_operation, batch_processing=False)
pipe.set_outputs(output_batch, output_sample, input)
return pipe
check_pipeline(generate_data(31, 13, image_like_shape_generator, lo=0, hi=255, dtype=np.uint8),
pipeline_fn=pipe, devices=['cpu'])
def test_random_object_bbox():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
with pipe:
# just to drive the variable batch size.
data = fn.external_source(source=input_data, batch=False, cycle="quiet", device=device)
out = fn.segmentation.random_object_bbox(data)
pipe.set_outputs(*out)
return pipe
get_data = [
np.int32([[1, 0, 0, 0],
[1, 2, 2, 1],
[1, 1, 2, 0],
[2, 0, 0, 1]]),
np.int32([[0, 3, 3, 0],
[1, 0, 1, 2],
[0, 1, 1, 0],
[0, 2, 0, 1],
[0, 2, 2, 1]])
]
run_pipeline(get_data, pipeline_fn=pipe, devices=['cpu'])
def test_math_ops():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
with pipe:
# just to drive the variable batch size.
data, data2 = fn.external_source(
source=input_data, cycle=False, device=device, num_outputs=2)
processed = [
-data,
+data,
data * data2,
data + data2,
data - data2,
data / data2,
data // data2,
data ** data2,
# compare_pipelines doesn't work well with bool so promote to int by *
(data == data2) * 1,
(data != data2) * 1,
(data < data2) * 1,
(data <= data2) * 1,
(data > data2) * 1,
(data >= data2) * 1,
data & data,
data | data,
data ^ data,
dmath.abs(data),
dmath.fabs(data),
dmath.floor(data),
dmath.ceil(data),
dmath.pow(data, 2),
dmath.fpow(data, 1.5),
dmath.min(data, 2),
dmath.max(data, 50),
dmath.clamp(data, 10, 50),
dmath.sqrt(data),
dmath.rsqrt(data),
dmath.cbrt(data),
dmath.exp(data),
dmath.log(data),
dmath.log2(data),
dmath.log10(data),
dmath.sin(data),
dmath.cos(data),
dmath.tan(data),
dmath.asin(data),
dmath.acos(data),
dmath.atan(data),
dmath.atan2(data, 3),
dmath.sinh(data),
dmath.cosh(data),
dmath.tanh(data),
dmath.asinh(data),
dmath.acosh(data),
dmath.atanh(data)
]
pipe.set_outputs(*processed)
return pipe
def get_data(batch_size):
test_data_shape = [random.randint(5, 21), random.randint(5, 21), 3]
data1 = [
np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8)
for _ in range(batch_size)]
data2 = [
np.random.randint(1, 4, size=test_data_shape, dtype=np.uint8)
for _ in range(batch_size)]
return (data1, data2)
input_data = [get_data(random.randint(5, 31)) for _ in range(13)]
check_pipeline(input_data, pipeline_fn=pipe)
def test_squeeze_op():
def pipe(max_batch_size, input_data, device, input_layout=None):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
with pipe:
# just to drive the variable batch size.
data = fn.external_source(source=input_data, cycle=False, device=device,
layout=input_layout)
out = fn.expand_dims(data, axes=[0, 2], new_axis_names="YZ")
out = fn.squeeze(out, axis_names="Z")
pipe.set_outputs(out)
return pipe
check_pipeline(generate_data(31, 13, image_like_shape_generator, lo=0, hi=255, dtype=np.uint8),
pipeline_fn=pipe, input_layout="HWC")
def test_box_encoder_op():
def pipe(max_batch_size, input_data, device, input_layout=None):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
with pipe:
boxes, lables = fn.external_source(device=device, source=input_data, num_outputs=2)
processed, _ = fn.box_encoder(boxes, lables, anchors=coco_anchors())
pipe.set_outputs(processed)
return pipe
def get_data(batch_size):
obj_num = random.randint(1, 20)
test_box_shape = [obj_num, 4]
test_lables_shape = [obj_num, 1]
bboxes = [np.random.random(size=test_box_shape).astype(dtype=np.float32)
for _ in range(batch_size)]
labels = [np.random.randint(0, 255, size=test_lables_shape, dtype=np.int32)
for _ in range(batch_size)]
return (bboxes, labels)
input_data = [get_data(random.randint(5, 31)) for _ in range(13)]
check_pipeline(input_data, pipeline_fn=pipe, devices=["cpu"])
def test_remap():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, device_id=0, num_threads=4)
with pipe:
input, mapx, mapy = fn.external_source(device=device, source=input_data, num_outputs=3)
out = fn.experimental.remap(input, mapx, mapy)
pipe.set_outputs(out)
return pipe
def get_data(batch_size):
input_shape = [480, 640, 3]
mapx_shape = mapy_shape = [480, 640]
input = [np.random.randint(0, 255, size=input_shape, dtype=np.uint8)
for _ in range(batch_size)]
mapx = [640 * np.random.random(size=mapx_shape).astype(np.float32) # [0, 640) interval
for _ in range(batch_size)]
mapy = [480 * np.random.random(size=mapy_shape).astype(np.float32) # [0, 480) interval
for _ in range(batch_size)]
return input, mapx, mapy
input_data = [get_data(random.randint(5, 31)) for _ in range(13)]
check_pipeline(input_data, pipeline_fn=pipe, devices=['gpu'])
def test_random_bbox_crop_op():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
with pipe:
boxes, lables = fn.external_source(device=device, source=input_data, num_outputs=2)
processed = fn.random_bbox_crop(boxes, lables, aspect_ratio=[0.5, 2.0],
thresholds=[0.1, 0.3, 0.5], scaling=[0.8, 1.0],
bbox_layout="xyXY")
pipe.set_outputs(*processed)
return pipe
def get_data(batch_size):
obj_num = random.randint(1, 20)
test_box_shape = [obj_num, 4]
test_lables_shape = [obj_num, 1]
bboxes = [np.random.random(size=test_box_shape).astype(dtype=np.float32)
for _ in range(batch_size)]
labels = [np.random.randint(0, 255, size=test_lables_shape, dtype=np.int32)
for _ in range(batch_size)]
return (bboxes, labels)
input_data = [get_data(random.randint(5, 31)) for _ in range(13)]
run_pipeline(input_data, pipeline_fn=pipe, devices=["cpu"])
def test_ssd_random_crop_op():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
with pipe:
data, boxes, lables = fn.external_source(
device=device, source=input_data, num_outputs=3)
processed = fn.ssd_random_crop(data, boxes, lables)
pipe.set_outputs(*processed)
return pipe
def get_data(batch_size):
obj_num = random.randint(1, 20)
test_data_shape = [50, 20, 3]
test_box_shape = [obj_num, 4]
test_lables_shape = [obj_num]
data = [np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8)
for _ in range(batch_size)]
bboxes = [np.random.random(size=test_box_shape).astype(dtype=np.float32)
for _ in range(batch_size)]
labels = [np.random.randint(0, 255, size=test_lables_shape, dtype=np.int32)
for _ in range(batch_size)]
return (data, bboxes, labels)
input_data = [get_data(random.randint(5, 31)) for _ in range(13)]
run_pipeline(input_data, pipeline_fn=pipe, devices=["cpu"])
def test_reshape():
data = generate_data(31, 13, (160, 80, 3), lo=0, hi=255, dtype=np.uint8)
check_pipeline(data, pipeline_fn=single_op_pipeline, operator_fn=fn.reshape,
shape=(160 / 2, 80 * 2, 3))
def test_slice():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(source=input_data, cycle=False, device=device)
processed = fn.slice(data, 0.1, 0.5, axes=0, device=device)
pipe.set_outputs(processed)
return pipe
check_pipeline(generate_data(31, 13, image_like_shape_generator, lo=0, hi=255, dtype=np.uint8),
pipeline_fn=pipe)
def test_bb_flip():
check_pipeline(generate_data(31, 13, custom_shape_generator(150, 250, 4, 4)),
single_op_pipeline, operator_fn=fn.bb_flip)
def test_1_hot():
data = generate_data(31, 13, array_1d_shape_generator, lo=0, hi=255, dtype=np.uint8)
check_pipeline(data, single_op_pipeline, operator_fn=fn.one_hot)
def test_bbox_paste():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(source=input_data, cycle=False, device=device)
paste_posx = fn.random.uniform(range=(0, 1))
paste_posy = fn.random.uniform(range=(0, 1))
paste_ratio = fn.random.uniform(range=(1, 2))
processed = fn.bbox_paste(data, paste_x=paste_posx, paste_y=paste_posy, ratio=paste_ratio)
pipe.set_outputs(processed)
return pipe
check_pipeline(generate_data(31, 13, custom_shape_generator(150, 250, 4, 4)), pipe, eps=.5,
devices=['cpu'])
def test_coord_flip():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(source=input_data, cycle=False, device=device)
processed = fn.coord_flip(data)
pipe.set_outputs(processed)
return pipe
check_pipeline(generate_data(31, 13, custom_shape_generator(150, 250, 2, 2)), pipe)
def test_lookup_table():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(source=input_data, cycle=False, device=device)
processed = fn.lookup_table(data, keys=[1, 3], values=[10, 50])
pipe.set_outputs(processed)
return pipe
check_pipeline(generate_data(31, 13, array_1d_shape_generator, lo=0, hi=5, dtype=np.uint8),
pipe)
# TODO sequence
def test_reduce():
reduce_fns = [
fn.reductions.std_dev,
fn.reductions.variance
]
def pipe(max_batch_size, input_data, device, reduce_fn):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(source=input_data, cycle=False, device=device)
mean = fn.reductions.mean(data)
reduced = reduce_fn(data, mean)
pipe.set_outputs(reduced)
return pipe
for rf in reduce_fns:
check_pipeline(generate_data(31, 13, image_like_shape_generator), pipe, reduce_fn=rf)
def test_sequence_rearrange():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(source=input_data, cycle=False, device=device,
layout="FHWC")
processed = fn.sequence_rearrange(data, new_order=[0, 4, 1, 3, 2])
pipe.set_outputs(processed)
return pipe
check_pipeline(generate_data(31, 13, (5, 10, 20, 3), lo=0, hi=255, dtype=np.uint8), pipe)
def test_element_extract():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(source=input_data, cycle=False, device=device,
layout="FHWC")
processed, _ = fn.element_extract(data, element_map=[0, 3])
pipe.set_outputs(processed)
return pipe
check_pipeline(generate_data(31, 13, (5, 10, 20, 3), lo=0, hi=255, dtype=np.uint8), pipe)
def test_nonsilent_region():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(source=input_data, cycle=False, device=device)
processed, _ = fn.nonsilent_region(data)
pipe.set_outputs(processed)
return pipe
check_pipeline(generate_data(31, 13, array_1d_shape_generator, lo=0, hi=255, dtype=np.uint8),
pipe, devices=['cpu'])
def test_mel_filter_bank():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
with pipe:
data = fn.external_source(source=input_data, cycle=False, device=device)
spectrum = fn.spectrogram(data, nfft=60, window_length=50, window_step=25)
processed = fn.mel_filter_bank(spectrum)
pipe.set_outputs(processed)
return pipe
check_pipeline(generate_data(31, 13, array_1d_shape_generator), pipe)
def test_mfcc():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(source=input_data, cycle=False, device=device)
spectrum = fn.spectrogram(data, nfft=60, window_length=50, window_step=25)
mel = fn.mel_filter_bank(spectrum)
dec = fn.to_decibels(mel)
processed = fn.mfcc(dec)
pipe.set_outputs(processed)
return pipe
check_pipeline(generate_data(31, 13, array_1d_shape_generator), pipe)
@nottest
def generate_decoders_data(data_dir, data_extension, exclude_subdirs=[]):
# File reader won't work, so I need to load audio files into external_source manually
fnames = test_utils.filter_files(data_dir, data_extension, exclude_subdirs=exclude_subdirs)
nfiles = len(fnames)
# TODO(janton): Workaround for audio data (not enough samples)
# To be removed when more audio samples are added
for i in range(len(fnames), 10): # At least 10 elements
fnames.append(fnames[-1])
nfiles = len(fnames)
_input_epoch = [
list(map(lambda fname: test_utils.read_file_bin(fname), fnames[:nfiles // 3])),
list(map(lambda fname: test_utils.read_file_bin(fname),
fnames[nfiles // 3: nfiles // 2])),
list(map(lambda fname: test_utils.read_file_bin(fname), fnames[nfiles // 2:])),
]
# Since we pack buffers into ndarray, we need to pad samples with 0.
input_epoch = []
for inp in _input_epoch:
max_len = max(sample.shape[0] for sample in inp)
inp = map(lambda sample: np.pad(sample, (0, max_len - sample.shape[0])), inp)
input_epoch.append(np.stack(list(inp)))
input_epoch = list(map(lambda batch: np.reshape(batch, batch.shape), input_epoch))
return input_epoch
@nottest
def test_decoders_check(pipeline_fn, data_dir, data_extension, devices=['cpu'], exclude_subdirs=[]):
data = generate_decoders_data(data_dir=data_dir, data_extension=data_extension,
exclude_subdirs=exclude_subdirs)
check_pipeline(data, pipeline_fn=pipeline_fn, devices=devices)
@nottest
def test_decoders_run(pipeline_fn, data_dir, data_extension, devices=['cpu'], exclude_subdirs=[]):
data = generate_decoders_data(data_dir=data_dir, data_extension=data_extension,
exclude_subdirs=exclude_subdirs)
run_pipeline(data, pipeline_fn=pipeline_fn, devices=devices)
def test_audio_decoders():
def audio_decoder_pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
encoded = fn.external_source(source=input_data, cycle=False, device='cpu')
decoded, _ = fn.decoders.audio(encoded, downmix=True, sample_rate=12345, device=device)
pipe.set_outputs(decoded)
return pipe
audio_path = os.path.join(test_utils.get_dali_extra_path(), 'db', 'audio')
yield test_decoders_check, audio_decoder_pipe, audio_path, '.wav'
def test_image_decoders():
def image_decoder_pipe(module, max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
encoded = fn.external_source(source=input_data, cycle=False, device='cpu')
decoded = module.image(encoded, device=device)
pipe.set_outputs(decoded)
return pipe
def image_decoder_crop_pipe(module, max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
encoded = fn.external_source(source=input_data, cycle=False, device='cpu')
decoded = module.image_crop(encoded, device=device)
pipe.set_outputs(decoded)
return pipe
def image_decoder_slice_pipe(module, max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
encoded = fn.external_source(source=input_data, cycle=False, device='cpu')
decoded = module.image_slice(encoded, 0.1, 0.4, axes=0, device=device)
pipe.set_outputs(decoded)
return pipe
def image_decoder_rcrop_pipe(module, max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
encoded = fn.external_source(source=input_data, cycle=False, device='cpu')
decoded = module.image_random_crop(encoded, device=device)
pipe.set_outputs(decoded)
return pipe
def peek_image_shape_pipe(module, max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
encoded = fn.external_source(source=input_data, cycle=False, device='cpu')
shape = module.peek_image_shape(encoded, device=device)
pipe.set_outputs(shape)
return pipe
image_decoder_extensions = ['.jpg', '.bmp', '.png', '.pnm', '.jp2']
image_decoder_pipes = [
image_decoder_pipe,
image_decoder_crop_pipe,
image_decoder_slice_pipe,
]
data_path = os.path.join(test_utils.get_dali_extra_path(), 'db', 'single')
# excluding paths that contain images that are not widely supported (by legacy and new decoders)
exclude_subdirs = ['jpeg_lossless']
for ext in image_decoder_extensions:
for pipe_template in image_decoder_pipes:
pipe = partial(pipe_template, fn.decoders)
yield test_decoders_check, pipe, data_path, ext, ['cpu', 'mixed'], exclude_subdirs
pipe = partial(pipe_template, fn.experimental.decoders)
yield test_decoders_check, pipe, data_path, ext, ['cpu', 'mixed'], exclude_subdirs
pipe = partial(image_decoder_rcrop_pipe, fn.decoders)
yield test_decoders_run, pipe, data_path, ext, ['cpu', 'mixed'], exclude_subdirs
pipe = partial(image_decoder_rcrop_pipe, fn.experimental.decoders)
yield test_decoders_run, pipe, data_path, ext, ['cpu', 'mixed'], exclude_subdirs
pipe = partial(peek_image_shape_pipe, fn)
yield test_decoders_check, pipe, data_path, '.jpg', ['cpu'], exclude_subdirs
pipe = partial(peek_image_shape_pipe, fn.experimental)
yield test_decoders_check, pipe, data_path, '.jpg', ['cpu'], exclude_subdirs
def test_python_function():
def resize(data):
data += 13
return data
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0, exec_async=False,
exec_pipelined=False)
with pipe:
data = fn.external_source(source=input_data, cycle=False, device=device)
processed = fn.python_function(data, function=resize, num_outputs=1)
pipe.set_outputs(processed)
return pipe
check_pipeline(generate_data(31, 13, image_like_shape_generator), pipe, devices=['cpu'])
def test_reinterpret():
def pipe(max_batch_size, input_data, device, input_layout):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(source=input_data, cycle=False, device=device,
layout=input_layout)
processed = fn.reinterpret(data, rel_shape=[.5, 1, -1])
pipe.set_outputs(processed)
return pipe
check_pipeline(generate_data(31, 13, (160, 80, 3), lo=0, hi=255, dtype=np.uint8),
pipeline_fn=pipe, input_layout="HWC")
check_pipeline(generate_data(31, 13, (5, 160, 80, 3), lo=0, hi=255, dtype=np.uint8),
pipeline_fn=pipe, input_layout="FHWC")
def test_segmentation_select_masks():
def get_data_source(*args, **kwargs):
return make_batch_select_masks(*args, **kwargs)
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=None, seed=1234)
with pipe:
polygons, vertices, selected_masks = fn.external_source(
num_outputs=3, device=device, source=input_data
)
out_polygons, out_vertices = fn.segmentation.select_masks(
selected_masks, polygons, vertices, reindex_masks=False
)
pipe.set_outputs(polygons, vertices, selected_masks, out_polygons, out_vertices)
return pipe
input_data = [
get_data_source(random.randint(5, 31), vertex_ndim=2, npolygons_range=(1, 5),
nvertices_range=(3, 10))
for _ in range(13)]
check_pipeline(input_data, pipeline_fn=pipe, devices=["cpu"])
def test_optical_flow():
if not is_of_supported():
raise nose.SkipTest('Optical Flow is not supported on this platform')
def pipe(max_batch_size, input_data, device, input_layout=None):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
with pipe:
data = fn.external_source(
device=device, source=input_data, cycle=False, layout=input_layout)
processed = fn.optical_flow(data, device=device, output_grid=4)
pipe.set_outputs(processed)
return pipe
max_batch_size = 5
bach_sizes = [max_batch_size // 2, max_batch_size // 4, max_batch_size]
input_data = [[load_frames() for _ in range(bs)] for bs in bach_sizes]
check_pipeline(input_data, pipeline_fn=pipe, devices=["gpu"], input_layout="FHWC")
def test_tensor_subscript():
def pipe(max_batch_size, input_data, device, input_layout):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data = fn.external_source(
source=input_data, cycle=False, device=device, layout=input_layout)
processed = data[2, :-2:, 1]
pipe.set_outputs(processed)
return pipe
check_pipeline(generate_data(31, 13, (160, 80, 3), lo=0, hi=255, dtype=np.uint8),
pipeline_fn=pipe, input_layout="HWC")
check_pipeline(generate_data(31, 13, (5, 160, 80, 3), lo=0, hi=255, dtype=np.uint8),
pipeline_fn=pipe, input_layout="FHWC")
def test_subscript_dim_check():
data = generate_data(31, 13, array_1d_shape_generator, lo=0, hi=255, dtype=np.uint8)
check_pipeline(data, single_op_pipeline, operator_fn=fn.subscript_dim_check, num_subscripts=1)
def test_crop_argument_from_external_source():
"""
Tests, if the fn.crop operator works correctly, when its actual batch size is lower
than max batch size.
"""
@pipeline_def(batch_size=32, num_threads=4, device_id=0)
def pipeline():
images = fn.external_source(device="cpu", name="IMAGE", no_copy=False)
crop_x = fn.external_source(device="cpu", name="CROP_X", no_copy=False)
images = fn.decoders.image(images, device="mixed")
images = fn.crop(images, crop_pos_x=crop_x, crop_pos_y=0.05, crop_w=113, crop_h=149)
return images
pipe = pipeline()
pipe.build()
image_data = np.fromfile(
os.path.join(test_utils.get_dali_extra_path(), "db", "single", "jpeg", "100",
"swan-3584559_640.jpg"),
dtype=np.uint8)
pipe.feed_input("IMAGE", [image_data])
pipe.feed_input("CROP_X", [np.float32(0.5)])
pipe.feed_input("IMAGE", [image_data])
pipe.feed_input("CROP_X", [np.float32(0.4)])
pipe.run()
def test_video_decoder():
def video_decoder_pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
encoded = fn.external_source(source=input_data, cycle=False, device='cpu')
decoded = fn.experimental.decoders.video(encoded, device=device)
pipe.set_outputs(decoded)
return pipe
file_path = os.path.join(test_utils.get_dali_extra_path(), 'db', 'video', 'cfr', 'test_1.mp4')
video_file = np.fromfile(file_path, dtype=np.uint8)
batches = [[video_file] * 2, [video_file] * 5, [video_file] * 3]
check_pipeline(batches, video_decoder_pipe, devices=['cpu', 'mixed'])
@has_operator("experimental.inflate")
@restrict_platform(min_compute_cap=6.0, platforms=["x86_64"])
def test_inflate():
import lz4.block
def sample_to_lz4(sample):
deflated_buf = lz4.block.compress(sample, store_size=False)
return np.frombuffer(deflated_buf, dtype=np.uint8)
def inflate_pipline(max_batch_size, inputs, device):
input_data = [
[sample_to_lz4(sample) for sample in batch]
for batch in inputs]
input_shape = [
[np.array(sample.shape, dtype=np.int32) for sample in batch]
for batch in inputs]
@pipeline_def
def piepline():
defalted = fn.external_source(source=input_data)
shape = fn.external_source(source=input_shape)
return fn.experimental.inflate(defalted.gpu(), shape=shape)
return piepline(batch_size=max_batch_size, num_threads=4, device_id=0)
def sample_gen():
j = 42
while True:
yield np.full((13, 7), j)
j += 1
sample = sample_gen()
batches = [
[next(sample) for _ in range(5)],
[next(sample) for _ in range(13)],
[next(sample) for _ in range(2)]]
check_pipeline(batches, inflate_pipline, devices=['gpu'])
def test_debayer():
from debayer_test_utils import rgb2bayer, bayer_patterns, blue_position
def debayer_pipline(max_batch_size, inputs, device):
batches = [list(zip(*batch)) for batch in inputs]
img_batches = [list(imgs) for imgs, _ in batches]
blue_positions = [list(positions) for _, positions in batches]
@pipeline_def
def piepline():
bayered = fn.external_source(source=img_batches)
positions = fn.external_source(source=blue_positions)
return fn.experimental.debayer(bayered.gpu(), blue_position=positions)
return piepline(batch_size=max_batch_size, num_threads=4, device_id=0)
def sample_gen():
rng = np.random.default_rng(seed=101)
j = 0
while True:
pattern = bayer_patterns[j % len(bayer_patterns)]
h, w = 2 * np.int32(rng.uniform(2, 3, 2))
r, g, b = np.full((h, w), j), np.full((h, w), j + 1), np.full((h, w), j + 2)
rgb = np.uint8(np.stack([r, g, b], axis=2))
yield rgb2bayer(rgb, pattern), np.array(blue_position(pattern), dtype=np.int32)
j += 1
sample = sample_gen()
batches = [
[next(sample) for _ in range(5)],
[next(sample) for _ in range(13)],
[next(sample) for _ in range(2)]]
check_pipeline(batches, debayer_pipline, devices=['gpu'])
def test_filter():
def filter_pipeline(max_batch_size, inputs, device):
batches = [list(zip(*batch)) for batch in inputs]
sample_batches = [list(inp_batch) for inp_batch, _, _ in batches]
filter_batches = [list(filt_batch) for _, filt_batch, _ in batches]
fill_value_bacthes = [list(fvs) for _, _, fvs in batches]
@pipeline_def
def pipeline():
samples = fn.external_source(source=sample_batches, layout="HWC")
filters = fn.external_source(source=filter_batches)
fill_values = fn.external_source(source=fill_value_bacthes)
return fn.experimental.filter(samples.gpu(), filters, fill_values, border="constant")
return pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
def sample_gen():
rng = np.random.default_rng(seed=101)
sample_shapes = [(300, 600, 3), (100, 100, 3), (500, 1024, 1), (40, 40, 20)]
filter_shapes = [(5, 7), (3, 3), (60, 2)]
j = 0
while True:
sample_shape = sample_shapes[j % len(sample_shapes)]
filter_shape = filter_shapes[j % len(filter_shapes)]
sample = np.uint8(rng.uniform(0, 255, sample_shape))
filter = np.float32(rng.uniform(0, 255, filter_shape))
yield sample, filter, np.array([rng.uniform(0, 255)], dtype=np.uint8)
j += 1
sample = sample_gen()
batches = [[next(sample) for _ in range(5)], [next(sample) for _ in range(13)],
[next(sample) for _ in range(2)]]
check_pipeline(batches, filter_pipeline, devices=['gpu'])
def test_cast_like():
def pipe(max_batch_size, input_data, device):
pipe = Pipeline(batch_size=max_batch_size, num_threads=4, device_id=0)
data, data2 = fn.external_source(
source=input_data, cycle=False, device=device, num_outputs=2)
out = fn.cast_like(data, data2)
pipe.set_outputs(out)
return pipe
def get_data(batch_size):
test_data_shape = [random.randint(5, 21), random.randint(5, 21), 3]
data1 = [
np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8)
for _ in range(batch_size)]
data2 = [
np.random.randint(1, 4, size=test_data_shape, dtype=np.int32)
for _ in range(batch_size)]
return (data1, data2)
input_data = [get_data(random.randint(5, 31)) for _ in range(13)]
check_pipeline(input_data, pipeline_fn=pipe)
def test_conditional():
def conditional_wrapper(max_batch_size, input_data, device):
@experimental_pipeline_def(enable_conditionals=True, batch_size=max_batch_size,
num_threads=4, device_id=0)
def actual_pipe():
variable_condition = fn.external_source(source=input_data, cycle=False, device=device)
variable_data = variable_condition + 42.0
if variable_condition:
other_variable_data = variable_condition + 100
output = variable_data + other_variable_data
else:
output = types.Constant(np.array(42.0), device="cpu")
logical_expr = variable_condition or not variable_condition
logical_expr2 = not variable_condition and variable_condition
return output, variable_condition, variable_data, logical_expr, logical_expr2
return actual_pipe()
check_pipeline(
generate_data(31, 13, custom_shape_generator(), lo=False, hi=True, dtype=np.bool_),
pipeline_fn=conditional_wrapper, devices=['cpu'])
def split_merge_wrapper(max_batch_size, input_data, device):
@experimental_pipeline_def(enable_conditionals=True, batch_size=max_batch_size,
num_threads=4, device_id=0)
def actual_pipe():
variable_pred = fn.external_source(source=input_data, cycle=False, device=device)
variable_data = variable_pred + 42.0
true, false = fn._conditional.split(variable_data, predicate=variable_pred)
true = true + 10.0
merged = fn._conditional.merge(true, false, predicate=variable_pred)
return merged, variable_pred
return actual_pipe()
check_pipeline(
generate_data(31, 13, custom_shape_generator(), lo=False, hi=True, dtype=np.bool_),
pipeline_fn=split_merge_wrapper, devices=['cpu'])
def not_validate_wrapper(max_batch_size, input_data, device):
@experimental_pipeline_def(enable_conditionals=True, batch_size=max_batch_size,
num_threads=4, device_id=0)
def actual_pipe():
variable_pred = fn.external_source(source=input_data, cycle=False, device=device)
negated = fn._conditional.not_(variable_pred)
validated = fn._conditional.validate_logical(variable_pred, expression_name="or",
expression_side="right")
return negated, validated, variable_pred
return actual_pipe()
check_pipeline(
generate_data(31, 13, custom_shape_generator(), lo=False, hi=True, dtype=np.bool_),
pipeline_fn=not_validate_wrapper, devices=['cpu'])
tested_methods = [
"_conditional.merge",
"_conditional.split",
"_conditional.not_",
"_conditional.validate_logical",
"arithmetic_generic_op",
"audio_decoder",
"audio_resample",
"batch_permutation",
"bb_flip",
"bbox_paste",
"box_encoder",
"brightness",
"brightness_contrast",
"cast",
"cast_like",
"cat",
"coin_flip",
"color_space_conversion",
"color_twist",
"constant",
"contrast",
"coord_flip",
"coord_transform",
"copy",
"crop",
"crop_mirror_normalize",
"decoders.audio",
"decoders.image",
"decoders.image_crop",
"decoders.image_random_crop",
"decoders.image_slice",
"dl_tensor_python_function",
"dump_image",
"experimental.equalize",
"element_extract",
"erase",
"expand_dims",
"experimental.debayer",
"experimental.decoders.image",
"experimental.decoders.image_crop",
"experimental.decoders.image_slice",
"experimental.decoders.image_random_crop",
"experimental.decoders.video",
"experimental.filter",
"experimental.inflate",
"experimental.median_blur",
"experimental.peek_image_shape",
"experimental.remap",
"external_source",
"fast_resize_crop_mirror",
"flip",
"gaussian_blur",
"get_property",
"grid_mask",
"hsv",
"hue",
"image_decoder",
"image_decoder_crop",
"image_decoder_random_crop",
"image_decoder_slice",
"jitter",
"jpeg_compression_distortion",
"laplacian",
"lookup_table",
"math.abs",
"math.acos",
"math.acosh",
"math.asin",
"math.asinh",
"math.atan",
"math.atan2",
"math.atanh",
"math.cbrt",
"math.ceil",
"math.clamp",
"math.cos",
"math.cosh",
"math.exp",
"math.fabs",
"math.floor",
"math.fpow",
"math.log",
"math.log10",
"math.log2",
"math.max",
"math.min",
"math.pow",
"math.rsqrt",
"math.sin",
"math.sinh",
"math.sqrt",
"math.tan",
"math.tanh",
"mel_filter_bank",
"mfcc",
"noise.gaussian",
"noise.salt_and_pepper",
"noise.shot",
"nonsilent_region",
"normal_distribution",
"normalize",
"numba.fn.experimental.numba_function",
"one_hot",
"optical_flow",
"pad",
"paste",
"peek_image_shape",
"per_frame",
"permute_batch",
"power_spectrum",
"preemphasis_filter",
"python_function",
"random.coin_flip",
"random.normal",
"random.uniform",
"random_bbox_crop",
"random_resized_crop",
"reductions.max",
"reductions.mean",
"reductions.mean_square",
"reductions.min",
"reductions.rms",
"reductions.std_dev",
"reductions.sum",
"reductions.variance",
"reinterpret",
"reshape",
"resize",
"resize_crop_mirror",
"experimental.tensor_resize",
"roi_random_crop",
"rotate",
"saturation",
"segmentation.random_mask_pixel",
"segmentation.random_object_bbox",
"segmentation.select_masks",
"sequence_rearrange",
"shapes",
"slice",
"spectrogram",
"sphere",
"squeeze",
"ssd_random_crop",
"stack",
"subscript_dim_check",
"tensor_subscript",
"to_decibels",
"transform_translation",
"transforms.combine",
"transforms.crop",
"transforms.rotation",
"transforms.scale",
"transforms.shear",
"transforms.translation",
"transpose",
"uniform",
"warp_affine",
"water",
]
excluded_methods = [
"hidden.*",
"_conditional.hidden.*",
"multi_paste", # ToDo - crashes
"coco_reader", # readers do not support variable batch size yet
"sequence_reader", # readers do not support variable batch size yet
"numpy_reader", # readers do not support variable batch size yet
"file_reader", # readers do not support variable batch size yet
"caffe_reader", # readers do not support variable batch size yet
"caffe2_reader", # readers do not support variable batch size yet
"mxnet_reader", # readers do not support variable batch size yet
"tfrecord_reader", # readers do not support variable batch size yet
"nemo_asr_reader", # readers do not support variable batch size yet
"video_reader", # readers do not support variable batch size yet
"video_reader_resize", # readers do not support variable batch size yet
"readers.coco", # readers do not support variable batch size yet
"readers.sequence", # readers do not support variable batch size yet
"readers.numpy", # readers do not support variable batch size yet
"readers.file", # readers do not support variable batch size yet
"readers.caffe", # readers do not support variable batch size yet
"readers.caffe2", # readers do not support variable batch size yet
"readers.mxnet", # readers do not support variable batch size yet
"readers.tfrecord", # readers do not support variable batch size yet
"readers.nemo_asr", # readers do not support variable batch size yet
"readers.video", # readers do not support variable batch size yet
"readers.video_resize", # readers do not support variable batch size yet
"readers.webdataset", # readers do not support variable batch size yet
"experimental.inputs.video", # Input batch_size of inputs.video is always 1 and output
# batch_size varies and is tested in this operator's test.
"experimental.readers.video", # readers do not support variable batch size yet
"experimental.audio_resample", # Alias of audio_resample (already tested)
"experimental.readers.fits", # readers do not support variable batch size yet
]
def test_coverage():
methods = module_functions(fn, remove_prefix="nvidia.dali.fn",
allowed_private_modules=["_conditional"])
methods += module_functions(dmath, remove_prefix="nvidia.dali")
exclude = "|".join([
"(^" + x.replace(".", "\\.").replace("*", ".*").replace("?", ".") + "$)"
for x in excluded_methods])
exclude = re.compile(exclude)
methods = [x for x in methods if not exclude.match(x)]
# we are fine with covering more we can easily list, like numba
assert set(methods).difference(set(tested_methods)) == set(), \
"Test doesn't cover:\n {}".format(set(methods) - set(tested_methods))
|
DALI-main
|
dali/test/python/test_dali_variable_batch_size.py
|
# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. 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
border2scipy_border = {
"101": "mirror",
"1001": "reflect",
"clamp": "nearest",
"wrap": "wrap",
"constant": "constant",
}
def make_slice(start, end):
return slice(start, end if end < 0 else None)
def scipy_baseline_plane(sample, kernel, anchor, border, fill_value, mode):
from scipy.ndimage import convolve as sp_convolve
ndim = len(sample.shape)
assert len(kernel.shape) == ndim, f"{kernel.shape}, {ndim}"
in_dtype = sample.dtype
if isinstance(anchor, int):
anchor = (anchor, ) * ndim
assert len(anchor) == ndim, f"{anchor}, {ndim}"
anchor = tuple(filt_ext // 2 if anch == -1 else anch
for anch, filt_ext in zip(anchor, kernel.shape))
for anch, filt_ext in zip(anchor, kernel.shape):
assert 0 <= anch < filt_ext
# there are two ways (and none exact) to center the even filter
# over the image; scipy does it the other way round
origin = tuple((filt_ext - 1) // 2 - anch for anch, filt_ext in zip(anchor, kernel.shape))
out = sp_convolve(
np.float32(sample),
np.float32(np.flip(kernel)),
mode=border2scipy_border[border],
origin=origin,
cval=0 if fill_value is None else fill_value,
)
if np.issubdtype(in_dtype, np.integer):
type_info = np.iinfo(in_dtype)
v_min, v_max = type_info.min, type_info.max
out = np.clip(out, v_min, v_max)
if mode == "valid":
slices = tuple(
make_slice(anch, anch - filt_ext + 1) for anch, filt_ext in zip(anchor, kernel.shape))
out = out[slices]
return out.astype(in_dtype)
def filter_baseline(sample, kernel, anchor, border, fill_value=None, mode="same",
has_channels=False):
assert mode in ("same", "valid"), f"{mode}"
def baseline_call(plane):
return scipy_baseline_plane(plane, kernel, anchor, border, fill_value, mode)
ndim = len(sample.shape)
if not has_channels:
assert ndim in (2, 3)
return baseline_call(sample)
assert ndim in (3, 4)
ndim = len(sample.shape)
channel_dim = ndim - 1
channel_first = sample.transpose([channel_dim] + [i for i in range(channel_dim)])
out = np.stack([baseline_call(plane) for plane in channel_first], axis=channel_dim)
return out
def filter_baseline_layout(layout, sample, kernel, anchor, border, fill_value=None, mode="same"):
ndim = len(sample.shape)
if not layout:
assert ndim in (2, 3), f"{sample.shape}"
layout = "HW" if ndim == 2 else "DHW"
assert len(layout) == ndim, f"{layout}, {sample.shape}"
has_channels = layout[ndim - 1] == "C"
def baseline_call(plane):
return filter_baseline(plane, kernel, anchor, border, fill_value, mode,
has_channels=has_channels)
def get_seq_ndim():
for i, c in enumerate(layout):
if c not in "FC":
return i
assert False
seq_ndim = get_seq_ndim()
if seq_ndim == 0:
return baseline_call(sample)
else:
seq_shape = sample.shape[:seq_ndim]
spatial_shape = sample.shape[seq_ndim:]
seq_vol = np.prod(seq_shape)
sample = sample.reshape((seq_vol,) + spatial_shape)
out = np.stack([baseline_call(plane) for plane in sample])
return out.reshape(seq_shape + out.shape[1:])
|
DALI-main
|
dali/test/python/filter_test_utils.py
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION & AFFILIATES. 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 nvidia.dali as dali
from nose.tools import with_setup
from nvidia.dali.types import SampleInfo, BatchInfo
import test_external_source_parallel_utils as utils
from nose_utils import raises
def no_arg_fun():
pass
def multi_arg_fun(a, b, c):
pass
class Iterable:
def __init__(self, batch_size=4, shape=(10, 10), epoch_size=None, dtype=None):
self.count = 0
self.batch_size = batch_size
self.shape = shape
self.epoch_size = epoch_size
self.dtype = dtype or np.int16
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.epoch_size is not None and self.epoch_size <= self.count:
raise StopIteration
batch = [np.full(self.shape, self.count + i, dtype=self.dtype) for i in
range(self.batch_size)]
self.count += 1
return batch
class FaultyResetIterable(Iterable):
def __iter__(self):
return self
class SampleCallbackBatched:
def __init__(self, sample_cb, batch_size, batch_info):
self.sample_cb = sample_cb
self.batch_size = batch_size
self.batch_info = batch_info
def __call__(self, batch_info):
if not self.batch_info:
batch_i = batch_info
epoch_idx = 0
else:
batch_i = batch_info.iteration
epoch_idx = batch_info.epoch_idx
epoch_offset = batch_i * self.batch_size
return [self.sample_cb(SampleInfo(epoch_offset + i, i, batch_i, epoch_idx)) for i in
range(self.batch_size)]
class SampleCallbackIterator:
def __init__(self, sample_cb, batch_size, batch_info):
self.iters = 0
self.batch_info = batch_info
self.epoch_idx = 0
self.batched = SampleCallbackBatched(sample_cb, batch_size, batch_info)
def __iter__(self):
if self.iters > 0:
self.epoch_idx += 1
self.iters = 0
return self
def __next__(self):
batch_info = BatchInfo(self.iters, self.epoch_idx) if self.batch_info else self.iters
batch = self.batched(batch_info)
self.iters += 1
return batch
def generator_fun():
while True:
yield [np.full((2, 2), 42)]
def check_source_build(source):
pipe = utils.create_pipe(source, 'cpu', 10, py_num_workers=4, py_start_method='spawn',
parallel=True)
pipe.build()
def test_wrong_source():
callable_msg = ("Callable passed to External Source in parallel mode (when `parallel=True`) "
"must accept exactly one argument*. Got {} instead.")
batch_required_msg = "Parallel external source with {} must be run in a batch mode"
disallowed_sources = [
(no_arg_fun, (TypeError, callable_msg.format("a callable that does not accept arguments"))),
(multi_arg_fun,
(TypeError, "External source callback must be a callable with 0 or 1 argument")),
(Iterable(), (TypeError, batch_required_msg.format("an iterable"))),
(generator_fun, (TypeError, batch_required_msg.format("a generator function"))),
(generator_fun(), (TypeError, batch_required_msg.format("an iterable"))),
]
for source, (error_type, error_msg) in disallowed_sources:
yield raises(error_type, error_msg)(check_source_build), source
# Test that we can launch several CPU-only pipelines by fork as we don't touch CUDA context.
@with_setup(utils.setup_function, utils.teardown_function)
def test_parallel_fork_cpu_only():
pipeline_pairs = 4
batch_size = 10
iters = 40
callback = utils.ExtCallback((4, 5), iters * batch_size, np.int32)
parallel_pipes = [(utils.create_pipe(callback, 'cpu', batch_size, py_num_workers=4,
py_start_method='fork', parallel=True, device_id=None),
utils.create_pipe(callback, 'cpu', batch_size, py_num_workers=4,
py_start_method='fork', parallel=True, device_id=None))
for i in range(pipeline_pairs)]
for pipe0, pipe1 in parallel_pipes:
pipe0.build()
pipe1.build()
utils.capture_processes(pipe0._py_pool)
utils.capture_processes(pipe1._py_pool)
utils.compare_pipelines(pipe0, pipe1, batch_size, iters)
def test_parallel_no_workers():
batch_size = 10
iters = 4
callback = utils.ExtCallback((4, 5), iters * batch_size, np.int32)
parallel_pipe = utils.create_pipe(callback, 'cpu', batch_size, py_num_workers=0,
py_start_method='spawn', parallel=True, device_id=None)
parallel_pipe.build()
assert parallel_pipe._py_pool is None
assert not parallel_pipe._py_pool_started
@with_setup(utils.setup_function, utils.teardown_function)
def test_parallel_fork():
epoch_size = 250
callback = utils.ExtCallback((4, 5), epoch_size, np.int32)
pipes = [(utils.create_pipe(callback, 'cpu', batch_size, py_num_workers=num_workers,
py_start_method='fork', parallel=True),
utils.create_pipe(callback, 'cpu', batch_size, parallel=False), dtype, batch_size)
for dtype in [np.float32, np.int16] for num_workers in [1, 3, 4] for batch_size in
[1, 16, 150, 250]]
pipes.append((utils.create_pipe(Iterable(32, (4, 5), dtype=np.int16), 'cpu', 32,
py_num_workers=1, py_start_method='fork', parallel=True,
batch=True),
utils.create_pipe(Iterable(32, (4, 5), dtype=np.int16), 'cpu', 32, parallel=False,
batch=True), np.int16, 32))
for parallel_pipe, _, _, _ in pipes:
parallel_pipe.start_py_workers()
for parallel_pipe, pipe, dtype, batch_size in pipes:
yield utils.check_callback, parallel_pipe, pipe, epoch_size, batch_size, dtype
# explicitely call py_pool close
# as nose might still reference parallel_pipe from the yield above
parallel_pipe._py_pool.close()
# test that another pipline with forking initialization fails
# as there is CUDA contexts already initialized
parallel_pipe = utils.create_pipe(callback, 'cpu', 16, py_num_workers=4, py_start_method='fork',
parallel=True)
yield raises(RuntimeError,
"Cannot fork a process when the CUDA has been initialized in the process.")(
utils.build_and_run_pipeline), parallel_pipe, 1
def test_dtypes():
yield from utils.check_spawn_with_callback(utils.ExtCallback)
def test_random_data():
yield from utils.check_spawn_with_callback(utils.ExtCallback,
shapes=[(100, 40, 3), (8, 64, 64, 3)],
random_data=True)
def test_randomly_shaped_data():
yield from utils.check_spawn_with_callback(utils.ExtCallback,
shapes=[(100, 40, 3), (8, 64, 64, 3)],
random_data=True, random_shape=True)
def test_num_outputs():
yield from utils.check_spawn_with_callback(utils.ExtCallbackMultipleOutputs,
utils.ExtCallbackMultipleOutputs, num_outputs=2,
dtypes=[np.uint8, np.float])
def test_tensor_cpu():
yield from utils.check_spawn_with_callback(utils.ExtCallbackTensorCPU)
@with_setup(utils.setup_function, utils.teardown_function)
def _test_exception_propagation(callback, batch_size, num_workers, expected):
pipe = utils.create_pipe(callback, 'cpu', batch_size, py_num_workers=num_workers,
py_start_method='spawn', parallel=True)
raises(expected)(utils.build_and_run_pipeline)(pipe, None)
def test_exception_propagation():
for raised, expected in [(StopIteration, StopIteration), (utils.CustomException, Exception)]:
callback = utils.ExtCallback((4, 4), 250, np.int32, exception_class=raised)
for num_workers in [1, 4]:
for batch_size in [1, 15, 150]:
yield _test_exception_propagation, callback, batch_size, num_workers, expected
@with_setup(utils.setup_function, utils.teardown_function)
def _test_stop_iteration_resume(callback, batch_size, layout, num_workers):
pipe = utils.create_pipe(callback, 'cpu', batch_size, layout=layout, py_num_workers=num_workers,
py_start_method='spawn', parallel=True)
utils.check_stop_iteration_resume(pipe, batch_size, layout)
def test_stop_iteration_resume():
callback = utils.ExtCallback((4, 4), 250, 'int32')
layout = "XY"
for num_workers in [1, 4]:
for batch_size in [1, 15, 150]:
yield _test_stop_iteration_resume, callback, batch_size, layout, num_workers
@with_setup(utils.setup_function, utils.teardown_function)
def _test_layout(callback, batch_size, layout, num_workers):
pipe = utils.create_pipe(callback, 'cpu', batch_size, layout=layout, py_num_workers=num_workers,
py_start_method='spawn', parallel=True)
utils.check_layout(pipe, layout)
def test_layout():
for layout, dims in zip(["X", "XY", "XYZ"], ((4,), (4, 4), (4, 4, 4))):
callback = utils.ExtCallback(dims, 1024, 'int32')
for num_workers in [1, 4]:
for batch_size in [1, 256, 600]:
yield _test_layout, callback, batch_size, layout, num_workers
class ext_cb():
def __init__(self, name, shape):
self.name = name
self.shape = shape
def __call__(self, sinfo):
return np.full(self.shape, sinfo.idx_in_epoch, dtype=np.int32)
@with_setup(utils.setup_function, utils.teardown_function)
def _test_vs_non_parallel(batch_size, cb_parallel, cb_seq, batch, py_num_workers):
pipe = dali.Pipeline(batch_size=batch_size, device_id=None, num_threads=5,
py_num_workers=py_num_workers, py_start_method='spawn')
with pipe:
ext_seq = dali.fn.external_source(cb_parallel, batch=batch, parallel=False)
ext_par = dali.fn.external_source(cb_seq, batch=batch, parallel=True)
pipe.set_outputs(ext_seq, ext_par)
pipe.build()
utils.capture_processes(pipe._py_pool)
for i in range(10):
seq, par = pipe.run()
for j in range(batch_size):
s = seq.at(j)
p = par.at(j)
assert np.array_equal(s, p)
def test_vs_non_parallel():
for shape in [[], [10], [100, 100, 100]]:
for batch_size, cb_parallel, cb_seq, batch, py_num_workers in [
(50, ext_cb("cb 1", shape), ext_cb("cb 2", shape), False, 14),
(50, Iterable(50, shape), Iterable(50, shape), True, 1)
]:
yield _test_vs_non_parallel, batch_size, cb_parallel, cb_seq, batch, py_num_workers
def generator_shape_empty():
count = 0
while True:
yield [np.full([], count + i) for i in range(50)]
def generator_shape_10():
count = 0
while True:
yield [np.full([10], count + i) for i in range(50)]
def generator_shape_100x3():
count = 0
while True:
yield [np.full([10, 10, 10], count + i) for i in range(50)]
def test_generator_vs_non_parallel():
for cb in [generator_shape_empty, generator_shape_10, generator_shape_100x3]:
yield _test_vs_non_parallel, 50, cb, cb, True, 1
@with_setup(utils.setup_function, utils.teardown_function)
def _test_cycle_raise(cb, is_gen_fun, batch_size, epoch_size, reader_queue_size):
pipe = utils.create_pipe(cb, "cpu", batch_size=batch_size, py_num_workers=1,
py_start_method="spawn", parallel=True, device_id=None, batch=True,
num_threads=5, cycle="raise", reader_queue_depth=reader_queue_size)
pipe.build()
utils.capture_processes(pipe._py_pool)
if is_gen_fun:
refer_iter = cb()
else:
refer_iter = cb
for _ in range(3):
i = 0
while True:
try:
(batch,) = pipe.run()
expected_batch = next(refer_iter)
assert len(batch) == len(expected_batch), \
f"Batch length mismatch: expected {len(expected_batch)}, got {len(batch)}"
for sample, expected_sample in zip(batch, expected_batch):
np.testing.assert_equal(sample, expected_sample)
i += 1
except StopIteration:
pipe.reset()
if is_gen_fun:
refer_iter = cb()
else:
refer_iter = iter(cb)
assert i == epoch_size, \
f"Number of iterations mismatch: expected {epoch_size}, got {i}"
break
def generator_epoch_size_1():
yield [np.full((4, 5), i) for i in range(20)]
def generator_epoch_size_4():
for j in range(4):
yield [np.full((4, 5), j + i) for i in range(20)]
def test_cycle_raise():
batch_size = 20
for epoch_size, cb, is_gen_fun in [
(1, Iterable(batch_size, (4, 5), epoch_size=1), False),
(4, Iterable(batch_size, (4, 5), epoch_size=4), False),
(1, generator_epoch_size_1, True),
(4, generator_epoch_size_4, True),
]:
for reader_queue_size in (1, 2, 6):
yield _test_cycle_raise, cb, is_gen_fun, batch_size, epoch_size, reader_queue_size
@with_setup(utils.setup_function, utils.teardown_function)
def _test_cycle_quiet(cb, is_gen_fun, batch_size, epoch_size, reader_queue_size):
pipe = utils.create_pipe(cb, "cpu", batch_size=batch_size, py_num_workers=1,
py_start_method="spawn", parallel=True, device_id=None, batch=True,
num_threads=5, cycle="quiet", reader_queue_depth=reader_queue_size)
pipe.build()
utils.capture_processes(pipe._py_pool)
refer_iter = cb
for i in range(3 * epoch_size + 1):
if i % epoch_size == 0:
if is_gen_fun:
refer_iter = cb()
else:
refer_iter = iter(cb)
(batch,) = pipe.run()
expected_batch = next(refer_iter)
assert len(batch) == len(expected_batch), \
f"Batch length mismatch: expected {len(expected_batch)}, got {len(batch)}"
for sample, expected_sample in zip(batch, expected_batch):
np.testing.assert_equal(sample, expected_sample)
def test_cycle_quiet():
batch_size = 20
for epoch_size, cb, is_gen_fun in [
(1, Iterable(batch_size, (4, 5), epoch_size=1), False),
(4, Iterable(batch_size, (4, 5), epoch_size=4), False),
(1, generator_epoch_size_1, True),
(4, generator_epoch_size_4, True),
]:
for reader_queue_size in (1, 2, 6):
yield _test_cycle_quiet, cb, is_gen_fun, batch_size, epoch_size, reader_queue_size
@with_setup(utils.setup_function, utils.teardown_function)
def _test_cycle_quiet_non_resetable(iterable, reader_queue_size, batch_size, epoch_size):
pipe = utils.create_pipe(iterable, "cpu", batch_size=batch_size, py_num_workers=1,
py_start_method="spawn", parallel=True, device_id=None, batch=True,
num_threads=5, cycle="quiet", reader_queue_depth=reader_queue_size)
pipe.build()
utils.capture_processes(pipe._py_pool)
for _ in range(epoch_size):
pipe.run()
try:
pipe.run()
except StopIteration:
pipe.reset()
try:
pipe.run()
except StopIteration:
pass
else:
assert False, "Expected stop iteration"
else:
assert False, "Expected stop iteration at the end of the epoch"
def test_cycle_quiet_non_resetable():
epoch_size = 3
batch_size = 20
iterable = FaultyResetIterable(batch_size, (5, 4), epoch_size=epoch_size)
for reader_queue_size in (1, 3, 6):
yield _test_cycle_quiet_non_resetable, iterable, reader_queue_size, batch_size, epoch_size
@with_setup(utils.setup_function, utils.teardown_function)
def _test_cycle_no_resetting(cb, batch_size, epoch_size, reader_queue_size):
pipe = utils.create_pipe(cb, "cpu", batch_size=batch_size, py_num_workers=1,
py_start_method="spawn", parallel=True, device_id=None, batch=True,
num_threads=5, cycle=None, reader_queue_depth=reader_queue_size)
pipe.build()
utils.capture_processes(pipe._py_pool)
for _ in range(epoch_size):
pipe.run()
try:
pipe.run()
except StopIteration:
pipe.reset()
else:
assert False, "Expected stop iteration"
pipe.run()
def test_cycle_no_resetting():
batch_size = 20
for epoch_size, cb in [
(1, Iterable(batch_size, (4, 5), epoch_size=1)),
(4, Iterable(batch_size, (4, 5), epoch_size=4)),
(1, generator_epoch_size_1),
(4, generator_epoch_size_4),
]:
for reader_queue_size in (1, 2, 6):
yield raises(StopIteration)(
_test_cycle_no_resetting), cb, batch_size, epoch_size, reader_queue_size
@with_setup(utils.setup_function, utils.teardown_function)
def _test_all_kinds_parallel(sample_cb, batch_cb, iter_cb, batch_size, py_num_workers,
reader_queue_sizes, num_iters):
@dali.pipeline_def(batch_size=batch_size, num_threads=4, device_id=None,
py_num_workers=py_num_workers, py_start_method='spawn')
def pipeline():
queue_size_1, queue_size_2, queue_size_3 = reader_queue_sizes
sample_out = dali.fn.external_source(source=sample_cb, parallel=True, batch=False,
prefetch_queue_depth=queue_size_1)
batch_out = dali.fn.external_source(source=batch_cb, parallel=True, batch=True,
prefetch_queue_depth=queue_size_2, batch_info=True)
iter_out = dali.fn.external_source(source=iter_cb, parallel=True, batch=True,
prefetch_queue_depth=queue_size_3, cycle="raise")
return (sample_out, batch_out, iter_out)
pipe = pipeline()
pipe.build()
utils.capture_processes(pipe._py_pool)
for _ in range(3):
i = 0
while True:
try:
(sample_outs, batch_outs, iter_outs) = pipe.run()
assert len(sample_outs) == len(batch_outs), \
f"Batch length mismatch: sample: {len(sample_outs)}, batch: {len(batch_outs)}"
assert len(batch_outs) == len(iter_outs), \
f"Batch length mismatch: batch: {len(batch_outs)}, iter: {len(iter_outs)}"
for sample_out, batch_out, iter_out in zip(sample_outs, batch_outs, iter_outs):
np.testing.assert_equal(np.array(sample_out), np.array(batch_out))
np.testing.assert_equal(np.array(batch_out), np.array(iter_out))
i += 1
except StopIteration:
pipe.reset()
assert i == num_iters, \
f"Number of iterations mismatch: expected {num_iters}, got {i}"
break
def test_all_kinds_parallel():
for batch_size in (1, 17):
for num_iters in (1, 3, 31):
for trailing in (0, 30):
if trailing >= batch_size:
continue
epoch_size = num_iters * batch_size + trailing
sample_cb = utils.ExtCallback((4, 5), epoch_size, np.int32)
batch_cb = SampleCallbackBatched(sample_cb, batch_size, batch_info=True)
iterator_cb = SampleCallbackIterator(sample_cb, batch_size, batch_info=True)
for reader_queue_sizes in (
(1, 1, 1), (2, 2, 2), (5, 5, 5), (3, 1, 1), (1, 3, 1), (1, 1, 3)):
for num_workers in (1, 7):
yield _test_all_kinds_parallel, sample_cb, batch_cb, iterator_cb, \
batch_size, num_workers, reader_queue_sizes, num_iters
def collect_iterations(pipe, num_iters):
outs = []
for _ in range(num_iters):
try:
out = pipe.run()
outs.append([[np.copy(sample) for sample in batch] for batch in out])
except StopIteration:
outs.append(StopIteration)
pipe.reset()
return outs
@with_setup(utils.setup_function, utils.teardown_function)
def _test_cycle_multiple_iterators(batch_size, iters_num, py_num_workers, reader_queue_sizes,
cycle_policies, epoch_sizes):
@dali.pipeline_def(batch_size=batch_size, num_threads=4, device_id=None,
py_num_workers=py_num_workers, py_start_method='spawn')
def pipeline(sample_cb, iter_1, iter_2, parallel):
if parallel:
queue_size_0, queue_size_1, queue_size_2 = reader_queue_sizes
else:
queue_size_0, queue_size_1, queue_size_2 = None, None, None
cycle_1, cycle_2 = cycle_policies
sample_out = dali.fn.external_source(source=sample_cb, parallel=parallel, batch=False,
prefetch_queue_depth=queue_size_0)
iter1_out = dali.fn.external_source(source=iter_1, parallel=parallel, batch=True,
prefetch_queue_depth=queue_size_1, cycle=cycle_1)
iter2_out = dali.fn.external_source(source=iter_2, parallel=parallel, batch=True,
prefetch_queue_depth=queue_size_2, cycle=cycle_2)
return (sample_out, iter1_out, iter2_out)
shape = (2, 3)
sample_epoch_size, iter_1_epoch_size, iter_2_epoch_size = epoch_sizes
sample_cb = utils.ExtCallback((4, 5), sample_epoch_size * batch_size, np.int32)
iter_1 = Iterable(batch_size, shape, epoch_size=iter_1_epoch_size, dtype=np.int32)
iter_2 = Iterable(batch_size, shape, epoch_size=iter_2_epoch_size, dtype=np.int32)
pipe_parallel = pipeline(sample_cb, iter_1, iter_2, parallel=True)
pipe_seq = pipeline(sample_cb, iter_1, iter_2, parallel=False)
pipe_parallel.build()
utils.capture_processes(pipe_parallel._py_pool)
pipe_seq.build()
parallel_outs = collect_iterations(pipe_parallel, iters_num)
seq_outs = collect_iterations(pipe_seq, iters_num)
assert len(parallel_outs) == len(seq_outs)
for parallel_out, seq_out in zip(parallel_outs, seq_outs):
if parallel_out == StopIteration or seq_out == StopIteration:
assert parallel_out == seq_out
continue
assert len(parallel_out) == len(seq_out) == 3
for batch_parallel, batch_seq in zip(parallel_out, seq_out):
assert len(batch_parallel) == len(batch_seq) == batch_size
for sample_parallel, sample_seq in zip(batch_parallel, batch_seq):
np.testing.assert_equal(np.array(sample_parallel), np.array(sample_seq))
def test_cycle_multiple_iterators():
batch_size = 50
iters_num = 17
num_workers = 4
for prefetch_queue_depths in ((3, 1, 1), (1, 3, 1), (1, 1, 3), (1, 1, 1), (3, 3, 3)):
for cycle_policies in (
("raise", "raise"), ("quiet", "raise"), ("raise", "quiet"), ("quiet", "quiet"),
(True, True)
):
for epoch_sizes in ((8, 4, 6), (8, 6, 4), (4, 6, 8), (1, 1, 1)):
yield _test_cycle_multiple_iterators, batch_size, iters_num, num_workers, \
prefetch_queue_depths, cycle_policies, epoch_sizes
def ext_cb2(sinfo):
return np.array([sinfo.idx_in_epoch, sinfo.idx_in_batch, sinfo.iteration], dtype=np.int32)
@with_setup(utils.setup_function, utils.teardown_function)
def test_discard():
bs = 5
pipe = dali.Pipeline(batch_size=bs, device_id=None, num_threads=5, py_num_workers=4,
py_start_method='spawn')
with pipe:
ext1 = dali.fn.external_source([[np.float32(i) for i in range(bs)]] * 3, cycle='raise')
ext2 = dali.fn.external_source(ext_cb2, batch=False, parallel=True)
ext3 = dali.fn.external_source(ext_cb2, batch=False, parallel=False)
pipe.set_outputs(ext1, ext2, ext3)
pipe.build()
utils.capture_processes(pipe._py_pool)
sample_in_epoch = 0
iteration = 0
for i in range(10):
try:
e1, e2, e3 = pipe.run()
for i in range(bs):
assert e1.at(i) == i
assert np.array_equal(e2.at(i), np.array([sample_in_epoch, i, iteration]))
assert np.array_equal(e3.at(i), np.array([sample_in_epoch, i, iteration]))
sample_in_epoch += 1
iteration += 1
except StopIteration:
sample_in_epoch = 0
iteration = 0
pipe.reset()
class SampleCb:
def __init__(self, batch_size, epoch_size):
self.batch_size = batch_size
self.epoch_size = epoch_size
def __call__(self, sample_info):
if sample_info.iteration >= self.epoch_size:
raise StopIteration
return np.array([
sample_info.idx_in_epoch, sample_info.idx_in_batch,
sample_info.iteration, sample_info.epoch_idx], dtype=np.int32)
@with_setup(utils.setup_function, utils.teardown_function)
def _test_epoch_idx(batch_size, epoch_size, cb, py_num_workers, prefetch_queue_depth,
reader_queue_depth, batch_mode, batch_info):
num_epochs = 3
pipe = utils.create_pipe(cb, "cpu", batch_size=batch_size, py_num_workers=py_num_workers,
py_start_method="spawn", parallel=True, device_id=0, batch=batch_mode,
num_threads=1, cycle=None, batch_info=batch_info,
prefetch_queue_depth=prefetch_queue_depth,
reader_queue_depth=reader_queue_depth)
pipe.build()
utils.capture_processes(pipe._py_pool)
for epoch_idx in range(num_epochs):
for iteration in range(epoch_size):
(batch,) = pipe.run()
assert len(batch) == batch_size
for sample_i, sample in enumerate(batch):
expected = np.array([iteration * batch_size + sample_i, sample_i, iteration,
epoch_idx if not batch_mode or batch_info else 0])
np.testing.assert_array_equal(sample, expected)
try:
pipe.run()
except StopIteration:
pipe.reset()
else:
assert False, "expected StopIteration"
def test_epoch_idx():
num_workers = 4
prefetch_queue_depth = 2
for batch_size in (1, 50):
for epoch_size in (1, 3, 7):
for reader_queue_depth in (1, 5):
sample_cb = SampleCb(batch_size, epoch_size)
yield _test_epoch_idx, batch_size, epoch_size, sample_cb, num_workers, \
prefetch_queue_depth, reader_queue_depth, False, None
batch_cb = SampleCallbackBatched(sample_cb, batch_size, True)
yield _test_epoch_idx, batch_size, epoch_size, batch_cb, num_workers, \
prefetch_queue_depth, reader_queue_depth, True, True
batch_cb = SampleCallbackBatched(sample_cb, batch_size, False)
yield _test_epoch_idx, batch_size, epoch_size, batch_cb, num_workers, \
prefetch_queue_depth, reader_queue_depth, True, False
class PermutableSampleCb:
def __init__(self, batch_size, epoch_size, trailing_samples):
self.batch_size = batch_size
self.epoch_size = epoch_size
self.trailing_samples = trailing_samples
self.last_seen_epoch = None
self.perm = None
def __call__(self, sample_info):
if sample_info.iteration > self.epoch_size or \
sample_info.iteration == self.epoch_size and sample_info.idx_in_batch >= self.trailing_samples: # noqa: E501
raise StopIteration
if self.last_seen_epoch != sample_info.epoch_idx:
self.last_seen_epoch = sample_info.epoch_idx
rng = np.random.default_rng(seed=42 + self.last_seen_epoch)
self.perm = rng.permutation(self.batch_size * self.epoch_size + self.trailing_samples)
return np.array([self.perm[sample_info.idx_in_epoch]], dtype=np.int32)
@with_setup(utils.setup_function, utils.teardown_function)
def _test_permute_dataset(batch_size, epoch_size, trailing_samples, cb, py_num_workers,
prefetch_queue_depth, reader_queue_depth):
num_epochs = 3
pipe = utils.create_pipe(cb, "cpu", batch_size=batch_size, py_num_workers=py_num_workers,
py_start_method="spawn", parallel=True, device_id=0, batch=False,
num_threads=1, cycle=None, prefetch_queue_depth=prefetch_queue_depth,
reader_queue_depth=reader_queue_depth)
pipe.build()
utils.capture_processes(pipe._py_pool)
for epoch_idx in range(num_epochs):
epoch_data = [False for _ in range(epoch_size * batch_size + trailing_samples)]
for _ in range(epoch_size):
(batch,) = pipe.run()
assert len(batch) == batch_size
for sample in batch:
epoch_data[np.array(sample)[0]] = True
assert sum(epoch_data) == epoch_size * batch_size, \
"Epoch number {} did not contain some samples from data set".format(epoch_idx)
try:
pipe.run()
except StopIteration:
pipe.reset()
else:
assert False, "expected StopIteration"
def test_permute_dataset():
for batch_size, trailing_samples in ((4, 0), (100, 0), (100, 99)):
for epoch_size in (3, 7):
cb = PermutableSampleCb(batch_size, epoch_size, trailing_samples=trailing_samples)
for reader_queue_depth in (1, 5):
yield _test_permute_dataset, batch_size, epoch_size, trailing_samples, \
cb, 4, 1, reader_queue_depth
class PerIterShapeSource:
def __init__(self, shapes):
self.shapes = shapes
def __call__(self, sample_info):
batch_idx = sample_info.iteration
shape = self.shapes[batch_idx % len(self.shapes)]
return np.full(shape, sample_info.idx_in_epoch, dtype=np.uint8)
def per_iter_shape_pipeline(shapes, py_num_workers=4, batch_size=4, parallel=True,
bytes_per_sample_hint=None):
@dali.pipeline_def
def pipeline():
return dali.fn.external_source(
PerIterShapeSource(shapes),
batch=False, parallel=parallel,
bytes_per_sample_hint=bytes_per_sample_hint)
pipe = pipeline(
batch_size=batch_size, py_num_workers=py_num_workers,
device_id=0, num_threads=4, py_start_method="spawn")
pipe.build()
return pipe
def test_no_parallel_no_shm():
shapes = [(4, 1024, 1024)]
pipe = per_iter_shape_pipeline(shapes, parallel=False)
for _ in range(5):
pipe.run()
assert pipe.external_source_shm_statistics()["capacities"] == []
def test_default_shm_size():
default_shm_size = 1024 * 1024
shapes = [(16, 1024, 1024)]
pipe_default = per_iter_shape_pipeline(shapes)
default_sizes = pipe_default.external_source_shm_statistics()["capacities"]
assert len(default_sizes) > 0
for size in default_sizes:
assert size == default_shm_size, (
f"Expected initial size to be {default_shm_size}, got {size}.")
pipe_too_small_hint = per_iter_shape_pipeline(
shapes, bytes_per_sample_hint=1024)
sizes = pipe_too_small_hint.external_source_shm_statistics()["capacities"]
assert len(sizes) > 0
for size in sizes:
assert size == default_shm_size, (
f"Expected initial size to be {default_shm_size}, got {size}.")
def test_initial_hint():
sample_size = 32 * 1024 * 1024
shapes = [(32, 1024, 1024)]
# make the initial size still smaller than necessary to check if reallocation works
bytes_per_sample_hint = 4 * 1024 * 1024
batch_size = 7
num_workers = 3
min_samples_in_mini_batch = batch_size // num_workers
max_samples_in_mini_batch = (batch_size + num_workers - 1) // num_workers
initial_shm_size = max_samples_in_mini_batch * bytes_per_sample_hint
expected_min_chunk_size = min_samples_in_mini_batch * sample_size
pipe = per_iter_shape_pipeline(
shapes, bytes_per_sample_hint=bytes_per_sample_hint,
batch_size=batch_size, py_num_workers=num_workers)
sizes = pipe.external_source_shm_statistics()["capacities"]
assert len(sizes) > 0
for size in sizes:
assert size == initial_shm_size, (
f"Expected initial size to be {initial_shm_size}, got {size}.")
for _ in range(5):
pipe.run()
sizes = pipe.external_source_shm_statistics()["capacities"]
assert len(sizes) > 0
for size in sizes:
assert size >= expected_min_chunk_size, (
f"Expected the size to be at least {expected_min_chunk_size}, got {size}.")
def test_variable_sample_size():
shapes = [(31, 1024, 1024), (32, 1024, 1024)]
# make the initial enough to hold samples of any of the two shapes
bytes_per_sample_hint = 32 * 1024 * 1024
# add some extra bytes to accommodate meta-data (we purposely do not stipulate
# the exact number in the docs, as
# 1. we may want to modify the exact meta-data stored,
# 2. they are pickled, so the serialized data size could change with pickle itself,
# 3. there are things like idx_in_epoch serialized that are truly unbound in Python)
bytes_per_sample_hint += 4096
batch_size = 8
num_workers = 4
max_samples_in_mini_batch = batch_size // num_workers
initial_shm_size = max_samples_in_mini_batch * bytes_per_sample_hint
pipe = per_iter_shape_pipeline(
shapes, bytes_per_sample_hint=bytes_per_sample_hint,
batch_size=batch_size, py_num_workers=num_workers)
no_hint_pipe = per_iter_shape_pipeline(
shapes, batch_size=batch_size, py_num_workers=num_workers)
sizes = pipe.external_source_shm_statistics()["capacities"]
assert len(sizes) > 0
for size in sizes:
assert size == initial_shm_size, (
f"Expected initial size to be {initial_shm_size}, got {size}.")
for _ in range(5):
pipe.run()
no_hint_pipe.run()
sizes = pipe.external_source_shm_statistics()["capacities"]
assert len(sizes) > 0
for size in sizes:
assert size >= initial_shm_size, (
f"Expected the size to be unchanged and equal {initial_shm_size}, got {size}.")
per_sample_sizes = pipe.external_source_shm_statistics()["per_sample_capacities"]
assert len(sizes) == len(per_sample_sizes)
for size in per_sample_sizes:
assert size == bytes_per_sample_hint, (
f"Expected initial per sample size to be {bytes_per_sample_hint}, got {size}.")
# This demonstrates that providing a hint can improve memory usage, but if one day
# DALI changes strategy of dynamic shm reallocation it can be simply removed
no_hint_pipe_shm_size = min(no_hint_pipe.external_source_shm_statistics()["capacities"])
sizes = pipe.external_source_shm_statistics()["capacities"]
for size in sizes:
assert size < no_hint_pipe_shm_size, (
f"Expected the size to be less than {no_hint_pipe_shm_size}, got {size}.")
|
DALI-main
|
dali/test/python/test_external_source_parallel.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION & AFFILIATES. 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 glob
import numpy as np
import nvidia.dali.tensors as tensors
import nvidia.dali.fn as fn
import nvidia.dali.math as dmath
import nvidia.dali.tfrecord as tfrec
import nvidia.dali.types as types
import os
import re
from collections.abc import Iterable
from nose.plugins.attrib import attr
from nose.tools import nottest
from nvidia.dali.pipeline import Pipeline, pipeline_def
from nvidia.dali.pipeline.experimental import pipeline_def as experimental_pipeline_def
from nvidia.dali.plugin.numba.fn.experimental import numba_function
from nose_utils import assert_raises
from segmentation_test_utils import make_batch_select_masks
from test_dali_cpu_only_utils import (pipeline_arithm_ops_cpu, setup_test_nemo_asr_reader_cpu,
setup_test_numpy_reader_cpu)
from test_detection_pipeline import coco_anchors
from test_utils import get_dali_extra_path, get_files, module_functions
from webdataset_base import generate_temp_index_file as generate_temp_wds_index
data_root = get_dali_extra_path()
images_dir = os.path.join(data_root, 'db', 'single', 'jpeg')
audio_files = get_files(os.path.join('db', 'audio', 'wav'), 'wav')
caffe_dir = os.path.join(data_root, 'db', 'lmdb')
caffe2_dir = os.path.join(data_root, 'db', 'c2lmdb')
recordio_dir = os.path.join(data_root, 'db', 'recordio')
tfrecord_dir = os.path.join(data_root, 'db', 'tfrecord')
webdataset_dir = os.path.join(data_root, 'db', 'webdataset')
coco_dir = os.path.join(data_root, 'db', 'coco', 'images')
coco_annotation = os.path.join(data_root, 'db', 'coco', 'instances.json')
sequence_dir = os.path.join(data_root, 'db', 'sequence', 'frames')
video_files = [
os.path.join(get_dali_extra_path(), 'db', 'video', 'vfr', 'test_1.mp4'),
os.path.join(get_dali_extra_path(), 'db', 'video', 'vfr', 'test_2.mp4')]
batch_size = 2
test_data_shape = [10, 20, 3]
def get_data():
out = [np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8) for _ in
range(batch_size)]
return out
# The same code is used as CPU-only pipeline to test if TF plugin loads successfully
# during its installation.
def test_tensorflow_build_check():
@pipeline_def()
def get_dali_pipe():
data = types.Constant(1)
return data
pipe = get_dali_pipe(batch_size=3, device_id=types.CPU_ONLY_DEVICE_ID, num_threads=1)
pipe.build()
pipe.run()
def test_move_to_device_end():
test_data_shape = [1, 3, 0, 4]
def get_data():
out = [np.empty(test_data_shape, dtype=np.uint8) for _ in range(batch_size)]
return out
pipe = Pipeline(batch_size=batch_size, num_threads=3, device_id=None)
outs = fn.external_source(source=get_data)
pipe.set_outputs(outs.gpu())
assert_raises(
RuntimeError, pipe.build,
glob='Cannot move the data node __ExternalSource_* to the GPU in a CPU-only pipeline. '
'The `device_id` parameter is set to `CPU_ONLY_DEVICE_ID`. '
'Set `device_id` to a valid GPU identifier to enable GPU features in the pipeline.')
def test_move_to_device_middle():
test_data_shape = [1, 3, 0, 4]
def get_data():
out = [np.empty(test_data_shape, dtype=np.uint8) for _ in range(batch_size)]
return out
pipe = Pipeline(batch_size=batch_size, num_threads=3, device_id=None)
data = fn.external_source(source=get_data)
outs = fn.rotate(data.gpu(), angle=25)
pipe.set_outputs(outs)
assert_raises(
RuntimeError, pipe.build,
glob="Cannot add a GPU operator Rotate, device_id should not be equal CPU_ONLY_DEVICE_ID.")
def check_bad_device(device_id, error_msg):
test_data_shape = [1, 3, 0, 4]
def get_data():
out = [np.empty(test_data_shape, dtype=np.uint8) for _ in range(batch_size)]
return out
pipe = Pipeline(batch_size=batch_size, num_threads=3, device_id=device_id)
outs = fn.external_source(source=get_data, device="gpu")
pipe.set_outputs(outs)
assert_raises(RuntimeError, pipe.build, glob=error_msg)
def test_gpu_op_bad_device():
device_ids = [None, 0]
error_msgs = [
"Cannot add a GPU operator ExternalSource, device_id should not be equal CPU_ONLY_DEVICE_ID.", # noqa: E501
"Failed to load libcuda.so. Check your library paths and if the driver is installed correctly." # noqa: E501
]
for device_id, error_msg in zip(device_ids, error_msgs):
yield check_bad_device, device_id, error_msg
def check_mixed_op_bad_device(device_id, error_msg):
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=device_id)
input, _ = fn.readers.file(file_root=images_dir, shard_id=0, num_shards=1)
decoded = fn.decoders.image(input, device="mixed", output_type=types.RGB)
pipe.set_outputs(decoded)
assert_raises(RuntimeError, pipe.build, glob=error_msg)
def test_mixed_op_bad_device():
device_ids = [None, 0]
error_msgs = [
"Cannot add a mixed operator decoders__Image with a GPU output, device_id should not be CPU_ONLY_DEVICE_ID.", # noqa: E501
"Failed to load libcuda.so. Check your library paths and if the driver is installed correctly." # noqa: E501
]
for device_id, error_msg in zip(device_ids, error_msgs):
yield check_mixed_op_bad_device, device_id, error_msg
def check_single_input(op, input_layout="HWC", get_data=get_data, batch=True, cycle=None,
exec_async=True, exec_pipelined=True, **kwargs):
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None, exec_async=exec_async,
exec_pipelined=exec_pipelined)
with pipe:
data = fn.external_source(source=get_data, layout=input_layout, batch=batch, cycle=cycle)
processed = op(data, **kwargs)
if isinstance(processed, Iterable):
pipe.set_outputs(*processed)
else:
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
def check_no_input(op, get_data=get_data, **kwargs):
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
with pipe:
processed = op(**kwargs)
if isinstance(processed, Iterable):
pipe.set_outputs(*processed)
else:
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
def test_rotate_cpu():
check_single_input(fn.rotate, angle=25)
def test_brightness_contrast_cpu():
check_single_input(fn.brightness_contrast)
def test_hue_cpu():
check_single_input(fn.hue)
def test_brightness_cpu():
check_single_input(fn.brightness)
def test_contrast_cpu():
check_single_input(fn.contrast)
def test_hsv_cpu():
check_single_input(fn.hsv)
def test_color_twist_cpu():
check_single_input(fn.color_twist)
def test_saturation_cpu():
check_single_input(fn.saturation)
def test_shapes_cpu():
check_single_input(fn.shapes)
def test_crop_cpu():
check_single_input(fn.crop, crop=(5, 5))
def test_color_space_coversion_cpu():
check_single_input(fn.color_space_conversion, image_type=types.BGR, output_type=types.RGB)
def test_cast_cpu():
check_single_input(fn.cast, dtype=types.INT32)
def test_cast_like_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=3, device_id=None)
out = fn.cast_like(np.array([1, 2, 3], dtype=np.int32), np.array([1.0], dtype=np.float32))
pipe.set_outputs(out)
pipe.build()
for _ in range(3):
pipe.run()
def test_resize_cpu():
check_single_input(fn.resize, resize_x=50, resize_y=50)
def test_tensor_resize_cpu():
check_single_input(fn.experimental.tensor_resize, sizes=[50, 50], axes=[0, 1])
def test_per_frame_cpu():
check_single_input(fn.per_frame, replace=True)
def test_gaussian_blur_cpu():
check_single_input(fn.gaussian_blur, window_size=5)
def test_laplacian_cpu():
check_single_input(fn.laplacian, window_size=5)
def test_crop_mirror_normalize_cpu():
check_single_input(fn.crop_mirror_normalize)
def test_flip_cpu():
check_single_input(fn.flip, horizontal=True)
def test_jpeg_compression_distortion_cpu():
check_single_input(fn.jpeg_compression_distortion, quality=10)
def test_noise_gaussian_cpu():
check_single_input(fn.noise.gaussian)
def test_noise_shot_cpu():
check_single_input(fn.noise.shot)
def test_noise_salt_and_pepper_cpu():
check_single_input(fn.noise.salt_and_pepper)
@nottest
def _test_image_decoder_args_cpu(decoder_type, **args):
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
input, _ = fn.readers.file(file_root=images_dir, shard_id=0, num_shards=1)
decoded = decoder_type(input, output_type=types.RGB, **args)
pipe.set_outputs(decoded)
pipe.build()
for _ in range(3):
pipe.run()
def test_image_decoder_cpu():
_test_image_decoder_args_cpu(fn.decoders.image)
def test_experimental_image_decoder_cpu():
_test_image_decoder_args_cpu(fn.experimental.decoders.image)
def test_image_decoder_crop_cpu():
_test_image_decoder_args_cpu(fn.decoders.image_crop, crop=(10, 10))
def test_experimental_image_decoder_crop_cpu():
_test_image_decoder_args_cpu(fn.experimental.decoders.image_crop, crop=(10, 10))
def test_image_decoder_random_crop_cpu():
_test_image_decoder_args_cpu(fn.decoders.image_random_crop)
def test_experimental_image_decoder_random_crop_cpu():
_test_image_decoder_args_cpu(fn.experimental.decoders.image_random_crop)
def test_coin_flip_cpu():
check_no_input(fn.random.coin_flip)
def test_uniform_device():
check_no_input(fn.random.uniform)
def test_reshape_cpu():
new_shape = test_data_shape.copy()
new_shape[0] //= 2
new_shape[1] *= 2
check_single_input(fn.reshape, shape=new_shape)
def test_reinterpret_cpu():
check_single_input(fn.reinterpret, rel_shape=[0.5, 1, -1])
def test_water_cpu():
check_single_input(fn.water)
def test_sphere_cpu():
check_single_input(fn.sphere)
def test_erase_cpu():
check_single_input(fn.erase, anchor=[0.3], axis_names="H", normalized_anchor=True, shape=[0.1],
normalized_shape=True)
def test_random_resized_crop_cpu():
check_single_input(fn.random_resized_crop, size=[5, 5])
def test_expand_dims_cpu():
check_single_input(fn.expand_dims, axes=1, new_axis_names="Z")
def test_coord_transform_cpu():
M = [0, 0, 1,
0, 1, 0,
1, 0, 0]
check_single_input(fn.coord_transform, M=M, dtype=types.UINT8)
def test_grid_mask_cpu():
check_single_input(fn.grid_mask, tile=51, ratio=0.38158387, angle=2.6810782)
def test_multi_paste_cpu():
check_single_input(fn.multi_paste, in_ids=np.array([0, 1]), output_size=test_data_shape)
def test_roi_random_crop_cpu():
check_single_input(fn.roi_random_crop,
crop_shape=[x // 2 for x in test_data_shape],
roi_start=[x // 4 for x in test_data_shape],
roi_shape=[x // 2 for x in test_data_shape])
def test_random_object_bbox_cpu():
get_data = [
np.int32([[1, 0, 0, 0],
[1, 2, 2, 1],
[1, 1, 2, 0],
[2, 0, 0, 1]]),
np.int32([[0, 3, 3, 0],
[1, 0, 1, 2],
[0, 1, 1, 0],
[0, 2, 0, 1],
[0, 2, 2, 1]])
]
check_single_input(fn.segmentation.random_object_bbox, get_data=get_data, batch=False,
cycle="quiet", input_layout="")
@attr('numba')
def test_numba_func_cpu():
def set_all_values_to_255_batch(out0, in0):
out0[0][:] = 255
def setup_out_shape(out_shape, in_shape):
pass
check_single_input(numba_function, run_fn=set_all_values_to_255_batch, out_types=[types.UINT8],
in_types=[types.UINT8], outs_ndim=[3], ins_ndim=[3],
setup_fn=setup_out_shape, batch_processing=True)
@attr('pytorch')
def test_dl_tensor_python_function_cpu():
import torch.utils.dlpack as torch_dlpack
def dl_tensor_operation(tensor):
tensor = torch_dlpack.from_dlpack(tensor)
tensor_n = tensor.double() / 255
ret = tensor_n.sin()
ret = torch_dlpack.to_dlpack(ret)
return ret
def batch_dl_tensor_operation(tensors):
out = [dl_tensor_operation(t) for t in tensors]
return out
check_single_input(fn.dl_tensor_python_function, function=batch_dl_tensor_operation,
batch_processing=True, exec_async=False, exec_pipelined=False)
def test_nonsilent_region_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
test_data_shape = [200]
def get_data():
out = [np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8) for _ in
range(batch_size)]
out[0][0] = 0
out[1][0] = 0
out[1][1] = 0
return out
data = fn.external_source(source=get_data)
processed, _ = fn.nonsilent_region(data)
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
test_audio_data_shape = [200]
def get_audio_data():
out = [np.random.ranf(size=test_audio_data_shape).astype(dtype=np.float32) for _ in
range(batch_size)]
return out
def test_preemphasis_filter_cpu():
check_single_input(fn.preemphasis_filter, get_data=get_audio_data, input_layout=None)
def test_power_spectrum_cpu():
check_single_input(fn.power_spectrum, get_data=get_audio_data, input_layout=None)
def test_spectrogram_cpu():
check_single_input(fn.spectrogram, get_data=get_audio_data, input_layout=None, nfft=60,
window_length=50, window_step=25)
def test_mel_filter_bank_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
data = fn.external_source(source=get_audio_data)
spectrum = fn.spectrogram(data, nfft=60, window_length=50, window_step=25)
processed = fn.mel_filter_bank(spectrum)
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
def test_to_decibels_cpu():
check_single_input(fn.to_decibels, get_data=get_audio_data, input_layout=None)
def test_audio_resample():
check_single_input(fn.audio_resample, get_data=get_audio_data, input_layout=None,
scale=1.25)
def test_mfcc_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
data = fn.external_source(source=get_audio_data)
spectrum = fn.spectrogram(data, nfft=60, window_length=50, window_step=25)
mel = fn.mel_filter_bank(spectrum)
dec = fn.to_decibels(mel)
processed = fn.mfcc(dec)
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
def test_fast_resize_crop_mirror_cpu():
check_single_input(fn.fast_resize_crop_mirror, crop=[5, 5], resize_shorter=10)
def test_resize_crop_mirror_cpu():
check_single_input(fn.resize_crop_mirror, crop=[5, 5], resize_shorter=10)
def test_normal_distribution_cpu():
check_no_input(fn.random.normal, shape=[5, 5])
def test_one_hot_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
test_data_shape = [200]
def get_data():
out = [np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8) for _ in
range(batch_size)]
return out
data = fn.external_source(source=get_data)
processed = fn.one_hot(data, num_classes=256)
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
def test_transpose_cpu():
check_single_input(fn.transpose, perm=[2, 0, 1])
def test_audio_decoder_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
input, _ = fn.readers.file(files=audio_files, shard_id=0, num_shards=1)
decoded, _ = fn.decoders.audio(input)
pipe.set_outputs(decoded)
pipe.build()
for _ in range(3):
pipe.run()
def test_coord_flip_cpu():
test_data_shape = [200, 2]
def get_data():
out = [(np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8) / 255).astype(
dtype=np.float32) for _ in range(batch_size)]
return out
check_single_input(fn.coord_flip, get_data=get_data, input_layout=None)
def test_bb_flip_cpu():
test_data_shape = [200, 4]
def get_data():
out = [(np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8) / 255).astype(
dtype=np.float32) for _ in range(batch_size)]
return out
check_single_input(fn.bb_flip, get_data=get_data, input_layout=None)
def test_warp_affine_cpu():
warp_matrix = (0.1, 0.9, 10, 0.8, -0.2, -20)
check_single_input(fn.warp_affine, matrix=warp_matrix)
def test_normalize_cpu():
check_single_input(fn.normalize, batch=True)
def test_lookup_table_cpu():
test_data_shape = [100]
def get_data():
out = [np.random.randint(0, 5, size=test_data_shape, dtype=np.uint8) for _ in
range(batch_size)]
return out
check_single_input(fn.lookup_table, keys=[1, 3], values=[10, 50], get_data=get_data,
input_layout=None)
def test_slice_cpu():
anch_shape = [2]
def get_anchors():
out = [(np.random.randint(1, 256, size=anch_shape, dtype=np.uint8) / 255).astype(
dtype=np.float32) for _ in range(batch_size)]
return out
def get_shape():
out = [(np.random.randint(1, 256, size=anch_shape, dtype=np.uint8) / 255).astype(
dtype=np.float32) for _ in range(batch_size)]
return out
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
data = fn.external_source(source=get_data, layout="HWC")
anchors = fn.external_source(source=get_anchors)
shape = fn.external_source(source=get_shape)
processed = fn.slice(data, anchors, shape, out_of_bounds_policy="pad")
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
@nottest
def _test_image_decoder_slice_cpu(decoder_type):
anch_shape = [2]
def get_anchors():
out = [(np.random.randint(1, 128, size=anch_shape, dtype=np.uint8) / 255).astype(
dtype=np.float32) for _ in range(batch_size)]
return out
def get_shape():
out = [(np.random.randint(1, 128, size=anch_shape, dtype=np.uint8) / 255).astype(
dtype=np.float32) for _ in range(batch_size)]
return out
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
input, _ = fn.readers.file(file_root=images_dir, shard_id=0, num_shards=1)
anchors = fn.external_source(source=get_anchors)
shape = fn.external_source(source=get_shape)
processed = decoder_type(input, anchors, shape)
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
def test_image_decoder_slice_cpu():
_test_image_decoder_slice_cpu(fn.decoders.image_slice)
def test_experimental_image_decoder_slice_cpu():
_test_image_decoder_slice_cpu(fn.experimental.decoders.image_slice)
def test_pad_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
test_data_shape = [5, 4, 3]
def get_data():
out = [np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8) for _ in
range(batch_size)]
return out
data = fn.external_source(source=get_data, layout="HWC")
processed = fn.pad(data, fill_value=-1, axes=(0,), shape=(10,))
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
def test_mxnet_reader_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None) # noqa: F841
out, _ = fn.readers.mxnet(path=os.path.join(recordio_dir, "train.rec"),
index_path=os.path.join(recordio_dir, "train.idx"), shard_id=0,
num_shards=1)
check_no_input(fn.readers.mxnet, path=os.path.join(recordio_dir, "train.rec"),
index_path=os.path.join(recordio_dir, "train.idx"), shard_id=0, num_shards=1)
def test_tfrecord_reader_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
tfrecord = sorted(glob.glob(os.path.join(tfrecord_dir, '*[!i][!d][!x]')))
tfrecord_idx = sorted(glob.glob(os.path.join(tfrecord_dir, '*idx')))
input = fn.readers.tfrecord(path=tfrecord, index_path=tfrecord_idx, shard_id=0, num_shards=1,
features={
"image/encoded": tfrec.FixedLenFeature((), tfrec.string, ""),
"image/class/label": tfrec.FixedLenFeature([1], tfrec.int64, -1)
})
out = input["image/encoded"]
pipe.set_outputs(out)
pipe.build()
for _ in range(3):
pipe.run()
def test_webdataset_reader_cpu():
webdataset = os.path.join(webdataset_dir, 'MNIST', 'devel-0.tar')
webdataset_idx = generate_temp_wds_index(webdataset)
check_no_input(fn.readers.webdataset, paths=webdataset, index_paths=webdataset_idx.name,
ext=["jpg", "cls"], shard_id=0, num_shards=1)
def test_coco_reader_cpu():
check_no_input(fn.readers.coco, file_root=coco_dir, annotations_file=coco_annotation,
shard_id=0, num_shards=1)
def test_caffe_reader_cpu():
check_no_input(fn.readers.caffe, path=caffe_dir, shard_id=0, num_shards=1)
def test_caffe2_reader_cpu():
check_no_input(fn.readers.caffe2, path=caffe2_dir, shard_id=0, num_shards=1)
def test_nemo_asr_reader_cpu():
tmp_dir, nemo_asr_manifest = setup_test_nemo_asr_reader_cpu()
with tmp_dir:
check_no_input(fn.readers.nemo_asr, manifest_filepaths=[nemo_asr_manifest],
dtype=types.INT16, downmix=False, read_sample_rate=True, read_text=True,
seed=1234)
def test_video_reader():
check_no_input(fn.experimental.readers.video, filenames=video_files, labels=[0, 1],
sequence_length=10)
def test_copy_cpu():
check_single_input(fn.copy)
def test_element_extract_cpu():
check_single_input(fn.element_extract, element_map=[0, 3], input_layout=None)
def test_bbox_paste_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
test_data_shape = [200, 4]
def get_data():
out = [(np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8) / 255).astype(
dtype=np.float32) for _ in range(batch_size)]
return out
data = fn.external_source(source=get_data)
paste_posx = fn.random.uniform(range=(0, 1))
paste_posy = fn.random.uniform(range=(0, 1))
paste_ratio = fn.random.uniform(range=(1, 2))
processed = fn.bbox_paste(data, paste_x=paste_posx, paste_y=paste_posy, ratio=paste_ratio)
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
def test_random_bbox_crop_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
test_box_shape = [200, 4]
def get_boxes():
out = [(np.random.randint(0, 255, size=test_box_shape, dtype=np.uint8) / 255).astype(
dtype=np.float32) for _ in range(batch_size)]
return out
test_lables_shape = [200, 1]
def get_lables():
out = [np.random.randint(0, 255, size=test_lables_shape, dtype=np.int32) for _ in
range(batch_size)]
return out
boxes = fn.external_source(source=get_boxes)
lables = fn.external_source(source=get_lables)
processed, _, _, _ = fn.random_bbox_crop(boxes, lables, aspect_ratio=[0.5, 2.0],
thresholds=[0.1, 0.3, 0.5], scaling=[0.8, 1.0],
bbox_layout="xyXY")
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
def test_ssd_random_crop_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
test_box_shape = [200, 4]
def get_boxes():
out = [(np.random.randint(0, 255, size=test_box_shape, dtype=np.uint8) / 255).astype(
dtype=np.float32) for _ in range(batch_size)]
return out
test_lables_shape = [200]
def get_lables():
out = [np.random.randint(0, 255, size=test_lables_shape, dtype=np.int32) for _ in
range(batch_size)]
return out
data = fn.external_source(source=get_data)
boxes = fn.external_source(source=get_boxes)
lables = fn.external_source(source=get_lables)
processed, _, _ = fn.ssd_random_crop(data, boxes, lables)
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
def test_sequence_rearrange_cpu():
test_data_shape = [5, 10, 20, 3]
def get_data():
out = [np.random.randint(0, 255, size=test_data_shape, dtype=np.uint8) for _ in
range(batch_size)]
return out
check_single_input(fn.sequence_rearrange, new_order=[0, 4, 1, 3, 2], get_data=get_data,
input_layout="FHWC")
def test_box_encoder_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
test_box_shape = [20, 4]
def get_boxes():
out = [(np.random.randint(0, 255, size=test_box_shape, dtype=np.uint8) / 255).astype(
dtype=np.float32) for _ in range(batch_size)]
return out
test_lables_shape = [20, 1]
def get_labels():
out = [np.random.randint(0, 255, size=test_lables_shape, dtype=np.int32) for _ in
range(batch_size)]
return out
boxes = fn.external_source(source=get_boxes)
labels = fn.external_source(source=get_labels)
processed, _ = fn.box_encoder(boxes, labels, anchors=coco_anchors())
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
def test_numpy_reader_cpu():
with setup_test_numpy_reader_cpu() as test_data_root:
check_no_input(fn.readers.numpy, file_root=test_data_root)
@attr('pytorch')
def test_python_function_cpu():
from PIL import Image
def resize(image):
return np.array(Image.fromarray(image).resize((50, 10)))
pipe = Pipeline( # noqa: F841
batch_size=batch_size, num_threads=4, device_id=None, exec_async=False,
exec_pipelined=False)
check_single_input(fn.python_function, function=resize, exec_async=False, exec_pipelined=False)
def test_constant_cpu():
check_no_input(fn.constant, fdata=(1.25, 2.5, 3))
def test_dump_image_cpu():
check_single_input(fn.dump_image)
def test_sequence_reader_cpu():
check_no_input(fn.readers.sequence, file_root=sequence_dir, sequence_length=2, shard_id=0,
num_shards=1)
def test_affine_translate_cpu():
check_no_input(fn.transforms.translation, offset=(2, 3))
def test_affine_scale_cpu():
check_no_input(fn.transforms.scale, scale=(2, 3))
def test_affine_rotate_cpu():
check_no_input(fn.transforms.rotation, angle=30.0)
def test_affine_shear_cpu():
check_no_input(fn.transforms.shear, shear=(2., 1.))
def test_affine_crop_cpu():
check_no_input(fn.transforms.crop, from_start=(0., 1.), from_end=(1., 1.), to_start=(0.2, 0.3),
to_end=(0.8, 0.5))
def test_combine_transforms_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
with pipe:
t = fn.transforms.translation(offset=(1, 2))
r = fn.transforms.rotation(angle=30.0)
s = fn.transforms.scale(scale=(2, 3))
out = fn.transforms.combine(t, r, s)
pipe.set_outputs(out)
pipe.build()
for _ in range(3):
pipe.run()
def test_reduce_min_cpu():
check_single_input(fn.reductions.min)
def test_reduce_max_cpu():
check_single_input(fn.reductions.max)
def test_reduce_sum_cpu():
check_single_input(fn.reductions.sum)
def test_segmentation_select_masks():
def get_data_source(*args, **kwargs):
return lambda: make_batch_select_masks(*args, **kwargs)
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None, seed=1234)
with pipe:
polygons, vertices, selected_masks = fn.external_source(
num_outputs=3, device='cpu',
source=get_data_source(batch_size, vertex_ndim=2, npolygons_range=(1, 5),
nvertices_range=(3, 10)))
out_polygons, out_vertices = fn.segmentation.select_masks(
selected_masks, polygons, vertices, reindex_masks=False)
pipe.set_outputs(polygons, vertices, selected_masks, out_polygons, out_vertices)
pipe.build()
for _ in range(3):
pipe.run()
def test_reduce_mean_cpu():
check_single_input(fn.reductions.mean)
def test_reduce_mean_square_cpu():
check_single_input(fn.reductions.mean_square)
def test_reduce_root_mean_square_cpu():
check_single_input(fn.reductions.rms)
def test_reduce_std_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
data = fn.external_source(source=get_data)
mean = fn.reductions.mean(data)
reduced = fn.reductions.std_dev(data, mean)
pipe.set_outputs(reduced)
pipe.build()
for _ in range(3):
pipe.run()
def test_reduce_variance_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
data = fn.external_source(source=get_data)
mean = fn.reductions.mean(data)
reduced = fn.reductions.variance(data, mean)
pipe.set_outputs(reduced)
def test_arithm_ops_cpu():
pipe = pipeline_arithm_ops_cpu(get_data, batch_size=batch_size, num_threads=4, device_id=None)
pipe.build()
for _ in range(3):
pipe.run()
def test_arithm_ops_cpu_gpu():
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
data = fn.external_source(source=get_data, layout="HWC")
processed = [data * data.gpu(),
data + data.gpu(),
data - data.gpu(),
data / data.gpu(),
data // data.gpu(),
data ** data.gpu(),
data == data.gpu(),
data != data.gpu(),
data < data.gpu(),
data <= data.gpu(),
data > data.gpu(),
data >= data.gpu(),
data & data.gpu(),
data | data.gpu(),
data ^ data.gpu()]
pipe.set_outputs(*processed)
assert_raises(RuntimeError, pipe.build,
glob="Cannot add a GPU operator ArithmeticGenericOp, device_id should not be equal CPU_ONLY_DEVICE_ID.") # noqa: E501
@attr('pytorch')
def test_pytorch_plugin_cpu():
import nvidia.dali.plugin.pytorch as pytorch
pipe = Pipeline(batch_size=batch_size, num_threads=3, device_id=None)
outs = fn.external_source(source=get_data, layout="HWC")
pipe.set_outputs(outs)
pii = pytorch.DALIGenericIterator([pipe], ["data"]) # noqa: F841
def test_random_mask_pixel_cpu():
check_single_input(fn.segmentation.random_mask_pixel)
def test_cat_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=3, device_id=None)
data = fn.external_source(source=get_data, layout="HWC")
data2 = fn.external_source(source=get_data, layout="HWC")
data3 = fn.external_source(source=get_data, layout="HWC")
pixel_pos = fn.cat(data, data2, data3)
pipe.set_outputs(pixel_pos)
pipe.build()
for _ in range(3):
pipe.run()
def test_stack_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=3, device_id=None)
data = fn.external_source(source=get_data, layout="HWC")
data2 = fn.external_source(source=get_data, layout="HWC")
data3 = fn.external_source(source=get_data, layout="HWC")
pixel_pos = fn.stack(data, data2, data3)
pipe.set_outputs(pixel_pos)
pipe.build()
for _ in range(3):
pipe.run()
def test_batch_permute_cpu():
pipe = Pipeline(batch_size=batch_size, num_threads=3, device_id=None)
data = fn.external_source(source=get_data, layout="HWC")
perm = fn.batch_permutation(seed=420)
processed = fn.permute_batch(data, indices=perm)
pipe.set_outputs(processed)
pipe.build()
for _ in range(3):
pipe.run()
def test_squeeze_cpu():
test_data_shape = [10, 20, 3, 1, 1]
def get_data():
out = [np.zeros(shape=test_data_shape, dtype=np.uint8) for _ in range(batch_size)]
return out
check_single_input(fn.squeeze, axis_names="YZ", get_data=get_data, input_layout="HWCYZ")
@nottest
def _test_peek_image_shape_cpu(op):
pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=None)
input, _ = fn.readers.file(file_root=images_dir, shard_id=0, num_shards=1)
shapes = op(input)
pipe.set_outputs(shapes)
pipe.build()
for _ in range(3):
pipe.run()
def test_peek_image_shape_cpu():
_test_peek_image_shape_cpu(fn.peek_image_shape)
def test_experimental_peek_image_shape_cpu():
_test_peek_image_shape_cpu(fn.experimental.peek_image_shape)
def test_separated_exec_setup():
batch_size = 128
pipe = Pipeline(batch_size=batch_size, num_threads=3, device_id=None,
prefetch_queue_depth={"cpu_size": 5, "gpu_size": 3})
inputs, labels = fn.readers.caffe(path=caffe_dir, shard_id=0, num_shards=1)
images = fn.decoders.image(inputs, output_type=types.RGB)
images = fn.resize(images, resize_x=224, resize_y=224)
images_cpu = fn.dump_image(images, suffix="cpu")
pipe.set_outputs(images, images_cpu)
pipe.build()
out = pipe.run()
assert out[0].is_dense_tensor()
assert out[1].is_dense_tensor()
assert out[0].as_tensor().shape() == out[1].as_tensor().shape()
a_raw = out[0]
a_cpu = out[1]
for i in range(batch_size):
t_raw = a_raw.at(i)
t_cpu = a_cpu.at(i)
assert np.sum(np.abs(t_cpu - t_raw)) == 0
def test_tensor_subscript():
pipe = Pipeline(batch_size=3, num_threads=3, device_id=None)
input = fn.external_source(source=get_data)
pipe.set_outputs(input[1:, :-1, 1])
pipe.build()
out, = pipe.run()
assert out.at(0).shape == np.zeros(test_data_shape)[1:, :-1, 1].shape
def test_subscript_dim_check():
check_single_input(fn.subscript_dim_check, num_subscripts=3)
def test_get_property():
@pipeline_def
def file_properties(files):
read, _ = fn.readers.file(files=files)
return fn.get_property(read, key="source_info")
root_path = os.path.join(data_root, 'db', 'single', 'png', '0')
files = [os.path.join(root_path, i) for i in os.listdir(root_path)]
p = file_properties(files, batch_size=8, num_threads=4, device_id=None)
p.build()
output = p.run()
for out in output:
for source_info, ref in zip(out, files):
assert np.array(source_info).tobytes().decode() == ref
def test_video_decoder():
def get_data():
filename = os.path.join(get_dali_extra_path(), 'db', 'video', 'cfr', 'test_1.mp4')
return np.fromfile(filename, dtype=np.uint8)
check_single_input(fn.experimental.decoders.video, "", get_data, batch=False)
def test_tensor_list_cpu():
n_ar = np.empty([2, 3])
d_ten = tensors.TensorCPU(n_ar)
d_tl = tensors.TensorListCPU([d_ten])
del d_tl
def test_video_input():
@pipeline_def(batch_size=3, num_threads=1, device_id=None)
def video_input_pipeline(input_name):
vid = fn.experimental.inputs.video(name=input_name, sequence_length=7, blocking=False)
return vid
input_name = "VIDEO_INPUT"
n_iterations = 3
test_data = np.fromfile(video_files[0], dtype=np.uint8)
p = video_input_pipeline(input_name)
p.build()
p.feed_input(input_name, [test_data])
for _ in range(n_iterations):
p.run()
def test_conditional():
@experimental_pipeline_def(enable_conditionals=True)
def conditional_pipeline():
true = types.Constant(np.array(True), device="cpu")
false = types.Constant(np.array(False), device="cpu")
if true and true or not false:
output = types.Constant(np.array([42]), device="cpu")
else:
output = types.Constant(np.array([0]), device="cpu")
return output
cond_pipe = conditional_pipeline(batch_size=5, num_threads=1, device_id=None)
cond_pipe.build()
cond_pipe.run()
@pipeline_def
def explicit_conditional_ops_pipeline():
value = types.Constant(np.array([42]), device="cpu")
pred = fn.random.coin_flip(dtype=types.DALIDataType.BOOL)
pred_validated = fn._conditional.validate_logical(pred, expression_name="or",
expression_side="right")
true, false = fn._conditional.split(value, predicate=pred)
true = true + 10
merged = fn._conditional.merge(true, false, predicate=pred)
negated = fn._conditional.not_(pred)
return merged, negated, pred_validated
pipe = explicit_conditional_ops_pipeline(batch_size=5, num_threads=1, device_id=None)
pipe.build()
pipe.run()
tested_methods = [
"_conditional.merge",
"_conditional.split",
"_conditional.not_",
"_conditional.validate_logical",
"audio_decoder",
"image_decoder",
"image_decoder_slice",
"image_decoder_crop",
"image_decoder_random_crop",
"decoders.image",
"decoders.image_crop",
"decoders.image_slice",
"decoders.image_random_crop",
"experimental.decoders.image",
"experimental.decoders.image_crop",
"experimental.decoders.image_slice",
"experimental.decoders.image_random_crop",
"experimental.inputs.video",
"decoders.audio",
"external_source",
"stack",
"reductions.variance",
"reductions.std_dev",
"reductions.rms",
"reductions.mean",
"reductions.mean_square",
"reductions.max",
"reductions.min",
"reductions.sum",
"transforms.translation",
"transforms.rotation",
"transforms.scale",
"transforms.combine",
"transforms.shear",
"transforms.crop",
"transform_translation",
"crop",
"constant",
"dump_image",
"get_property",
"numpy_reader",
"tfrecord_reader",
"file_reader",
"sequence_reader",
"mxnet_reader",
"caffe_reader",
"caffe2_reader",
"coco_reader",
"nemo_asr_reader",
"readers.nemo_asr",
"readers.file",
"readers.sequence",
"readers.tfrecord",
"readers.mxnet",
"readers.caffe",
"readers.caffe2",
"readers.coco",
"readers.numpy",
"readers.webdataset",
"experimental.readers.video",
"coin_flip",
"uniform",
"random.uniform",
"random.coin_flip",
"random.normal",
"random_bbox_crop",
"python_function",
"rotate",
"brightness_contrast",
"hue",
"brightness",
"contrast",
"hsv",
"color_twist",
"saturation",
"shapes",
"crop",
"color_space_conversion",
"cast",
"cast_like",
"resize",
"experimental.tensor_resize",
"gaussian_blur",
"laplacian",
"crop_mirror_normalize",
"flip",
"jpeg_compression_distortion",
"noise.shot",
"noise.gaussian",
"noise.salt_and_pepper",
"reshape",
"per_frame",
"reinterpret",
"water",
"sphere",
"erase",
"random_resized_crop",
"ssd_random_crop",
"bbox_paste",
"coord_flip",
"cat",
"bb_flip",
"warp_affine",
"normalize",
"pad",
"preemphasis_filter",
"power_spectrum",
"spectrogram",
"to_decibels",
"sequence_rearrange",
"normal_distribution",
"mel_filter_bank",
"nonsilent_region",
"one_hot",
"copy",
"resize_crop_mirror",
"fast_resize_crop_mirror",
"segmentation.select_masks",
"slice",
"segmentation.random_mask_pixel",
"transpose",
"mfcc",
"lookup_table",
"element_extract",
"arithmetic_generic_op",
"box_encoder",
"permute_batch",
"batch_permutation",
"squeeze",
"peek_image_shape",
"experimental.peek_image_shape",
"expand_dims",
"coord_transform",
"grid_mask",
"multi_paste",
"roi_random_crop",
"segmentation.random_object_bbox",
"tensor_subscript",
"subscript_dim_check",
"math.ceil",
"math.clamp",
"math.tanh",
"math.tan",
"math.log2",
"math.atanh",
"math.atan",
"math.atan2",
"math.sin",
"math.cos",
"math.asinh",
"math.abs",
"math.sqrt",
"math.exp",
"math.acos",
"math.log",
"math.fabs",
"math.sinh",
"math.rsqrt",
"math.asin",
"math.floor",
"math.cosh",
"math.log10",
"math.max",
"math.cbrt",
"math.pow",
"math.fpow",
"math.acosh",
"math.min",
"numba.fn.experimental.numba_function",
"dl_tensor_python_function",
"audio_resample",
"experimental.decoders.video"
]
excluded_methods = [
"hidden.*",
"_conditional.hidden.*",
"jitter", # not supported for CPU
"video_reader", # not supported for CPU
"video_reader_resize", # not supported for CPU
"readers.video", # not supported for CPU
"readers.video_resize", # not supported for CPU
"optical_flow", # not supported for CPU
"paste", # not supported for CPU
"experimental.audio_resample", # Alias of audio_resample (already tested)
"experimental.debayer", # not supported for CPU
"experimental.equalize", # not supported for CPU
"experimental.filter", # not supported for CPU
"experimental.inflate", # not supported for CPU
"experimental.remap", # operator is GPU-only
"experimental.readers.fits", # lacking test files in DALI_EXTRA
"experimental.median_blur" # not supported for CPU
]
def test_coverage():
methods = module_functions(fn, remove_prefix="nvidia.dali.fn",
allowed_private_modules=["_conditional"])
methods += module_functions(dmath, remove_prefix="nvidia.dali")
exclude = "|".join([
"(^" + x.replace(".", r"\.").replace("*", ".*").replace("?", ".") + "$)"
for x in excluded_methods
])
exclude = re.compile(exclude)
methods = [x for x in methods if not exclude.match(x)]
# we are fine with covering more we can easily list, like numba
assert set(methods).difference(set(tested_methods)) == set(), \
"Test doesn't cover:\n {}".format(set(methods) - set(tested_methods))
|
DALI-main
|
dali/test/python/test_dali_cpu_only.py
|
# Copyright (c) 2019-2022, NVIDIA CORPORATION & AFFILIATES. 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 nvidia.dali.pipeline import Pipeline
import nvidia.dali.ops as ops
import nvidia.dali.types as types
from numpy.testing import assert_array_equal
from test_utils import get_dali_extra_path
seed = 1549361629
img_root = get_dali_extra_path()
image_dir = img_root + "/db/single/jpeg"
batch_size = 20
def compare(tl1, tl2):
tl1_cpu = tl1.as_cpu()
tl2_cpu = tl2.as_cpu()
assert len(tl1_cpu) == len(tl2_cpu)
for i in range(0, len(tl1_cpu)):
assert_array_equal(tl1_cpu.at(i), tl2_cpu.at(i), "cached and non-cached images differ")
class HybridDecoderPipeline(Pipeline):
def __init__(self, batch_size, num_threads, device_id, cache_size):
super(HybridDecoderPipeline, self).__init__(batch_size, num_threads, device_id, seed=seed)
self.input = ops.readers.File(file_root=image_dir)
policy = None
if cache_size > 0:
policy = "threshold"
self.decode = ops.decoders.Image(device='mixed', output_type=types.RGB, cache_debug=False,
cache_size=cache_size, cache_type=policy,
cache_batch_copy=True)
def define_graph(self):
jpegs, labels = self.input(name="Reader")
images = self.decode(jpegs)
return (images, labels)
def test_nvjpeg_cached():
ref_pipe = HybridDecoderPipeline(batch_size, 1, 0, 0)
ref_pipe.build()
cached_pipe = HybridDecoderPipeline(batch_size, 1, 0, 100)
cached_pipe.build()
epoch_size = ref_pipe.epoch_size("Reader")
for i in range(0, (2 * epoch_size + batch_size - 1) // batch_size):
print("Batch %d-%d / %d" % (i * batch_size, (i + 1) * batch_size, epoch_size))
ref_images, _ = ref_pipe.run()
out_images, _ = cached_pipe.run()
compare(ref_images, out_images)
ref_images, _ = ref_pipe.run()
out_images, _ = cached_pipe.run()
compare(ref_images, out_images)
ref_images, _ = ref_pipe.run()
out_images, _ = cached_pipe.run()
compare(ref_images, out_images)
def main():
test_nvjpeg_cached()
if __name__ == '__main__':
main()
|
DALI-main
|
dali/test/python/test_nvjpeg_cache.py
|
#!/usr/bin/python3
# Copyright (c) 2020-2021, NVIDIA CORPORATION & AFFILIATES. 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 time
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim
import torchvision.models as models
from nvidia.dali.plugin.base_iterator import LastBatchPolicy
from nvidia.dali.plugin.pytorch import DALIClassificationIterator
from torch.nn.parallel import DistributedDataParallel as DDP
from test_RN50_external_source_parallel_utils import (
parse_test_arguments, external_source_parallel_pipeline, external_source_pipeline,
file_reader_pipeline, get_pipe_factories)
from test_utils import AverageMeter
# This test requires significant amount of shared memory to be able to pass
# the batches between worker processes and the main process. If running in docker
# make sure that -shm-size is big enough.
# We place the parallel External Source as first as we need to fork before we call anything
# from cuda.
TEST_PIPES_FACTORIES = [
external_source_parallel_pipeline,
file_reader_pipeline,
external_source_pipeline,
]
def reduce_tensor(tensor):
rt = tensor.clone()
dist.all_reduce(rt, op=dist.reduce_op.SUM)
rt /= args.world_size
return rt
def training_test(args):
"""Run ExternalSource pipelines along RN18 network. Based on simplified RN50 Pytorch sample. """
args.distributed = False
args.world_size = 1
args.gpu = 0
args.distributed_initialized = False
if 'WORLD_SIZE' in os.environ:
args.distributed = int(os.environ['WORLD_SIZE']) > 1
test_pipe_factories = get_pipe_factories(args.test_pipes, external_source_parallel_pipeline,
file_reader_pipeline, external_source_pipeline)
for pipe_factory in test_pipe_factories:
pipe = pipe_factory(
batch_size=args.batch_size,
num_threads=args.workers,
device_id=args.local_rank,
data_path=args.data_path,
prefetch_queue_depth=args.prefetch,
reader_queue_depth=args.reader_queue_depth,
py_start_method=args.worker_init,
py_num_workers=args.py_workers,
source_mode=args.source_mode,
read_encoded=args.dali_decode, )
# Start the pipeline workers first, before any CUDA call. The first pipeline factory
# is the one with Parallel External Source that needs that.
pipe.start_py_workers()
if args.distributed and not args.distributed_initialized:
args.gpu = args.local_rank
torch.cuda.set_device(args.gpu)
torch.distributed.init_process_group(backend='nccl', init_method='env://')
args.world_size = torch.distributed.get_world_size()
args.distributed_initialized = True
pipe.build()
model = models.resnet18().cuda()
if args.distributed:
model = DDP(model, device_ids=[args.gpu], output_device=args.gpu)
model.train()
loss_fun = nn.CrossEntropyLoss().cuda()
lr = 0.1 * args.batch_size / 256
optimizer = torch.optim.SGD(model.parameters(), lr, momentum=0.9)
samples_no = pipe.epoch_size("Reader")
if args.benchmark_iters is None:
expected_iters = samples_no // args.batch_size + (samples_no % args.batch_size != 0)
else:
expected_iters = args.benchmark_iters
if pipe_factory == file_reader_pipeline:
iterator = DALIClassificationIterator([pipe], reader_name="Reader",
last_batch_policy=LastBatchPolicy.DROP,
auto_reset=True)
else:
iterator = DALIClassificationIterator([pipe], size=samples_no * args.world_size,
auto_reset=True)
if args.local_rank == 0:
print("RUN {}".format(pipe_factory.__name__))
losses = AverageMeter()
for i in range(args.epochs):
if args.local_rank == 0:
if i == 0:
print("Warm up")
else:
print("Test run " + str(i))
end = time.time()
data_time = AverageMeter()
for j, data in enumerate(iterator):
inputs = data[0]["data"]
target = data[0]["label"].squeeze(-1).cuda().long()
outputs = model(inputs)
loss = loss_fun(outputs, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if j % 50 == 0 and j != 0:
if args.distributed:
reduced_loss = reduce_tensor(loss.data)
else:
reduced_loss = loss.data
if args.local_rank == 0:
print(reduced_loss.item())
losses.update(reduced_loss.item())
torch.cuda.synchronize()
data_time.update((time.time() - end) / 50)
end = time.time()
if args.local_rank == 0:
template_string = "{} {}/ {}, avg time: {} [s], worst time: {} [s], " \
"speed: {} [img/s], loss: {}, loss_avg: {}"
print(
template_string.format(
pipe_factory.__name__,
j,
expected_iters,
data_time.avg,
data_time.max_val,
args.batch_size * args.world_size / data_time.avg,
reduced_loss.item(),
losses.avg
))
if j >= expected_iters:
break
print("OK {}".format(pipe_factory.__name__))
if __name__ == "__main__":
args = parse_test_arguments(True)
training_test(args)
|
DALI-main
|
dali/test/python/test_RN50_external_source_parallel_train_ddp.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.