id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
25,599 | import torch
import numpy as np
from PIL import Image
from OnBoard import SummaryCollector
The provided code snippet includes necessary dependencies for implementing the `demo_add_graph_wego_torch` function. Write a Python function `def demo_add_graph_wego_torch(logdir)` to solve the following problem:
OnBoard API Dem... | OnBoard API Demo for WeGO-Torch, introduction of how to use OnBoard when you run a model. It would generate an event file in `logdir` by your defination, you can use exactly the same command of TensorBoard to obtain the visualize results: `tensorboard --logdir=same/as/logdir`. |
25,600 | import torch
import numpy as np
from PIL import Image
from OnBoard import SummaryCollector
The provided code snippet includes necessary dependencies for implementing the `demo_add_graph_torchvision` function. Write a Python function `def demo_add_graph_torchvision(logdir)` to solve the following problem:
OnBoard API D... | OnBoard API Demo for TorchVision models, samely as the usage for WeGO model. OnBoard is not depend on WeGO, you can use it when you run the original PyTorch models. The usage of them are exactly the same. |
25,601 | import torch
import numpy as np
from PIL import Image
from OnBoard import SummaryCollector
The provided code snippet includes necessary dependencies for implementing the `demo_add_text` function. Write a Python function `def demo_add_text(logdir)` to solve the following problem:
OnBoard API Demo for adding images to v... | OnBoard API Demo for adding images to visualize in TensorBoard. |
25,602 | import torch
import numpy as np
from PIL import Image
from OnBoard import SummaryCollector
The provided code snippet includes necessary dependencies for implementing the `demo_add_image` function. Write a Python function `def demo_add_image(logdir)` to solve the following problem:
OnBoard API Demo for adding images to... | OnBoard API Demo for adding images to visualize in TensorBoard. |
25,603 | import os
import re
import sys
import argparse
import time
import pdb
import random
from pytorch_nndct.apis import torch_quantizer, dump_xmodel
import torch
import torchvision
import torchvision.transforms as transforms
from ofa.model_zoo import ofa_net
import pickle
from tqdm import tqdm
device = torch.device("cuda" i... | null |
25,604 | import os
import math
import random
import numpy as np
import torch
import cv2
import os
def uint2tensor3(img):
if img.ndim == 2:
img = np.expand_dims(img, axis=2)
return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().div(255.) | null |
25,605 | import os
import math
import random
import numpy as np
import torch
import cv2
import os
def tensor2uint(img):
img = img.data.squeeze().float().clamp_(0, 1).cpu().numpy()
if img.ndim == 3:
img = np.transpose(img, (1, 2, 0))
return np.uint8((img*255.0).round()) | null |
25,606 | import os
import math
import random
import numpy as np
import torch
import cv2
import os
def imsave(img, img_path):
img = np.squeeze(img)
if img.ndim == 3:
img = img[:, :, [2, 1, 0]]
cv2.imwrite(img_path, img) | null |
25,607 | import os
import os.path
import time
import threading
import argparse
import numpy as np
import torch
import cv2
import torch.utils.data as udata
import wego_torch
from skimage.metrics import peak_signal_noise_ratio
from tqdm import tqdm
import utils
def read_image(image_path):
img = cv2.imread(image_path)
# c... | null |
25,608 | import os
import os.path
import time
import threading
import argparse
import numpy as np
import torch
import cv2
import torch.utils.data as udata
import wego_torch
from skimage.metrics import peak_signal_noise_ratio
from tqdm import tqdm
import utils
def run(model, images, n_threads):
thread_list = []
for t_id ... | null |
25,609 | import os
import sys
import threading
import argparse
import time
import random
import torch
import wego_torch
import torchvision
import validators
import requests
from PIL import Image
from typing import Tuple
import torchvision.transforms as transforms
from tqdm import tqdm
from config import load_config
from OnBoard... | null |
25,610 | import os
import sys
import threading
import argparse
import time
import random
import torch
import wego_torch
import torchvision
import validators
import requests
from PIL import Image
from typing import Tuple
import torchvision.transforms as transforms
from tqdm import tqdm
from config import load_config
from OnBoard... | null |
25,611 | import os
import sys
import threading
import argparse
import time
import random
import torch
import wego_torch
import torchvision
import validators
import requests
from PIL import Image
from typing import Tuple
import torchvision.transforms as transforms
from tqdm import tqdm
from config import load_config
from OnBoard... | null |
25,612 | import os
import sys
import threading
import argparse
import time
import random
import torch
import wego_torch
import torchvision
import validators
import requests
from PIL import Image
from typing import Tuple
import torchvision.transforms as transforms
from tqdm import tqdm
from config import load_config
from OnBoard... | null |
25,613 | import yaml
def load_config(config_file):
with open(config_file, 'r') as stream:
try:
parsed_yaml = yaml.safe_load(stream)
except yaml.YAMLError as exc:
msg = 'An error occurred during YAML parsing.'
raise ValueError(msg)
if not isinstance(parsed_yaml, d... | null |
25,614 | import os
import argparse
import threading
import math
from tqdm import tqdm
import time
import torch
import wego_torch
import torchvision
import validators
import requests
from PIL import Image
import torch.utils.data
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import cv2
from o... | null |
25,615 | import os
import argparse
import threading
import math
from tqdm import tqdm
import time
import torch
import wego_torch
import torchvision
import validators
import requests
from PIL import Image
import torch.utils.data
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import cv2
from o... | null |
25,616 | import os
import argparse
import threading
import math
from tqdm import tqdm
import time
import torch
import wego_torch
import torchvision
import validators
import requests
from PIL import Image
import torch.utils.data
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import cv2
from o... | null |
25,617 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
try:
import accimage
except ImportError:
accimage = None
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def _is_pil_image(img):
if accimage is not None:
... | null |
25,618 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
The provided code snippet inc... | Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. See ``ToTensor`` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. |
25,619 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def _is_tensor_image(img):
return torch.is_tensor(img) and img.ndimension() == 3
The provided code snippet includes... | Normalize a tensor image with mean and standard deviation. .. note:: This transform acts in-place, i.e., it mutates the input tensor. See :class:`~torchvision.transforms.Normalize` for more details. Args: tensor (Tensor): Tensor image of size (C, H, W) to be normalized. mean (sequence): Sequence of means for each chann... |
25,620 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def resize(img, size, interpolation=cv2.INTER_LINEAR):
r"""Resize the input numpy ndarray to the given size.
Arg... | null |
25,621 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
_cv2_pad_to_str = {
'constant': cv2.BORDER_CONSTANT,
'edge': cv2.BORDER_REPLICATE,
'reflect': cv2.BORDER_REF... | r"""Pad the given numpy ndarray on all sides with specified padding mode and fill value. Args: img (numpy ndarray): image to be padded. padding (int or tuple): Padding on each border. If a single int is provided this is used to pad all borders. If tuple of length 2 is provided this is the padding on left/right and top/... |
25,622 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
def resize(img, size, interpol... | Crop the given numpy ndarray and resize it to desired size. Notably used in :class:`~torchvision.transforms.RandomResizedCrop`. Args: img (numpy ndarray): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. size (sequence or int): Desi... |
25,623 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def hflip(img):
"""Horizontally flip the given numpy ndarray.
Args:
img (numpy ndarray): image to be fli... | r"""Crop the given numpy ndarray into four corners and the central crop plus the flipped version of these (horizontal flipping is used by default). .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your ``Dataset`` returns. Args: size (sequence or int): D... |
25,624 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
The provided code snippet inc... | Adjust brightness of an Image. Args: img (numpy ndarray): numpy ndarray to be adjusted. brightness_factor (float): How much to adjust the brightness. Can be any non negative number. 0 gives a black image, 1 gives the original image while 2 increases the brightness by a factor of 2. Returns: numpy ndarray: Brightness ad... |
25,625 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
The provided code snippet inc... | Adjust contrast of an mage. Args: img (numpy ndarray): numpy ndarray to be adjusted. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the original image while 2 increases the contrast by a factor of 2. Returns: numpy ndarray: Contrast adjusted... |
25,626 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
The provided code snippet inc... | Adjust color saturation of an image. Args: img (numpy ndarray): numpy ndarray to be adjusted. saturation_factor (float): How much to adjust the saturation. 0 will give a black and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2. Returns: numpy ndarray: Saturation adjuste... |
25,627 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
The provided code snippet inc... | Adjust hue of an image. The image hue is adjusted by converting the image to HSV and cyclically shifting the intensities in the hue channel (H). The image is then converted back to original image mode. `hue_factor` is the amount of shift in H channel and must be in the interval `[-0.5, 0.5]`. See `Hue`_ for more detail... |
25,628 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
The provided code snippet inc... | r"""Perform gamma correction on an image. Also known as Power Law Transform. Intensities in RGB mode are adjusted based on the following equation: .. math:: I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma} See `Gamma Correction`_ for more details. .. _Gamma Correction: http... |
25,629 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
The provided code snippet inc... | Rotate the image by angle. Args: img (numpy ndarray): numpy ndarray to be rotated. angle (float or int): In degrees degrees counter clockwise order. resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Image.BICUBIC``, optional): An optional resampling filter. See `filters`_ for more information. If omitt... |
25,630 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
def _get_affine_matrix(center,... | Apply affine transformation on the image keeping image center invariant Args: img (numpy ndarray): numpy ndarray to be transformed. angle (float or int): rotation angle in degrees between -180 and 180, clockwise direction. translate (list or tuple of integers): horizontal and vertical translations (post-rotation transl... |
25,631 | import math
import random
import torch
from PIL import Image, ImageEnhance, ImageOps
import collections
import numbers
import types
import warnings
import cv2
import numpy as np
from PIL import Image
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
The provided code snippet inc... | Convert image to grayscale version of image. Args: img (numpy ndarray): Image to be converted to grayscale. num_output_channels: int if 1 : returned image is single channel if 3 : returned image is 3 channel with r = g = b Returns: numpy ndarray: Grayscale version of the image. |
25,632 | import os
import argparse
import torch
import wego_torch
import torchvision
import validators
import requests
from PIL import Image
import torchvision.transforms as transforms
from config import load_config
def get_image_from_url(img_transforms, url=''):
# download the image from web if uri is valid.
if (valid... | null |
25,633 | import os
import argparse
import torch
import wego_torch
import torchvision
import validators
import requests
from PIL import Image
import torchvision.transforms as transforms
from config import load_config
def get_categories():
def cal_topk(output, topk):
def run_normal(img, wego_mod):
with torch.no_grad():
... | null |
25,634 | import os
import argparse
import torch
import wego_torch
import torchvision
import validators
import requests
from PIL import Image
import torchvision.transforms as transforms
from config import load_config
model_config = load_config(args.config_file)
def get_transform():
mean = model_config['preprocess']['mean']
... | null |
25,635 | import os
import argparse
import torch
import wego_torch
import torchvision
import validators
import requests
from PIL import Image
import torchvision.transforms as transforms
from config import load_config
args, _ = parser.parse_known_args()
model_config = load_config(args.config_file)
def get_wego_mod(img_transforms... | null |
25,637 | import os
import argparse
import threading
import time
from tqdm import tqdm
import torch
import wego_torch
def generate_inputs_data(batch, inputs_shapes):
inputs_data = []
for i, shape in enumerate(inputs_shapes):
data = torch.randint(1, 3, shape).to(torch.float)
batch_data = torch.cat([data f... | null |
25,638 | import os
import argparse
import threading
import time
from tqdm import tqdm
import torch
import wego_torch
def run_throughput(model, inputs_data, n_thread=1, n_of_group=1200):
threads = []
for i in range(n_thread):
tr = threading.Thread(target=run_thread, args=(model, inputs_data, i, n_of_group, n_thre... | null |
25,639 | import argparse
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tf_nndct.optimization import IterativePruningRunner
num_classes = 10
input_shape = (28, 28, 1)
def build_model(pretrained=None):
# Implementation adapted from https://keras.io/examples/vis... | null |
25,640 | import argparse
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tf_nndct.optimization import IterativePruningRunner
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("f... | null |
25,641 | import argparse
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tf_nndct.optimization import IterativePruningRunner
input_shape = (28, 28, 1)
def evaluate(model):
def prune(model, ratio):
input_spec = tf.TensorSpec((1, *input_shape), tf.float32)
runn... | null |
25,642 | import argparse
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tf_nndct.optimization import IterativePruningRunner
input_shape = (28, 28, 1)
def transform(model):
input_spec = tf.TensorSpec((1, *input_shape), tf.float32)
runner = IterativePruningRun... | null |
25,643 | import argparse
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tf_nndct.optimization import IterativePruningRunner
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-t",
"--train",
action="store_true",
... | null |
25,644 | import tensorflow as tf
from google.protobuf import text_format
from tensorflow.core.framework import graph_pb2
from tensorflow.python.framework import importer
from tensorflow.python.platform import app
from tensorflow.python.platform import gfile
from net import x_train, y_train, x_test, y_test
The provided code sni... | Parser input tensorflow graph into GraphDef proto. |
25,645 | from tensorflow.keras import backend as K
from tensorflow.keras import layers
import tensorflow as tf
x_test = x_test.astype('float32')
def build_model():
if K.image_data_format() == 'channels_first':
inputs = tf.keras.Input(shape=(1, img_rows, img_cols)) # Returns a placeholder tensor
else:
inputs = tf.ke... | null |
25,646 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
from google.protobuf import text_format
from tensorflow.core.framework import graph_pb2
from tensorflow.core.protobuf import saver_pb2
from tensorflow.core.protobuf.meta_graph_pb2 impo... | Converts all variables in a graph and checkpoint into constants. |
25,647 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
from google.protobuf import text_format
from tensorflow.core.framework import graph_pb2
from tensorflow.core.protobuf import saver_pb2
from tensorflow.core.protobuf.meta_graph_pb2 impo... | null |
25,648 | import time
import torch
from common import AverageMeter, ProgressMeter
def get_gpus(device):
return [int(i) for i in device.split(',')] | null |
25,649 | import time
import torch
from common import AverageMeter, ProgressMeter
def changeWeightKeyname_removePrefix(weights, prefix='module.'):
keys_weights = list(weights.keys())
if keys_weights[0].startswith(prefix):
for key in keys_weights:
new_key = key.split(prefix)[-1]
weights[new_key] = weights[key]... | null |
25,650 | import time
import torch
from common import AverageMeter, ProgressMeter
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions
for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True... | null |
25,651 | import time
import torch
from common import AverageMeter, ProgressMeter
def accuracy(output, target, topk=(1,)):
class AverageMeter(object):
def __init__(self, name, fmt=':f'):
def reset(self):
def update(self, val, n=1):
def __str__(self):
class ProgressMeter(object):
def __init__(self, num_... | null |
25,652 | import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
def get_dataloader(data_dir, batch_size, num_workers=48, shuffle=True, train=True, download=True)... | null |
25,653 | import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
def get_subnet_dataloader(data_dir, batch_size, subnet_len, num_workers=48, shuffle=True, train=T... | null |
25,654 | import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
def get_dataloader_ddp(data_dir, batch_size, num_workers=48, shuffle=True, train=True, download=T... | null |
25,655 | import argparse
import os
import time
import torch
from common import AverageMeter, ProgressMeter
from data import get_dataloader, get_subnet_dataloader
from net import MyNet
from utils import *
from pytorch_nndct import get_pruning_runner
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k t... | null |
25,656 | import argparse
import os
import time
import torch
from common import AverageMeter, ProgressMeter
from data import get_dataloader, get_subnet_dataloader
from net import MyNet
from utils import *
from pytorch_nndct import get_pruning_runner
def calibration_fn(model, dataloader, number_forward=100):
model.train()
pr... | null |
25,659 | import argparse
import torch
import torchvision.datasets as datasets
import torch.nn as nn
import torchvision.transforms as transforms
from pytorch_nndct import OFAPruner
def get_gpus(device):
return [int(i) for i in device.split(',')] | null |
25,660 | import argparse
import torch
import torchvision.datasets as datasets
import torch.nn as nn
import torchvision.transforms as transforms
from pytorch_nndct import OFAPruner
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=':f'):
self.name = name
... | null |
25,661 | import argparse
import torch
import torchvision.datasets as datasets
import torch.nn as nn
import torchvision.transforms as transforms
from pytorch_nndct import OFAPruner
def calibration_fn(model, train_loader, number_forward=16):
model.eval()
for n, m in model.named_modules():
if isinstance(m, torch.nn.BatchN... | null |
25,662 | import argparse
import os
import time
import torch
import torch.nn as nn
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from pytorch_nndct import OFAPruner
The provided code snippet includes necessary dependencies for implementing the `adjust_learning_rate` function. Write a Python... | Sets the learning rate to the initial LR decayed by every 2 epochs |
25,663 | import argparse
import os
import time
import torch
import torch.nn as nn
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from pytorch_nndct import OFAPruner
class AverageMeter(object):
def __init__(self, name, fmt=':f'):
def reset(self):
def update(self, val, n=1):
... | null |
25,664 | import argparse
import os
import time
import torch
import torch.nn as nn
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from pytorch_nndct import OFAPruner
def load_weights(model, model_path):
checkpoint = torch.load(model_path)
model.load_state_dict(checkpoint)
return model | null |
25,665 | import argparse
import os
import time
import torch
import torch.nn as nn
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from pytorch_nndct import OFAPruner
args, _ = parser.parse_known_args()
def train(train_loader,
model,
criterion,
optimizer,
... | null |
25,666 | import argparse
import os
import time
import torch
import torchvision.datasets as datasets
import torch.nn as nn
import torchvision.transforms as transforms
from pytorch_nndct import OFAPruner
def get_gpus(device):
return [int(i) for i in device.split(',')] | null |
25,667 | import argparse
import os
import time
import torch
import torchvision.datasets as datasets
import torch.nn as nn
import torchvision.transforms as transforms
from pytorch_nndct import OFAPruner
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=':f'):
... | null |
25,672 | import argparse
import os
import time
import torch
import torchvision.datasets as datasets
from torchvision.models.mobilenet import mobilenet_v2
import torchvision.transforms as transforms
from pytorch_nndct import OFAPruner
def get_gpus(device):
return [int(i) for i in device.split(',')] | null |
25,673 | import argparse
import os
import time
import torch
import torchvision.datasets as datasets
from torchvision.models.mobilenet import mobilenet_v2
import torchvision.transforms as transforms
from pytorch_nndct import OFAPruner
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __i... | null |
25,676 | import time
import torch
from common import AverageMeter, ProgressMeter
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions
for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True... | null |
25,677 | import time
import torch
from common import AverageMeter, ProgressMeter
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions
for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True... | null |
25,680 | import argparse
import os
import time
import torch
from common import AverageMeter, ProgressMeter
from data import get_dataloader, get_subnet_dataloader
from net import MyNet
from utils import *
from pytorch_nndct import get_pruning_runner
def accuracy(output, target, topk=(1,)):
class AverageMeter(object):
def _... | null |
25,684 | import sys
import os
def LOAD_FUNC(ports_num):
char = ""
for i in range (ports_num):
char += r' <port name="M_AXI_HP' + str(2)+'" mode="master" range="0xFFFFFFFF" dataWidth="128" portType="addressable" base="0x0"/>' + "\n"
return char | null |
25,685 | import sys
import os
def PORT_ARGS(ports_num):
char = ""
char += r' <arg name="dpu_base4_addr" addressQualifier="1" id="9" port="M_AXI_HP' + str(ports_num)+'" size="0x8" offset="0x80" hostOffset="0x0" hostSize="0x8" type="int*"/>' + "\n"
char += r' <arg name="dpu_base5_addr" addressQualifier="1" id="10... | null |
25,686 | import sys
import os
def IMG_AXI(ports_num):
char = ""
for i in range (ports_num):
char += r' <port name="M' + str(i).rjust(2,'0') + r'_IMG_AXI" mode="master" range="0x7FFFFFFF" dataWidth="128" portType="addressable" base="0x0"/>' + "\n"
return char | null |
25,687 | import sys
import os
def WGT_AXI(ports_num):
char = ""
for i in range (ports_num):
char += r' <port name="M' + str(i).rjust(2,'0') + r'_WGT_AXI" mode="master" range="0x7FFFFFFF" dataWidth="512" portType="addressable" base="0x0"/>' + "\n"
return char | null |
25,688 | import sys
import os
def IFM_AXIS(ports_num):
char = ""
for i in range (ports_num):
char += r' <port name="M' + str(i).rjust(2,'0') + r'_IFM_AXIS" mode="write_only" dataWidth="128" portType="stream"/>' + "\n"
return char | null |
25,689 | import sys
import os
def WGT_AXIS(ports_num):
char = ""
for i in range (ports_num):
char += r' <port name="M' + str(i).rjust(2,'0') + r'_WGT_AXIS" mode="write_only" dataWidth="128" portType="stream"/>' + "\n"
return char | null |
25,690 | import sys
import os
def OFM_AXIS(ports_num):
char = ""
for i in range (ports_num):
char += r' <port name="S' + str(i).rjust(2,'0') + r'_OFM_AXIS" mode="read_only" dataWidth="64" portType="stream"/>' + "\n"
return char | null |
25,691 | import sys
import os
global arg_id
arg_id = 15
def WGT_ARGS(ports_num):
char = ""
global arg_id
for i in range (ports_num):
offset_Batch0 = 0x200
for x in range (8):
char += r' <arg name="dpu_batch0_addr' + str(x) + r'" addressQualifier="1" id="' + str(arg_id) + r'" port=... | null |
25,692 | import sys
import os
global arg_id
arg_id = 15
def IMG_ARGS(batch, img_port):
char = ""
global arg_id
for i in range (batch):
offset_batch = i*64
offset_No = 0x200 + offset_batch
IMG_P = img_port * i
offset_Batch0 = 0x200
for x in range (img_port):
... | null |
25,693 | import sys
import os
global arg_id
arg_id = 15
global AXIS_No
def IFM_AXIS_ARGS(ports_num):
char = ""
AXIS_offset = 0x600
global arg_id
global AXIS_No
for i in range (ports_num):
AXIS_No = AXIS_offset + i*8
char += r' <arg name="M' + str(i).rjust(2,'0') + r'_IFM_AXIS" ... | null |
25,694 | import sys
import os
global arg_id
arg_id = 15
global AXIS_No
def WGT_AXIS_ARGS(ports_num):
char = ""
global arg_id
global AXIS_No
for i in range (ports_num):
AXIS_No = AXIS_No + 8
char += r' <arg name="M' + str(i).rjust(2,'0') + r'_WGT_AXIS" addressQualifier="4" id="' + str(a... | null |
25,695 | import sys
import os
global arg_id
arg_id = 15
global AXIS_No
def OFM_AXIS_ARGS(ports_num):
char = ""
global arg_id
global AXIS_No
for i in range (ports_num):
AXIS_No = AXIS_No + 8
char += r' <arg name="S' + str(i).rjust(2,'0') + r'_OFM_AXIS" addressQualifier="4" id="' + str(a... | null |
25,696 | import sys
import os
for i in range (CU_N):
result += genOFM(i,ofm_number)
for i in range (CU_N):
result += genIFM(i,ifm_number)
for i in range (CU_N):
result += genWGT(i,wgt_number,ifm_number*CU_N)
for i in range (CU_N):
result += genSP(i, "INSTR", 1, 0)
for i in range (CU_N):
result += genSP(i... | null |
25,697 | import sys
import os
for i in range (CU_N):
result += genOFM(i,ofm_number)
for i in range (CU_N):
result += genIFM(i,ifm_number)
for i in range (CU_N):
result += genWGT(i,wgt_number,ifm_number*CU_N)
for i in range (CU_N):
result += genSP(i, "INSTR", 1, 0)
for i in range (CU_N):
result += genSP(i... | null |
25,698 | import sys
import os
for i in range (CU_N):
result += genOFM(i,ofm_number)
for i in range (CU_N):
result += genIFM(i,ifm_number)
for i in range (CU_N):
result += genWGT(i,wgt_number,ifm_number*CU_N)
for i in range (CU_N):
result += genSP(i, "INSTR", 1, 0)
for i in range (CU_N):
result += genSP(i... | null |
25,699 | import sys
import os
for i in range (CU_N):
result += genOFM(i,ofm_number)
for i in range (CU_N):
result += genIFM(i,ifm_number)
for i in range (CU_N):
result += genWGT(i,wgt_number,ifm_number*CU_N)
global S_AXI_N
for i in range (CU_N):
result += genSP(i, "INSTR", 1, 0)
S_AXI_N = S_AXI_N + 1
for i... | null |
25,700 | import sys
import xml.etree.ElementTree
def vbnv(root):
v = root.attrib['{http://www.xilinx.com/sdx}vendor']
b = root.attrib['{http://www.xilinx.com/sdx}library']
n = root.attrib['{http://www.xilinx.com/sdx}name']
r = root.attrib['{http://www.xilinx.com/sdx}version']
return ':'.join([v,b,n,r]) | null |
25,701 | import sys
import xml.etree.ElementTree
def hw(root):
xpath = './{http://www.xilinx.com/sdx}hardwarePlatforms/{http://www.xilinx.com/sdx}hardwarePlatform'
sdx = root.find(xpath).attrib
dir = sdx['{http://www.xilinx.com/sdx}path']
dsa = sdx['{http://www.xilinx.com/sdx}name']
return dir + '/' + dsa | null |
25,702 | from sys import argv
import json
import glob
import os
import subprocess
def profile_report(target):
target.write("[Debug]\n")
target.write("profile=true\n")
return | null |
25,703 | from sys import argv
import json
import glob
import os
import subprocess
def create_params(target,data):
target.write("# Points to Utility Directory\n")
target.write("COMMON_REPO = ../../../\n")
target.write("ABS_COMMON_REPO = $(shell readlink -f $(COMMON_REPO))\n")
target.write("\n")
target.write("... | null |
25,704 | from sys import argv
import json
import os
import subprocess
def header(target,data):
target.write(data["example"])
target.write("\n")
target.write("======================\n\n")
target.write("This README file contains the following sections:\n\n")
target.write("1. OVERVIEW\n")
target.write("2. ... | null |
25,705 | from sys import argv
import json
import os
import subprocess
def download(target):
target.write("## 2. HOW TO DOWNLOAD THE REPOSITORY\n")
target.write("To get a local copy of the SDAccel example repository, clone this repository to the local system with the following command:\n")
target.write("```\n")
... | null |
25,706 | from sys import argv
import json
import os
import subprocess
def overview(target,data):
target.write("## 1. OVERVIEW\n")
target.write(('\n').join(data["overview"]))
target.write("\n\n")
if 'more_info' in data:
target.write(('\n').join(data["more_info"]))
target.write("\n\n")
if 'per... | null |
25,707 | from sys import argv
import json
import os
import subprocess
VERSION = 'SDAccel 2018.2'
DEVICES = {
'xilinx:kcu1500:dynamic': {
'version': '5.0',
'name': 'Xilinx Kintex UltraScale KCU1500',
'nae': 'nx4'
},
'xilinx:vcu1525:dynamic': {
'version': '5.0',
'name': 'Xilinx Virt... | null |
25,708 | from sys import argv
import json
import os
import subprocess
def hierarchy(target):
target.write("## 4. DESIGN FILE HIERARCHY\n")
target.write("Application code is located in the src directory. ")
target.write("Accelerator binary files will be compiled to the xclbin directory. ")
target.write("The xclb... | null |
25,709 | from sys import argv
import json
import os
import subprocess
DSA = 'xilinx:vcu1525:dynamic'
def compilation(target,data):
target.write("## 5. COMPILATION AND EXECUTION\n")
target.write("### Compiling for Application Emulation\n")
target.write("As part of the capabilities available to an application develop... | null |
25,710 | from sys import argv
import json
import os
import subprocess
def execution(target):
target.write("## 6. Execution in Cloud Environments\n")
target.write("FPGA acceleration boards have been deployed to the cloud. For information on how to execute the example within a specific cloud, take a look at the following... | null |
25,711 | from sys import argv
import json
import os
import subprocess
data = json.load(desc)
assert("OpenCL" in data['runtime'])
print "Generating the README for %s" % data["example"]
def nimbix(target):
target.write("The developer instance hosting the SDAccel tools on Nimbix is not directly connected to an FPGA accelerato... | null |
25,712 | from sys import argv
import json
import os
import subprocess
def power(target):
target.write("\n## 6. COMPILATION AND EXECUTION FOR IBM POWER SERVERS\n")
target.write("View the SuperVessel [Walkthrough Video][] to become familiar with the environment.\n\n")
target.write("Compile the application with the fo... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.