id
int64 0
190k
| prompt
stringlengths 21
13.4M
| docstring
stringlengths 1
12k
⌀ |
---|---|---|
1,213 | from __future__ import print_function
import torch
import pickle
import numpy as np
import math
import cv2
from PIL import Image, JpegImagePlugin
from scipy import ndimage
import hashlib
import sys, os
from zipfile import ZipFile
from .imgproc import loadImage
def printProgressBar(prefix='', suffix='', decimals=1, length=100, fill='█'):
def download_and_unzip(url, filename, model_storage_directory, verbose=True):
zip_path = os.path.join(model_storage_directory, 'temp.zip')
reporthook = printProgressBar(prefix='Progress:', suffix='Complete', length=50) if verbose else None
urlretrieve(url, zip_path, reporthook=reporthook)
with ZipFile(zip_path, 'r') as zipObj:
zipObj.extract(filename, model_storage_directory)
os.remove(zip_path) | null |
1,214 | from __future__ import print_function
import torch
import pickle
import numpy as np
import math
import cv2
from PIL import Image, JpegImagePlugin
from scipy import ndimage
import hashlib
import sys, os
from zipfile import ZipFile
from .imgproc import loadImage
def calculate_md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest() | null |
1,215 | from __future__ import print_function
import torch
import pickle
import numpy as np
import math
import cv2
from PIL import Image, JpegImagePlugin
from scipy import ndimage
import hashlib
import sys, os
from zipfile import ZipFile
from .imgproc import loadImage
def get_paragraph(raw_result, x_ths=1, y_ths=0.5, mode = 'ltr'):
# create basic attributes
box_group = []
for box in raw_result:
all_x = [int(coord[0]) for coord in box[0]]
all_y = [int(coord[1]) for coord in box[0]]
min_x = min(all_x)
max_x = max(all_x)
min_y = min(all_y)
max_y = max(all_y)
height = max_y - min_y
box_group.append([box[1], min_x, max_x, min_y, max_y, height, 0.5*(min_y+max_y), 0]) # last element indicates group
# cluster boxes into paragraph
current_group = 1
while len([box for box in box_group if box[7]==0]) > 0:
box_group0 = [box for box in box_group if box[7]==0] # group0 = non-group
# new group
if len([box for box in box_group if box[7]==current_group]) == 0:
box_group0[0][7] = current_group # assign first box to form new group
# try to add group
else:
current_box_group = [box for box in box_group if box[7]==current_group]
mean_height = np.mean([box[5] for box in current_box_group])
min_gx = min([box[1] for box in current_box_group]) - x_ths*mean_height
max_gx = max([box[2] for box in current_box_group]) + x_ths*mean_height
min_gy = min([box[3] for box in current_box_group]) - y_ths*mean_height
max_gy = max([box[4] for box in current_box_group]) + y_ths*mean_height
add_box = False
for box in box_group0:
same_horizontal_level = (min_gx<=box[1]<=max_gx) or (min_gx<=box[2]<=max_gx)
same_vertical_level = (min_gy<=box[3]<=max_gy) or (min_gy<=box[4]<=max_gy)
if same_horizontal_level and same_vertical_level:
box[7] = current_group
add_box = True
break
# cannot add more box, go to next group
if add_box==False:
current_group += 1
# arrage order in paragraph
result = []
for i in set(box[7] for box in box_group):
current_box_group = [box for box in box_group if box[7]==i]
mean_height = np.mean([box[5] for box in current_box_group])
min_gx = min([box[1] for box in current_box_group])
max_gx = max([box[2] for box in current_box_group])
min_gy = min([box[3] for box in current_box_group])
max_gy = max([box[4] for box in current_box_group])
text = ''
while len(current_box_group) > 0:
highest = min([box[6] for box in current_box_group])
candidates = [box for box in current_box_group if box[6]<highest+0.4*mean_height]
# get the far left
if mode == 'ltr':
most_left = min([box[1] for box in candidates])
for box in candidates:
if box[1] == most_left: best_box = box
elif mode == 'rtl':
most_right = max([box[2] for box in candidates])
for box in candidates:
if box[2] == most_right: best_box = box
text += ' '+best_box[0]
current_box_group.remove(best_box)
result.append([ [[min_gx,min_gy],[max_gx,min_gy],[max_gx,max_gy],[min_gx,max_gy]], text[1:]])
return result | null |
1,216 | from __future__ import print_function
import torch
import pickle
import numpy as np
import math
import cv2
from PIL import Image, JpegImagePlugin
from scipy import ndimage
import hashlib
import sys, os
from zipfile import ZipFile
from .imgproc import loadImage
def reformat_input(image):
if type(image) == str:
if image.startswith('http://') or image.startswith('https://'):
tmp, _ = urlretrieve(image , reporthook=printProgressBar(prefix = 'Progress:', suffix = 'Complete', length = 50))
img_cv_grey = cv2.imread(tmp, cv2.IMREAD_GRAYSCALE)
os.remove(tmp)
else:
img_cv_grey = cv2.imread(image, cv2.IMREAD_GRAYSCALE)
image = os.path.expanduser(image)
img = loadImage(image) # can accept URL
elif type(image) == bytes:
nparr = np.frombuffer(image, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_cv_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
elif type(image) == np.ndarray:
if len(image.shape) == 2: # grayscale
img_cv_grey = image
img = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
elif len(image.shape) == 3 and image.shape[2] == 1:
img_cv_grey = np.squeeze(image)
img = cv2.cvtColor(img_cv_grey, cv2.COLOR_GRAY2BGR)
elif len(image.shape) == 3 and image.shape[2] == 3: # BGRscale
img = image
img_cv_grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
elif len(image.shape) == 3 and image.shape[2] == 4: # RGBAscale
img = image[:,:,:3]
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
img_cv_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
elif type(image) == JpegImagePlugin.JpegImageFile:
image_array = np.array(image)
img = cv2.cvtColor(image_array, cv2.COLOR_RGB2BGR)
img_cv_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
else:
raise ValueError('Invalid input type. Supporting format = string(file path or url), bytes, numpy array')
return img, img_cv_grey
The provided code snippet includes necessary dependencies for implementing the `reformat_input_batched` function. Write a Python function `def reformat_input_batched(image, n_width=None, n_height=None)` to solve the following problem:
reformats an image or list of images or a 4D numpy image array & returns a list of corresponding img, img_cv_grey nd.arrays image: [file path, numpy-array, byte stream object, list of file paths, list of numpy-array, 4D numpy array, list of byte stream objects]
Here is the function:
def reformat_input_batched(image, n_width=None, n_height=None):
"""
reformats an image or list of images or a 4D numpy image array &
returns a list of corresponding img, img_cv_grey nd.arrays
image:
[file path, numpy-array, byte stream object,
list of file paths, list of numpy-array, 4D numpy array,
list of byte stream objects]
"""
if ((isinstance(image, np.ndarray) and len(image.shape) == 4) or isinstance(image, list)):
# process image batches if image is list of image np arr, paths, bytes
img, img_cv_grey = [], []
for single_img in image:
clr, gry = reformat_input(single_img)
if n_width is not None and n_height is not None:
clr = cv2.resize(clr, (n_width, n_height))
gry = cv2.resize(gry, (n_width, n_height))
img.append(clr)
img_cv_grey.append(gry)
img, img_cv_grey = np.array(img), np.array(img_cv_grey)
# ragged tensors created when all input imgs are not of the same size
if len(img.shape) == 1 and len(img_cv_grey.shape) == 1:
raise ValueError("The input image array contains images of different sizes. " +
"Please resize all images to same shape or pass n_width, n_height to auto-resize")
else:
img, img_cv_grey = reformat_input(image)
return img, img_cv_grey | reformats an image or list of images or a 4D numpy image array & returns a list of corresponding img, img_cv_grey nd.arrays image: [file path, numpy-array, byte stream object, list of file paths, list of numpy-array, 4D numpy array, list of byte stream objects] |
1,217 | from __future__ import print_function
import torch
import pickle
import numpy as np
import math
import cv2
from PIL import Image, JpegImagePlugin
from scipy import ndimage
import hashlib
import sys, os
from zipfile import ZipFile
from .imgproc import loadImage
def calculate_ratio(width,height):
def make_rotated_img_list(rotationInfo, img_list):
result_img_list = img_list[:]
# add rotated images to original image_list
max_ratio=1
for angle in rotationInfo:
for img_info in img_list :
rotated = ndimage.rotate(img_info[1], angle, reshape=True)
height,width = rotated.shape
ratio = calculate_ratio(width,height)
max_ratio = max(max_ratio,ratio)
result_img_list.append((img_info[0], rotated))
return result_img_list | null |
1,218 | from __future__ import print_function
import torch
import pickle
import numpy as np
import math
import cv2
from PIL import Image, JpegImagePlugin
from scipy import ndimage
import hashlib
import sys, os
from zipfile import ZipFile
from .imgproc import loadImage
The provided code snippet includes necessary dependencies for implementing the `set_result_with_confidence` function. Write a Python function `def set_result_with_confidence(results)` to solve the following problem:
Select highest confidence augmentation for TTA Given a list of lists of results (outer list has one list per augmentation, inner lists index the images being recognized), choose the best result according to confidence level. Each "result" is of the form (box coords, text, confidence) A final_result is returned which contains one result for each image
Here is the function:
def set_result_with_confidence(results):
""" Select highest confidence augmentation for TTA
Given a list of lists of results (outer list has one list per augmentation,
inner lists index the images being recognized), choose the best result
according to confidence level.
Each "result" is of the form (box coords, text, confidence)
A final_result is returned which contains one result for each image
"""
final_result = []
for col_ix in range(len(results[0])):
# Take the row_ix associated with the max confidence
best_row = max(
[(row_ix, results[row_ix][col_ix][2]) for row_ix in range(len(results))],
key=lambda x: x[1])[0]
final_result.append(results[best_row][col_ix])
return final_result | Select highest confidence augmentation for TTA Given a list of lists of results (outer list has one list per augmentation, inner lists index the images being recognized), choose the best result according to confidence level. Each "result" is of the form (box coords, text, confidence) A final_result is returned which contains one result for each image |
1,219 | import torch
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from PIL import Image
from collections import OrderedDict
import cv2
import numpy as np
from .craft_utils import getDetBoxes, adjustResultCoordinates
from .imgproc import resize_aspect_ratio, normalizeMeanVariance
from .craft import CRAFT
def copyStateDict(state_dict):
class CRAFT(nn.Module):
def __init__(self, pretrained=False, freeze=False):
def forward(self, x):
def get_detector(trained_model, device='cpu', quantize=True, cudnn_benchmark=False):
net = CRAFT()
if device == 'cpu':
net.load_state_dict(copyStateDict(torch.load(trained_model, map_location=device)))
if quantize:
try:
torch.quantization.quantize_dynamic(net, dtype=torch.qint8, inplace=True)
except:
pass
else:
net.load_state_dict(copyStateDict(torch.load(trained_model, map_location=device)))
net = torch.nn.DataParallel(net).to(device)
cudnn.benchmark = cudnn_benchmark
net.eval()
return net | null |
1,220 | import torch
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from PIL import Image
from collections import OrderedDict
import cv2
import numpy as np
from .craft_utils import getDetBoxes, adjustResultCoordinates
from .imgproc import resize_aspect_ratio, normalizeMeanVariance
from .craft import CRAFT
def test_net(canvas_size, mag_ratio, net, image, text_threshold, link_threshold, low_text, poly, device, estimate_num_chars=False):
if isinstance(image, np.ndarray) and len(image.shape) == 4: # image is batch of np arrays
image_arrs = image
else: # image is single numpy array
image_arrs = [image]
img_resized_list = []
# resize
for img in image_arrs:
img_resized, target_ratio, size_heatmap = resize_aspect_ratio(img, canvas_size,
interpolation=cv2.INTER_LINEAR,
mag_ratio=mag_ratio)
img_resized_list.append(img_resized)
ratio_h = ratio_w = 1 / target_ratio
# preprocessing
x = [np.transpose(normalizeMeanVariance(n_img), (2, 0, 1))
for n_img in img_resized_list]
x = torch.from_numpy(np.array(x))
x = x.to(device)
# forward pass
with torch.no_grad():
y, feature = net(x)
boxes_list, polys_list = [], []
for out in y:
# make score and link map
score_text = out[:, :, 0].cpu().data.numpy()
score_link = out[:, :, 1].cpu().data.numpy()
# Post-processing
boxes, polys, mapper = getDetBoxes(
score_text, score_link, text_threshold, link_threshold, low_text, poly, estimate_num_chars)
# coordinate adjustment
boxes = adjustResultCoordinates(boxes, ratio_w, ratio_h)
polys = adjustResultCoordinates(polys, ratio_w, ratio_h)
if estimate_num_chars:
boxes = list(boxes)
polys = list(polys)
for k in range(len(polys)):
if estimate_num_chars:
boxes[k] = (boxes[k], mapper[k])
if polys[k] is None:
polys[k] = boxes[k]
boxes_list.append(boxes)
polys_list.append(polys)
return boxes_list, polys_list
def get_textbox(detector, image, canvas_size, mag_ratio, text_threshold, link_threshold, low_text, poly, device, optimal_num_chars=None, **kwargs):
result = []
estimate_num_chars = optimal_num_chars is not None
bboxes_list, polys_list = test_net(canvas_size, mag_ratio, detector,
image, text_threshold,
link_threshold, low_text, poly,
device, estimate_num_chars)
if estimate_num_chars:
polys_list = [[p for p, _ in sorted(polys, key=lambda x: abs(optimal_num_chars - x[1]))]
for polys in polys_list]
for polys in polys_list:
single_img_result = []
for i, box in enumerate(polys):
poly = np.array(box).astype(np.int32).reshape((-1))
single_img_result.append(poly)
result.append(single_img_result)
return result | null |
1,221 | from PIL import Image
import torch
import torch.backends.cudnn as cudnn
import torch.utils.data
import torch.nn.functional as F
import torchvision.transforms as transforms
import numpy as np
from collections import OrderedDict
import importlib
from .utils import CTCLabelConverter
import math
def contrast_grey(img):
def adjust_contrast_grey(img, target = 0.4):
contrast, high, low = contrast_grey(img)
if contrast < target:
img = img.astype(int)
ratio = 200./np.maximum(10, high-low)
img = (img - low + 25)*ratio
img = np.maximum(np.full(img.shape, 0) ,np.minimum(np.full(img.shape, 255), img)).astype(np.uint8)
return img | null |
1,222 | from PIL import Image
import torch
import torch.backends.cudnn as cudnn
import torch.utils.data
import torch.nn.functional as F
import torchvision.transforms as transforms
import numpy as np
from collections import OrderedDict
import importlib
from .utils import CTCLabelConverter
import math
class CTCLabelConverter(object):
""" Convert between text-label and text-index """
def __init__(self, character, separator_list = {}, dict_pathlist = {}):
# character (str): set of the possible characters.
dict_character = list(character)
self.dict = {}
for i, char in enumerate(dict_character):
self.dict[char] = i + 1
self.character = ['[blank]'] + dict_character # dummy '[blank]' token for CTCLoss (index 0)
self.separator_list = separator_list
separator_char = []
for lang, sep in separator_list.items():
separator_char += sep
self.ignore_idx = [0] + [i+1 for i,item in enumerate(separator_char)]
####### latin dict
if len(separator_list) == 0:
dict_list = []
for lang, dict_path in dict_pathlist.items():
try:
with open(dict_path, "r", encoding = "utf-8-sig") as input_file:
word_count = input_file.read().splitlines()
dict_list += word_count
except:
pass
else:
dict_list = {}
for lang, dict_path in dict_pathlist.items():
with open(dict_path, "r", encoding = "utf-8-sig") as input_file:
word_count = input_file.read().splitlines()
dict_list[lang] = word_count
self.dict_list = dict_list
def encode(self, text, batch_max_length=25):
"""convert text-label into text-index.
input:
text: text labels of each image. [batch_size]
output:
text: concatenated text index for CTCLoss.
[sum(text_lengths)] = [text_index_0 + text_index_1 + ... + text_index_(n - 1)]
length: length of each text. [batch_size]
"""
length = [len(s) for s in text]
text = ''.join(text)
text = [self.dict[char] for char in text]
return (torch.IntTensor(text), torch.IntTensor(length))
def decode_greedy(self, text_index, length):
""" convert text-index into text-label. """
texts = []
index = 0
for l in length:
t = text_index[index:index + l]
# Returns a boolean array where true is when the value is not repeated
a = np.insert(~((t[1:]==t[:-1])),0,True)
# Returns a boolean array where true is when the value is not in the ignore_idx list
b = ~np.isin(t,np.array(self.ignore_idx))
# Combine the two boolean array
c = a & b
# Gets the corresponding character according to the saved indexes
text = ''.join(np.array(self.character)[t[c.nonzero()]])
texts.append(text)
index += l
return texts
def decode_beamsearch(self, mat, beamWidth=5):
texts = []
for i in range(mat.shape[0]):
t = ctcBeamSearch(mat[i], self.character, self.ignore_idx, None, beamWidth=beamWidth)
texts.append(t)
return texts
def decode_wordbeamsearch(self, mat, beamWidth=5):
texts = []
argmax = np.argmax(mat, axis = 2)
for i in range(mat.shape[0]):
string = ''
# without separators - use space as separator
if len(self.separator_list) == 0:
space_idx = self.dict[' ']
data = np.argwhere(argmax[i]!=space_idx).flatten()
group = np.split(data, np.where(np.diff(data) != 1)[0]+1)
group = [ list(item) for item in group if len(item)>0]
for j, list_idx in enumerate(group):
matrix = mat[i, list_idx,:]
t = ctcBeamSearch(matrix, self.character, self.ignore_idx, None,\
beamWidth=beamWidth, dict_list=self.dict_list)
if j == 0: string += t
else: string += ' '+t
# with separators
else:
words = word_segmentation(argmax[i])
for word in words:
matrix = mat[i, word[1][0]:word[1][1]+1,:]
if word[0] == '': dict_list = []
else: dict_list = self.dict_list[word[0]]
t = ctcBeamSearch(matrix, self.character, self.ignore_idx, None, beamWidth=beamWidth, dict_list=dict_list)
string += t
texts.append(string)
return texts
def get_recognizer(recog_network, network_params, character,\
separator_list, dict_list, model_path,\
device = 'cpu', quantize = True):
converter = CTCLabelConverter(character, separator_list, dict_list)
num_class = len(converter.character)
if recog_network == 'generation1':
model_pkg = importlib.import_module("easyocr.model.model")
elif recog_network == 'generation2':
model_pkg = importlib.import_module("easyocr.model.vgg_model")
else:
model_pkg = importlib.import_module(recog_network)
model = model_pkg.Model(num_class=num_class, **network_params)
if device == 'cpu':
state_dict = torch.load(model_path, map_location=device)
new_state_dict = OrderedDict()
for key, value in state_dict.items():
new_key = key[7:]
new_state_dict[new_key] = value
model.load_state_dict(new_state_dict)
if quantize:
try:
torch.quantization.quantize_dynamic(model, dtype=torch.qint8, inplace=True)
except:
pass
else:
model = torch.nn.DataParallel(model).to(device)
model.load_state_dict(torch.load(model_path, map_location=device))
return model, converter | null |
1,223 | from PIL import Image
import torch
import torch.backends.cudnn as cudnn
import torch.utils.data
import torch.nn.functional as F
import torchvision.transforms as transforms
import numpy as np
from collections import OrderedDict
import importlib
from .utils import CTCLabelConverter
import math
class ListDataset(torch.utils.data.Dataset):
def __init__(self, image_list):
def __len__(self):
def __getitem__(self, index):
class AlignCollate(object):
def __init__(self, imgH=32, imgW=100, keep_ratio_with_pad=False, adjust_contrast = 0.):
def __call__(self, batch):
def recognizer_predict(model, converter, test_loader, batch_max_length,\
ignore_idx, char_group_idx, decoder = 'greedy', beamWidth= 5, device = 'cpu'):
def get_text(character, imgH, imgW, recognizer, converter, image_list,\
ignore_char = '',decoder = 'greedy', beamWidth =5, batch_size=1, contrast_ths=0.1,\
adjust_contrast=0.5, filter_ths = 0.003, workers = 1, device = 'cpu'):
batch_max_length = int(imgW/10)
char_group_idx = {}
ignore_idx = []
for char in ignore_char:
try: ignore_idx.append(character.index(char)+1)
except: pass
coord = [item[0] for item in image_list]
img_list = [item[1] for item in image_list]
AlignCollate_normal = AlignCollate(imgH=imgH, imgW=imgW, keep_ratio_with_pad=True)
test_data = ListDataset(img_list)
test_loader = torch.utils.data.DataLoader(
test_data, batch_size=batch_size, shuffle=False,
num_workers=int(workers), collate_fn=AlignCollate_normal, pin_memory=True)
# predict first round
result1 = recognizer_predict(recognizer, converter, test_loader,batch_max_length,\
ignore_idx, char_group_idx, decoder, beamWidth, device = device)
# predict second round
low_confident_idx = [i for i,item in enumerate(result1) if (item[1] < contrast_ths)]
if len(low_confident_idx) > 0:
img_list2 = [img_list[i] for i in low_confident_idx]
AlignCollate_contrast = AlignCollate(imgH=imgH, imgW=imgW, keep_ratio_with_pad=True, adjust_contrast=adjust_contrast)
test_data = ListDataset(img_list2)
test_loader = torch.utils.data.DataLoader(
test_data, batch_size=batch_size, shuffle=False,
num_workers=int(workers), collate_fn=AlignCollate_contrast, pin_memory=True)
result2 = recognizer_predict(recognizer, converter, test_loader, batch_max_length,\
ignore_idx, char_group_idx, decoder, beamWidth, device = device)
result = []
for i, zipped in enumerate(zip(coord, result1)):
box, pred1 = zipped
if i in low_confident_idx:
pred2 = result2[low_confident_idx.index(i)]
if pred1[1]>pred2[1]:
result.append( (box, pred1[0], pred1[1]) )
else:
result.append( (box, pred2[0], pred2[1]) )
else:
result.append( (box, pred1[0], pred1[1]) )
return result | null |
1,224 | import os
import glob
from datetime import datetime
import subprocess
def print_error(errors, log_path):
if not isinstance(errors, list):
errors = [errors]
errors = [error if isinstance(error, bytes) else error.encode('utf-8') for error in errors]
url = "https://github.com/JaidedAI/EasyOCR/tree/master/easyocr/DBNet"
print("Failed to compile dcn operator for DBNet.")
with open(log_path, "wb") as fid:
fid.write((datetime.now().strftime("%H:%M:%S - %d %b %Y") + "\n").encode('utf-8'))
fid.write("Failed to compile dcn operator for DBNet with the following error.\n".encode('utf-8'))
fid.write(("#"*42 + '\n').encode('utf-8'))
[fid.write(error) for error in errors]
print("Error message can be found in {}.".format(os.path.abspath(log_path)))
print("#"*42)
print("EasyOCR can still be used with CRAFT text detector (default).")
print("To use DBNet text detector, please check {} for troubleshoot and compile dcn operator manually.".format(url)) | null |
1,225 | import os
import glob
from datetime import datetime
import subprocess
def print_success(text, log_path):
with open(log_path, "wb") as fid:
fid.write((datetime.now().strftime("%H:%M:%S - %d %b %Y") + "\n").encode('utf-8'))
fid.write((text + "\n").encode('utf-8'))
print(text)
def validate_compilation(parent_dir, log_path, cpu_or_cuda):
dcn_dir = os.path.join(parent_dir, 'DBNet', 'assets', 'ops', 'dcn')
#Just to be safe, check explicitly.
if cpu_or_cuda == 'cpu':
conv_cpu_exist = glob.glob(os.path.join(dcn_dir, 'deform_conv_cpu.*.so'))
pool_cpu_exist = glob.glob(os.path.join(dcn_dir, 'deform_pool_cpu.*.so'))
success_message = "DCN CPU operator is compiled successfully at {}.".format(os.path.abspath(os.path.join(parent_dir,'DBNet')))
print_success(success_message, log_path)
return conv_cpu_exist and pool_cpu_exist
elif cpu_or_cuda == 'cuda':
conv_cuda_exist = glob.glob(os.path.join(dcn_dir, 'deform_conv_cuda.*.so'))
pool_cuda_exist = glob.glob(os.path.join(dcn_dir, 'deform_pool_cuda.*.so'))
success_message = "DCN CUDA operator is compiled successfully at {}.".format(os.path.abspath(os.path.join(parent_dir,'DBNet')))
print_success(success_message, log_path)
return conv_cuda_exist and pool_cuda_exist
else:
raise ValueError("'cpu_or_cuda' must be either 'cpu' or 'cuda'") | null |
1,226 | import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_bn(inp, oup, stride, conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU):
return nn.Sequential(
conv_layer(inp, oup, 3, stride, 1, bias=False),
norm_layer(oup),
nlin_layer(inplace=True)
) | null |
1,227 | import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_1x1_bn(inp, oup, conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU):
return nn.Sequential(
conv_layer(inp, oup, 1, 1, 0, bias=False),
norm_layer(oup),
nlin_layer(inplace=True)
) | null |
1,228 | import torch
import torch.nn as nn
import torch.nn.functional as F
def make_divisible(x, divisible_by=8):
import numpy as np
return int(np.ceil(x * 1. / divisible_by) * divisible_by) | null |
1,229 | import torch
import torch.nn as nn
import torch.nn.functional as F
class MobileNetV3(nn.Module):
def __init__(self, n_class=1000, input_size=224, dropout=0.8, mode='small', width_mult=1.0):
super(MobileNetV3, self).__init__()
input_channel = 16
last_channel = 1280
if mode == 'large':
# refer to Table 1 in paper
mobile_setting = [
# k, exp, c, se, nl, s,
[3, 16, 16, False, 'RE', 1],
[3, 64, 24, False, 'RE', 2],
[3, 72, 24, False, 'RE', 1], # 3
[5, 72, 40, True, 'RE', 2],
[5, 120, 40, True, 'RE', 1],
[5, 120, 40, True, 'RE', 1], # 6
[3, 240, 80, False, 'HS', 2],
[3, 200, 80, False, 'HS', 1],
[3, 184, 80, False, 'HS', 1],
[3, 184, 80, False, 'HS', 1],
[3, 480, 112, True, 'HS', 1],
[3, 672, 112, True, 'HS', 1], # 12
[5, 672, 160, True, 'HS', 2],
[5, 960, 160, True, 'HS', 1],
[5, 960, 160, True, 'HS', 1],
]
elif mode == 'small':
# refer to Table 2 in paper
mobile_setting = [
# k, exp, c, se, nl, s,
[3, 16, 16, True, 'RE', 2],
[3, 72, 24, False, 'RE', 2],
[3, 88, 24, False, 'RE', 1],
[5, 96, 40, True, 'HS', 2],
[5, 240, 40, True, 'HS', 1],
[5, 240, 40, True, 'HS', 1],
[5, 120, 48, True, 'HS', 1],
[5, 144, 48, True, 'HS', 1],
[5, 288, 96, True, 'HS', 2],
[5, 576, 96, True, 'HS', 1],
[5, 576, 96, True, 'HS', 1],
]
else:
raise NotImplementedError
# building first layer
assert input_size % 32 == 0
last_channel = make_divisible(last_channel * width_mult) if width_mult > 1.0 else last_channel
self.features = nn.ModuleList([conv_bn(3, input_channel, 2, nlin_layer=Hswish)]) # start_idx = 0: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same
self.classifier = []
# building mobile blocks
for k, exp, c, se, nl, s in mobile_setting:
output_channel = make_divisible(c * width_mult)
exp_channel = make_divisible(exp * width_mult)
self.features.append(MobileBottleneck(input_channel, output_channel, k, s, exp_channel, se, nl))
input_channel = output_channel
# building last several layers
if mode == 'large':
last_conv = make_divisible(960 * width_mult)
self.features.append(conv_1x1_bn(input_channel, last_conv, nlin_layer=Hswish)) # 16
self.features.append(nn.AdaptiveAvgPool2d(1))
self.features.append(nn.Conv2d(last_conv, last_channel, 1, 1, 0))
self.features.append(Hswish(inplace=True))
elif mode == 'small':
last_conv = make_divisible(576 * width_mult)
self.features.append(conv_1x1_bn(input_channel, last_conv, nlin_layer=Hswish))
# self.features.append(SEModule(last_conv)) # refer to paper Table2, but I think this is a mistake
self.features.append(nn.AdaptiveAvgPool2d(1))
self.features.append(nn.Conv2d(last_conv, last_channel, 1, 1, 0))
self.features.append(Hswish(inplace=True))
else:
raise NotImplementedError
# make it nn.Sequential
#self.features = nn.Sequential(*self.features) del for dbnet
# building classifier
self.classifier = nn.Sequential(
nn.Dropout(p=dropout), # refer to paper section 6
nn.Linear(last_channel, n_class),
)
self._initialize_weights()
def forward(self, x):
'''x = self.features(x)
x = x.mean(3).mean(2)
x = self.classifier(x)
return x'''
x2, x3, x4, x5 = None, None, None, None
for stage in range(17): # https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.1/ppocr/modeling/backbones/det_mobilenet_v3.py
x = self.features[stage](x)
if stage == 3: # if s == 2 and start_idx > 3
x2 = x
elif stage == 6:
x3 = x
elif stage == 12:
x4 = x
elif stage == 16:
x5 = x
return x2, x3, x4, x5
def _initialize_weights(self):
# weight initialization
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.BatchNorm2d):
nn.init.ones_(m.weight)
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
if m.bias is not None:
nn.init.zeros_(m.bias)
def mobilenet_v3_large(pretrained=False, **kwargs):
model = MobileNetV3(mode='large', **kwargs)
if pretrained:
state_dict = torch.load('mobilenetv3_large.pth.tar')
model.load_state_dict(state_dict, strict=True)
# raise NotImplementedError
return model | null |
1,230 | import torch
import torch.nn as nn
import torch.nn.functional as F
class MobileNetV3(nn.Module):
def __init__(self, n_class=1000, input_size=224, dropout=0.8, mode='small', width_mult=1.0):
super(MobileNetV3, self).__init__()
input_channel = 16
last_channel = 1280
if mode == 'large':
# refer to Table 1 in paper
mobile_setting = [
# k, exp, c, se, nl, s,
[3, 16, 16, False, 'RE', 1],
[3, 64, 24, False, 'RE', 2],
[3, 72, 24, False, 'RE', 1], # 3
[5, 72, 40, True, 'RE', 2],
[5, 120, 40, True, 'RE', 1],
[5, 120, 40, True, 'RE', 1], # 6
[3, 240, 80, False, 'HS', 2],
[3, 200, 80, False, 'HS', 1],
[3, 184, 80, False, 'HS', 1],
[3, 184, 80, False, 'HS', 1],
[3, 480, 112, True, 'HS', 1],
[3, 672, 112, True, 'HS', 1], # 12
[5, 672, 160, True, 'HS', 2],
[5, 960, 160, True, 'HS', 1],
[5, 960, 160, True, 'HS', 1],
]
elif mode == 'small':
# refer to Table 2 in paper
mobile_setting = [
# k, exp, c, se, nl, s,
[3, 16, 16, True, 'RE', 2],
[3, 72, 24, False, 'RE', 2],
[3, 88, 24, False, 'RE', 1],
[5, 96, 40, True, 'HS', 2],
[5, 240, 40, True, 'HS', 1],
[5, 240, 40, True, 'HS', 1],
[5, 120, 48, True, 'HS', 1],
[5, 144, 48, True, 'HS', 1],
[5, 288, 96, True, 'HS', 2],
[5, 576, 96, True, 'HS', 1],
[5, 576, 96, True, 'HS', 1],
]
else:
raise NotImplementedError
# building first layer
assert input_size % 32 == 0
last_channel = make_divisible(last_channel * width_mult) if width_mult > 1.0 else last_channel
self.features = nn.ModuleList([conv_bn(3, input_channel, 2, nlin_layer=Hswish)]) # start_idx = 0: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same
self.classifier = []
# building mobile blocks
for k, exp, c, se, nl, s in mobile_setting:
output_channel = make_divisible(c * width_mult)
exp_channel = make_divisible(exp * width_mult)
self.features.append(MobileBottleneck(input_channel, output_channel, k, s, exp_channel, se, nl))
input_channel = output_channel
# building last several layers
if mode == 'large':
last_conv = make_divisible(960 * width_mult)
self.features.append(conv_1x1_bn(input_channel, last_conv, nlin_layer=Hswish)) # 16
self.features.append(nn.AdaptiveAvgPool2d(1))
self.features.append(nn.Conv2d(last_conv, last_channel, 1, 1, 0))
self.features.append(Hswish(inplace=True))
elif mode == 'small':
last_conv = make_divisible(576 * width_mult)
self.features.append(conv_1x1_bn(input_channel, last_conv, nlin_layer=Hswish))
# self.features.append(SEModule(last_conv)) # refer to paper Table2, but I think this is a mistake
self.features.append(nn.AdaptiveAvgPool2d(1))
self.features.append(nn.Conv2d(last_conv, last_channel, 1, 1, 0))
self.features.append(Hswish(inplace=True))
else:
raise NotImplementedError
# make it nn.Sequential
#self.features = nn.Sequential(*self.features) del for dbnet
# building classifier
self.classifier = nn.Sequential(
nn.Dropout(p=dropout), # refer to paper section 6
nn.Linear(last_channel, n_class),
)
self._initialize_weights()
def forward(self, x):
'''x = self.features(x)
x = x.mean(3).mean(2)
x = self.classifier(x)
return x'''
x2, x3, x4, x5 = None, None, None, None
for stage in range(17): # https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.1/ppocr/modeling/backbones/det_mobilenet_v3.py
x = self.features[stage](x)
if stage == 3: # if s == 2 and start_idx > 3
x2 = x
elif stage == 6:
x3 = x
elif stage == 12:
x4 = x
elif stage == 16:
x5 = x
return x2, x3, x4, x5
def _initialize_weights(self):
# weight initialization
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.BatchNorm2d):
nn.init.ones_(m.weight)
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
if m.bias is not None:
nn.init.zeros_(m.bias)
def mobilenet_v3_small(pretrained=False, **kwargs):
model = MobileNetV3(mode='small', **kwargs)
if pretrained:
state_dict = torch.load('mobilenetv3_small_67.4.pth.tar')
model.load_state_dict(state_dict, strict=True)
# raise NotImplementedError
return model | null |
1,231 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
def constant_init(module, constant, bias=0):
nn.init.constant_(module.weight, constant)
if hasattr(module, 'bias'):
nn.init.constant_(module.bias, bias) | null |
1,232 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1)` to solve the following problem:
3x3 convolution with padding
Here is the function:
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False) | 3x3 convolution with padding |
1,233 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, dcn=None):
super(BasicBlock, self).__init__()
self.with_dcn = dcn is not None
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.with_modulated_dcn = False
if self.with_dcn:
fallback_on_stride = dcn.get('fallback_on_stride', False)
self.with_modulated_dcn = dcn.get('modulated', False)
# self.conv2 = conv3x3(planes, planes)
if not self.with_dcn or fallback_on_stride:
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
padding=1, bias=False)
else:
deformable_groups = dcn.get('deformable_groups', 1)
if not self.with_modulated_dcn:
#from assets.ops.dcn import DeformConv
from ..assets.ops.dcn import DeformConv
conv_op = DeformConv
offset_channels = 18
else:
#from assets.ops.dcn import ModulatedDeformConv
from ..assets.ops.dcn import ModulatedDeformConv
conv_op = ModulatedDeformConv
offset_channels = 27
self.conv2_offset = nn.Conv2d(
planes,
deformable_groups * offset_channels,
kernel_size=3,
padding=1)
self.conv2 = conv_op(
planes,
planes,
kernel_size=3,
padding=1,
deformable_groups=deformable_groups,
bias=False)
self.bn2 = BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
# out = self.conv2(out)
if not self.with_dcn:
out = self.conv2(out)
elif self.with_modulated_dcn:
offset_mask = self.conv2_offset(out)
offset = offset_mask[:, :18, :, :]
mask = offset_mask[:, -9:, :, :].sigmoid()
out = self.conv2(out, offset, mask)
else:
offset = self.conv2_offset(out)
out = self.conv2(out, offset)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000,
dcn=None, stage_with_dcn=(False, False, False, False)):
self.dcn = dcn
self.stage_with_dcn = stage_with_dcn
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(
block, 128, layers[1], stride=2, dcn=dcn)
self.layer3 = self._make_layer(
block, 256, layers[2], stride=2, dcn=dcn)
self.layer4 = self._make_layer(
block, 512, layers[3], stride=2, dcn=dcn)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
self.smooth = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=1)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
if self.dcn is not None:
for m in self.modules():
if isinstance(m, Bottleneck) or isinstance(m, BasicBlock):
if hasattr(m, 'conv2_offset'):
constant_init(m.conv2_offset, 0)
def _make_layer(self, block, planes, blocks, stride=1, dcn=None):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes,
stride, downsample, dcn=dcn))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes, dcn=dcn))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x2 = self.layer1(x)
x3 = self.layer2(x2)
x4 = self.layer3(x3)
x5 = self.layer4(x4)
return x2, x3, x4, x5
The provided code snippet includes necessary dependencies for implementing the `resnet18` function. Write a Python function `def resnet18(pretrained=True, **kwargs)` to solve the following problem:
Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Here is the function:
def resnet18(pretrained=True, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(
model_urls['resnet18']), strict=False)
return model | Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,234 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, dcn=None):
super(BasicBlock, self).__init__()
self.with_dcn = dcn is not None
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.with_modulated_dcn = False
if self.with_dcn:
fallback_on_stride = dcn.get('fallback_on_stride', False)
self.with_modulated_dcn = dcn.get('modulated', False)
# self.conv2 = conv3x3(planes, planes)
if not self.with_dcn or fallback_on_stride:
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
padding=1, bias=False)
else:
deformable_groups = dcn.get('deformable_groups', 1)
if not self.with_modulated_dcn:
#from assets.ops.dcn import DeformConv
from ..assets.ops.dcn import DeformConv
conv_op = DeformConv
offset_channels = 18
else:
#from assets.ops.dcn import ModulatedDeformConv
from ..assets.ops.dcn import ModulatedDeformConv
conv_op = ModulatedDeformConv
offset_channels = 27
self.conv2_offset = nn.Conv2d(
planes,
deformable_groups * offset_channels,
kernel_size=3,
padding=1)
self.conv2 = conv_op(
planes,
planes,
kernel_size=3,
padding=1,
deformable_groups=deformable_groups,
bias=False)
self.bn2 = BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
# out = self.conv2(out)
if not self.with_dcn:
out = self.conv2(out)
elif self.with_modulated_dcn:
offset_mask = self.conv2_offset(out)
offset = offset_mask[:, :18, :, :]
mask = offset_mask[:, -9:, :, :].sigmoid()
out = self.conv2(out, offset, mask)
else:
offset = self.conv2_offset(out)
out = self.conv2(out, offset)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000,
dcn=None, stage_with_dcn=(False, False, False, False)):
self.dcn = dcn
self.stage_with_dcn = stage_with_dcn
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(
block, 128, layers[1], stride=2, dcn=dcn)
self.layer3 = self._make_layer(
block, 256, layers[2], stride=2, dcn=dcn)
self.layer4 = self._make_layer(
block, 512, layers[3], stride=2, dcn=dcn)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
self.smooth = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=1)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
if self.dcn is not None:
for m in self.modules():
if isinstance(m, Bottleneck) or isinstance(m, BasicBlock):
if hasattr(m, 'conv2_offset'):
constant_init(m.conv2_offset, 0)
def _make_layer(self, block, planes, blocks, stride=1, dcn=None):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes,
stride, downsample, dcn=dcn))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes, dcn=dcn))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x2 = self.layer1(x)
x3 = self.layer2(x2)
x4 = self.layer3(x3)
x5 = self.layer4(x4)
return x2, x3, x4, x5
The provided code snippet includes necessary dependencies for implementing the `deformable_resnet18` function. Write a Python function `def deformable_resnet18(pretrained=True, **kwargs)` to solve the following problem:
Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Here is the function:
def deformable_resnet18(pretrained=True, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [2, 2, 2, 2],
dcn=dict(modulated=True,
deformable_groups=1,
fallback_on_stride=False),
stage_with_dcn=[False, True, True, True], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(
model_urls['resnet18']), strict=False)
return model | Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,235 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, dcn=None):
super(BasicBlock, self).__init__()
self.with_dcn = dcn is not None
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.with_modulated_dcn = False
if self.with_dcn:
fallback_on_stride = dcn.get('fallback_on_stride', False)
self.with_modulated_dcn = dcn.get('modulated', False)
# self.conv2 = conv3x3(planes, planes)
if not self.with_dcn or fallback_on_stride:
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
padding=1, bias=False)
else:
deformable_groups = dcn.get('deformable_groups', 1)
if not self.with_modulated_dcn:
#from assets.ops.dcn import DeformConv
from ..assets.ops.dcn import DeformConv
conv_op = DeformConv
offset_channels = 18
else:
#from assets.ops.dcn import ModulatedDeformConv
from ..assets.ops.dcn import ModulatedDeformConv
conv_op = ModulatedDeformConv
offset_channels = 27
self.conv2_offset = nn.Conv2d(
planes,
deformable_groups * offset_channels,
kernel_size=3,
padding=1)
self.conv2 = conv_op(
planes,
planes,
kernel_size=3,
padding=1,
deformable_groups=deformable_groups,
bias=False)
self.bn2 = BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
# out = self.conv2(out)
if not self.with_dcn:
out = self.conv2(out)
elif self.with_modulated_dcn:
offset_mask = self.conv2_offset(out)
offset = offset_mask[:, :18, :, :]
mask = offset_mask[:, -9:, :, :].sigmoid()
out = self.conv2(out, offset, mask)
else:
offset = self.conv2_offset(out)
out = self.conv2(out, offset)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000,
dcn=None, stage_with_dcn=(False, False, False, False)):
self.dcn = dcn
self.stage_with_dcn = stage_with_dcn
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(
block, 128, layers[1], stride=2, dcn=dcn)
self.layer3 = self._make_layer(
block, 256, layers[2], stride=2, dcn=dcn)
self.layer4 = self._make_layer(
block, 512, layers[3], stride=2, dcn=dcn)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
self.smooth = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=1)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
if self.dcn is not None:
for m in self.modules():
if isinstance(m, Bottleneck) or isinstance(m, BasicBlock):
if hasattr(m, 'conv2_offset'):
constant_init(m.conv2_offset, 0)
def _make_layer(self, block, planes, blocks, stride=1, dcn=None):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes,
stride, downsample, dcn=dcn))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes, dcn=dcn))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x2 = self.layer1(x)
x3 = self.layer2(x2)
x4 = self.layer3(x3)
x5 = self.layer4(x4)
return x2, x3, x4, x5
The provided code snippet includes necessary dependencies for implementing the `resnet34` function. Write a Python function `def resnet34(pretrained=True, **kwargs)` to solve the following problem:
Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Here is the function:
def resnet34(pretrained=True, **kwargs):
"""Constructs a ResNet-34 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(
model_urls['resnet34']), strict=False)
return model | Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,236 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, dcn=None):
super(Bottleneck, self).__init__()
self.with_dcn = dcn is not None
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = BatchNorm2d(planes)
fallback_on_stride = False
self.with_modulated_dcn = False
if self.with_dcn:
fallback_on_stride = dcn.get('fallback_on_stride', False)
self.with_modulated_dcn = dcn.get('modulated', False)
if not self.with_dcn or fallback_on_stride:
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
stride=stride, padding=1, bias=False)
else:
deformable_groups = dcn.get('deformable_groups', 1)
if not self.with_modulated_dcn:
#from assets.ops.dcn import DeformConv
from ..assets.ops.dcn import DeformConv
conv_op = DeformConv
offset_channels = 18
else:
#from assets.ops.dcn import ModulatedDeformConv
from ..assets.ops.dcn import ModulatedDeformConv
conv_op = ModulatedDeformConv
offset_channels = 27
self.conv2_offset = nn.Conv2d(
planes, deformable_groups * offset_channels,
kernel_size=3,
padding=1)
self.conv2 = conv_op(
planes, planes, kernel_size=3, padding=1, stride=stride,
deformable_groups=deformable_groups, bias=False)
self.bn2 = BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
self.bn3 = BatchNorm2d(planes * 4)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.dcn = dcn
self.with_dcn = dcn is not None
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
# out = self.conv2(out)
if not self.with_dcn:
out = self.conv2(out)
elif self.with_modulated_dcn:
offset_mask = self.conv2_offset(out)
offset = offset_mask[:, :18, :, :]
mask = offset_mask[:, -9:, :, :].sigmoid()
out = self.conv2(out, offset, mask)
else:
offset = self.conv2_offset(out)
out = self.conv2(out, offset)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000,
dcn=None, stage_with_dcn=(False, False, False, False)):
self.dcn = dcn
self.stage_with_dcn = stage_with_dcn
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(
block, 128, layers[1], stride=2, dcn=dcn)
self.layer3 = self._make_layer(
block, 256, layers[2], stride=2, dcn=dcn)
self.layer4 = self._make_layer(
block, 512, layers[3], stride=2, dcn=dcn)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
self.smooth = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=1)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
if self.dcn is not None:
for m in self.modules():
if isinstance(m, Bottleneck) or isinstance(m, BasicBlock):
if hasattr(m, 'conv2_offset'):
constant_init(m.conv2_offset, 0)
def _make_layer(self, block, planes, blocks, stride=1, dcn=None):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes,
stride, downsample, dcn=dcn))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes, dcn=dcn))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x2 = self.layer1(x)
x3 = self.layer2(x2)
x4 = self.layer3(x3)
x5 = self.layer4(x4)
return x2, x3, x4, x5
The provided code snippet includes necessary dependencies for implementing the `resnet50` function. Write a Python function `def resnet50(pretrained=True, **kwargs)` to solve the following problem:
Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Here is the function:
def resnet50(pretrained=True, **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(
model_urls['resnet50']), strict=False)
return model | Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,237 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, dcn=None):
super(Bottleneck, self).__init__()
self.with_dcn = dcn is not None
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = BatchNorm2d(planes)
fallback_on_stride = False
self.with_modulated_dcn = False
if self.with_dcn:
fallback_on_stride = dcn.get('fallback_on_stride', False)
self.with_modulated_dcn = dcn.get('modulated', False)
if not self.with_dcn or fallback_on_stride:
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
stride=stride, padding=1, bias=False)
else:
deformable_groups = dcn.get('deformable_groups', 1)
if not self.with_modulated_dcn:
#from assets.ops.dcn import DeformConv
from ..assets.ops.dcn import DeformConv
conv_op = DeformConv
offset_channels = 18
else:
#from assets.ops.dcn import ModulatedDeformConv
from ..assets.ops.dcn import ModulatedDeformConv
conv_op = ModulatedDeformConv
offset_channels = 27
self.conv2_offset = nn.Conv2d(
planes, deformable_groups * offset_channels,
kernel_size=3,
padding=1)
self.conv2 = conv_op(
planes, planes, kernel_size=3, padding=1, stride=stride,
deformable_groups=deformable_groups, bias=False)
self.bn2 = BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
self.bn3 = BatchNorm2d(planes * 4)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.dcn = dcn
self.with_dcn = dcn is not None
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
# out = self.conv2(out)
if not self.with_dcn:
out = self.conv2(out)
elif self.with_modulated_dcn:
offset_mask = self.conv2_offset(out)
offset = offset_mask[:, :18, :, :]
mask = offset_mask[:, -9:, :, :].sigmoid()
out = self.conv2(out, offset, mask)
else:
offset = self.conv2_offset(out)
out = self.conv2(out, offset)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000,
dcn=None, stage_with_dcn=(False, False, False, False)):
self.dcn = dcn
self.stage_with_dcn = stage_with_dcn
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(
block, 128, layers[1], stride=2, dcn=dcn)
self.layer3 = self._make_layer(
block, 256, layers[2], stride=2, dcn=dcn)
self.layer4 = self._make_layer(
block, 512, layers[3], stride=2, dcn=dcn)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
self.smooth = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=1)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
if self.dcn is not None:
for m in self.modules():
if isinstance(m, Bottleneck) or isinstance(m, BasicBlock):
if hasattr(m, 'conv2_offset'):
constant_init(m.conv2_offset, 0)
def _make_layer(self, block, planes, blocks, stride=1, dcn=None):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes,
stride, downsample, dcn=dcn))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes, dcn=dcn))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x2 = self.layer1(x)
x3 = self.layer2(x2)
x4 = self.layer3(x3)
x5 = self.layer4(x4)
return x2, x3, x4, x5
The provided code snippet includes necessary dependencies for implementing the `deformable_resnet50` function. Write a Python function `def deformable_resnet50(pretrained=True, **kwargs)` to solve the following problem:
Constructs a ResNet-50 model with deformable conv. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Here is the function:
def deformable_resnet50(pretrained=True, **kwargs):
"""Constructs a ResNet-50 model with deformable conv.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 6, 3],
dcn=dict(modulated=True,
deformable_groups=1,
fallback_on_stride=False),
stage_with_dcn=[False, True, True, True],
**kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(
model_urls['resnet50']), strict=False)
return model | Constructs a ResNet-50 model with deformable conv. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,238 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, dcn=None):
super(Bottleneck, self).__init__()
self.with_dcn = dcn is not None
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = BatchNorm2d(planes)
fallback_on_stride = False
self.with_modulated_dcn = False
if self.with_dcn:
fallback_on_stride = dcn.get('fallback_on_stride', False)
self.with_modulated_dcn = dcn.get('modulated', False)
if not self.with_dcn or fallback_on_stride:
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
stride=stride, padding=1, bias=False)
else:
deformable_groups = dcn.get('deformable_groups', 1)
if not self.with_modulated_dcn:
#from assets.ops.dcn import DeformConv
from ..assets.ops.dcn import DeformConv
conv_op = DeformConv
offset_channels = 18
else:
#from assets.ops.dcn import ModulatedDeformConv
from ..assets.ops.dcn import ModulatedDeformConv
conv_op = ModulatedDeformConv
offset_channels = 27
self.conv2_offset = nn.Conv2d(
planes, deformable_groups * offset_channels,
kernel_size=3,
padding=1)
self.conv2 = conv_op(
planes, planes, kernel_size=3, padding=1, stride=stride,
deformable_groups=deformable_groups, bias=False)
self.bn2 = BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
self.bn3 = BatchNorm2d(planes * 4)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.dcn = dcn
self.with_dcn = dcn is not None
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
# out = self.conv2(out)
if not self.with_dcn:
out = self.conv2(out)
elif self.with_modulated_dcn:
offset_mask = self.conv2_offset(out)
offset = offset_mask[:, :18, :, :]
mask = offset_mask[:, -9:, :, :].sigmoid()
out = self.conv2(out, offset, mask)
else:
offset = self.conv2_offset(out)
out = self.conv2(out, offset)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000,
dcn=None, stage_with_dcn=(False, False, False, False)):
self.dcn = dcn
self.stage_with_dcn = stage_with_dcn
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(
block, 128, layers[1], stride=2, dcn=dcn)
self.layer3 = self._make_layer(
block, 256, layers[2], stride=2, dcn=dcn)
self.layer4 = self._make_layer(
block, 512, layers[3], stride=2, dcn=dcn)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
self.smooth = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=1)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
if self.dcn is not None:
for m in self.modules():
if isinstance(m, Bottleneck) or isinstance(m, BasicBlock):
if hasattr(m, 'conv2_offset'):
constant_init(m.conv2_offset, 0)
def _make_layer(self, block, planes, blocks, stride=1, dcn=None):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes,
stride, downsample, dcn=dcn))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes, dcn=dcn))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x2 = self.layer1(x)
x3 = self.layer2(x2)
x4 = self.layer3(x3)
x5 = self.layer4(x4)
return x2, x3, x4, x5
The provided code snippet includes necessary dependencies for implementing the `resnet101` function. Write a Python function `def resnet101(pretrained=True, **kwargs)` to solve the following problem:
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Here is the function:
def resnet101(pretrained=True, **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(
model_urls['resnet101']), strict=False)
return model | Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,239 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, dcn=None):
super(Bottleneck, self).__init__()
self.with_dcn = dcn is not None
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = BatchNorm2d(planes)
fallback_on_stride = False
self.with_modulated_dcn = False
if self.with_dcn:
fallback_on_stride = dcn.get('fallback_on_stride', False)
self.with_modulated_dcn = dcn.get('modulated', False)
if not self.with_dcn or fallback_on_stride:
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
stride=stride, padding=1, bias=False)
else:
deformable_groups = dcn.get('deformable_groups', 1)
if not self.with_modulated_dcn:
#from assets.ops.dcn import DeformConv
from ..assets.ops.dcn import DeformConv
conv_op = DeformConv
offset_channels = 18
else:
#from assets.ops.dcn import ModulatedDeformConv
from ..assets.ops.dcn import ModulatedDeformConv
conv_op = ModulatedDeformConv
offset_channels = 27
self.conv2_offset = nn.Conv2d(
planes, deformable_groups * offset_channels,
kernel_size=3,
padding=1)
self.conv2 = conv_op(
planes, planes, kernel_size=3, padding=1, stride=stride,
deformable_groups=deformable_groups, bias=False)
self.bn2 = BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
self.bn3 = BatchNorm2d(planes * 4)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.dcn = dcn
self.with_dcn = dcn is not None
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
# out = self.conv2(out)
if not self.with_dcn:
out = self.conv2(out)
elif self.with_modulated_dcn:
offset_mask = self.conv2_offset(out)
offset = offset_mask[:, :18, :, :]
mask = offset_mask[:, -9:, :, :].sigmoid()
out = self.conv2(out, offset, mask)
else:
offset = self.conv2_offset(out)
out = self.conv2(out, offset)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000,
dcn=None, stage_with_dcn=(False, False, False, False)):
self.dcn = dcn
self.stage_with_dcn = stage_with_dcn
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(
block, 128, layers[1], stride=2, dcn=dcn)
self.layer3 = self._make_layer(
block, 256, layers[2], stride=2, dcn=dcn)
self.layer4 = self._make_layer(
block, 512, layers[3], stride=2, dcn=dcn)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
self.smooth = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=1)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
if self.dcn is not None:
for m in self.modules():
if isinstance(m, Bottleneck) or isinstance(m, BasicBlock):
if hasattr(m, 'conv2_offset'):
constant_init(m.conv2_offset, 0)
def _make_layer(self, block, planes, blocks, stride=1, dcn=None):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes,
stride, downsample, dcn=dcn))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes, dcn=dcn))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x2 = self.layer1(x)
x3 = self.layer2(x2)
x4 = self.layer3(x3)
x5 = self.layer4(x4)
return x2, x3, x4, x5
The provided code snippet includes necessary dependencies for implementing the `resnet152` function. Write a Python function `def resnet152(pretrained=True, **kwargs)` to solve the following problem:
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Here is the function:
def resnet152(pretrained=True, **kwargs):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(
model_urls['resnet152']), strict=False)
return model | Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
1,240 | import os
import torch
import warnings
from torch.autograd import Function
from torch.nn.modules.utils import _pair
from torch.utils import cpp_extension
def custom_formatwarning(msg, *args, **kwargs):
# ignore everything except the message
return str(msg) + '\n' | null |
1,241 | import os
import warnings
import torch
from torch.autograd import Function
from torch.utils import cpp_extension
def custom_formatwarning(msg, *args, **kwargs):
# ignore everything except the message
return str(msg) + '\n' | null |
1,242 | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from .. import backbones
from .. import decoders
def parallelize(model, distributed, local_rank):
if distributed:
return nn.parallel.DistributedDataParallel(
model,
device_ids=[local_rank],
output_device=[local_rank],
find_unused_parameters=True)
else:
return nn.DataParallel(model) | null |
1,243 | import torch
import torch.nn as nn
import torch.nn.init as init
import torchvision
from torchvision import models
from collections import namedtuple
from packaging import version
def init_weights(modules):
for m in modules:
if isinstance(m, nn.Conv2d):
init.xavier_uniform_(m.weight.data)
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.weight.data.normal_(0, 0.01)
m.bias.data.zero_() | null |
1,244 | import os
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from .DBNet.DBNet import DBNet
class DBNet:
def __init__(self,
backbone = "resnet18",
weight_dir = None,
weight_name = 'pretrained',
initialize_model = True,
dynamic_import_relative_path = None,
device = 'cuda',
verbose = 0):
'''
DBNet text detector class
Parameters
----------
backbone : str, optional
Backbone to use. Options are "resnet18" and "resnet50". The default is "resnet18".
weight_dir : str, optional
Path to directory that contains weight files. If set to None, the path will be set
to "../weights/". The default is None.
weight_name : str, optional
Name of the weight to use as specified in DBNet_inference.yaml or a filename
in weight_dir. The default is 'pretrained'.
initialize_model : Boolean, optional
If True, construct the model and load weight at class initialization.
Otherwise, only initial the class without constructing the model.
The default is True.
dynamic_import_relative_path : str, optional
Relative path to 'model/detector.py'. This option is for supporting
integrating this module into other modules. For example, easyocr/DBNet
This should be left as None when calling this module as a standalone.
The default is None.
device : str, optional
Device to use. Options are "cuda" and "cpu". The default is 'cuda'.
verbose : int, optional
Verbosity level. The default is 0.
Raises
------
ValueError
Raised when backbone is invalid.
FileNotFoundError
Raised when weight file is not found.
Returns
-------
None.
'''
self.device = device
config_path = os.path.join(os.path.dirname(__file__), "configs", "DBNet_inference.yaml")
with open(config_path, 'r') as fid:
self.configs = yaml.safe_load(fid)
if dynamic_import_relative_path is not None:
self.configs = self.set_relative_import_path(self.configs, dynamic_import_relative_path)
if backbone in self.configs.keys():
self.backbone = backbone
else:
raise ValueError("Invalid backbone. Current support backbone are {}.".format(",".join(self.configs.keys())))
if weight_dir is not None:
self.weight_dir = weight_dir
else:
self.weight_dir = os.path.join(os.path.dirname(__file__), 'weights')
if initialize_model:
if weight_name in self.configs[backbone]['weight'].keys():
weight_path = os.path.join(self.weight_dir, self.configs[backbone]['weight'][weight_name])
error_message = "A weight with a name {} is found in DBNet_inference.yaml but cannot be find file: {}."
else:
weight_path = os.path.join(self.weight_dir, weight_name)
error_message = "A weight with a name {} is not found in DBNet_inference.yaml and cannot be find file: {}."
if not os.path.isfile(weight_path):
raise FileNotFoundError(error_message.format(weight_name, weight_path))
self.initialize_model(self.configs[backbone]['model'], weight_path)
else:
self.model = None
self.BGR_MEAN = np.array(self.configs['BGR_MEAN'])
self.min_detection_size = self.configs['min_detection_size']
self.max_detection_size = self.configs['max_detection_size']
def set_relative_import_path(self, configs, dynamic_import_relative_path):
'''
Create relative import paths for modules specified in class. This method
is recursive.
Parameters
----------
configs : dict
Configuration dictionary from .yaml file.
dynamic_import_relative_path : str, optional
Relative path to 'model/detector/'. This option is for supporting
integrating this module into other modules. For example, easyocr/DBNet
This should be left as None when calling this module as a standalone.
The default is None.
Returns
-------
configs : dict
Configuration dictionary with correct relative path.
'''
assert dynamic_import_relative_path is not None
prefices = dynamic_import_relative_path.split(os.sep)
for key,value in configs.items():
if key == 'class':
configs.update({key: ".".join(prefices + value.split("."))})
else:
if isinstance(value, dict):
value = self.set_relative_import_path(value, dynamic_import_relative_path)
else:
pass
return configs
def load_weight(self, weight_path):
'''
Load weight to model.
Parameters
----------
weight_path : str
Path to trained weight.
Raises
------
RuntimeError
Raised when the model has not yet been contructed.
Returns
-------
None.
'''
if self.model is None:
raise RuntimeError("model has not yet been constructed.")
self.model.load_state_dict(torch.load(weight_path, map_location=self.device), strict=False)
self.model.eval()
def construct_model(self, config):
'''
Contruct text detection model based on the configuration in .yaml file.
Parameters
----------
config : dict
Configuration dictionary.
Returns
-------
None.
'''
self.model = Configurable.construct_class_from_config(config).structure.builder.build(self.device)
def initialize_model(self, model_config, weight_path):
'''
Wrapper to initialize text detection model. This model includes contructing
and weight loading.
Parameters
----------
model_config : dict
Configuration dictionary.
weight_path : str
Path to trained weight.
Returns
-------
None.
'''
self.construct_model(model_config)
self.load_weight(weight_path)
if isinstance(self.model.model, torch.nn.DataParallel) and self.device == 'cpu':
self.model.model = self.model.model.module.to(self.device)
def get_cv2_image(self, image):
'''
Load or convert input to OpenCV BGR image numpy array.
Parameters
----------
image : str, PIL.Image, or np.ndarray
Image to load or convert.
Raises
------
FileNotFoundError
Raised when the input is a path to file (str), but the file is not found.
TypeError
Raised when the data type of the input is not supported.
Returns
-------
image : np.ndarray
OpenCV BGR image.
'''
if isinstance(image, str):
if os.path.isfile(image):
image = cv2.imread(image, cv2.IMREAD_COLOR).astype('float32')
else:
raise FileNotFoundError("Cannot find {}".format(image))
elif isinstance(image, np.ndarray):
image = image.astype('float32')
elif isinstance(image, PIL.Image.Image):
image = np.asarray(image)[:, :, ::-1]
else:
raise TypeError("Unsupport image format. Only path-to-file, opencv BGR image, and PIL image are supported.")
return image
def resize_image(self, img, detection_size = None):
'''
Resize image such that the shorter side of the image is equal to the
closest multiple of 32 to the provided detection_size. If detection_size
is not provided, it will be resized to the closest multiple of 32 each
side. If the original size exceeds the min-/max-detection sizes
(specified in configs.yaml), it will be resized to be within the
min-/max-sizes.
Parameters
----------
img : np.ndarray
OpenCV BGR image.
detection_size : int, optional
Target detection size. The default is None.
Returns
-------
np.ndarray
Resized OpenCV BGR image. The width and height of this image should
be multiple of 32.
'''
height, width, _ = img.shape
if detection_size is None:
detection_size = max(self.min_detection_size, min(height, width, self.max_detection_size))
if height < width:
new_height = int(math.ceil(detection_size / 32) * 32)
new_width = int(math.ceil(new_height / height * width / 32) * 32)
else:
new_width = int(math.ceil(detection_size / 32) * 32)
new_height = int(math.ceil(new_width / width * height / 32) * 32)
resized_img = cv2.resize(img, (new_width, new_height))
return resized_img, (height, width)
def image_array2tensor(self, image):
'''
Convert image array (assuming OpenCV BGR format) to image tensor.
Parameters
----------
image : np.ndarray
OpenCV BGR image.
Returns
-------
torch.tensor
Tensor image with 4 dimension [batch, channel, width, height].
'''
return torch.from_numpy(image).permute(2, 0, 1).float().unsqueeze(0)
def normalize_image(self, image):
'''
Normalize image by substracting BGR mean and divided by 255
Parameters
----------
image : np.ndarray
OpenCV BGR image.
Returns
-------
np.ndarray
OpenCV BGR image.
'''
return (image - self.BGR_MEAN)/255.0
def load_image(self, image_path, detection_size = 0):
'''
Wrapper to load and convert an image to an image tensor
Parameters
----------
image : path-to-file, PIL.Image, or np.ndarray
Image to load or convert.
detection_size : int, optional
Target detection size. The default is None.
Returns
-------
img : torch.tensor
Tensor image with 4 dimension [batch, channel, width, height]..
original_shape : tuple
A tuple (height, width) of the original input image before resizing.
'''
img =self.get_cv2_image(image_path)
img, original_shape = self.resize_image(img, detection_size = detection_size)
img = self.normalize_image(img)
img = self.image_array2tensor(img)
return img, original_shape
def load_images(self, images, detection_size = None):
'''
Wrapper to load or convert list of multiple images to a single image
tensor. Multiple images are concatenated together on the first dimension.
Parameters
----------
images : a list of path-to-file, PIL.Image, or np.ndarray
Image to load or convert.
detection_size : int, optional
Target detection size. The default is None.
Returns
-------
img : torch.tensor
A single tensor image with 4 dimension [batch, channel, width, height].
original_shape : tuple
A list of tuples (height, width) of the original input image before resizing.
'''
images, original_shapes = zip(*[self.load_image(image, detection_size = detection_size)
for image in images])
return torch.cat(images, dim = 0), original_shapes
def hmap2bbox(self,
image_tensor,
original_shapes,
hmap,
text_threshold = 0.2,
bbox_min_score = 0.2,
bbox_min_size = 3,
max_candidates = 0,
as_polygon=False):
'''
Translate probability heatmap tensor to text region boudning boxes.
Parameters
----------
image_tensor : torch.tensor
Image tensor.
original_shapes : tuple
Original size of the image (height, width) of the input image (before
rounded to the closest multiple of 32).
hmap : torch.tensor
Probability heatmap tensor.
text_threshold : float, optional
Minimum probability for each pixel of heatmap tensor to be considered
as a valid text pixel. The default is 0.2.
bbox_min_score : float, optional
Minimum score for each detected bounding box to be considered as a
valid text bounding box. The default is 0.2.
bbox_min_size : int, optional
Minimum size for each detected bounding box to be considered as a
valid text bounding box. The default is 3.
max_candidates : int, optional
Maximum number of detected bounding boxes to be considered as
candidates for valid text bounding box. Setting it to 0 implies
no maximum. The default is 0.
as_polygon : boolean, optional
If True, return the bounding box as polygon (fine vertrices),
otherwise return as rectangular. The default is False.
Returns
-------
boxes_batch : list of lists
Bounding boxes of each text box.
scores_batch : list of floats
Confidence scores of each text box.
'''
segmentation = self.binarize(hmap, threshold = text_threshold)
boxes_batch = []
scores_batch = []
for batch_index in range(image_tensor.size(0)):
height, width = original_shapes[batch_index]
if as_polygon:
boxes, scores = self.polygons_from_bitmap(
hmap[batch_index],
segmentation[batch_index],
width,
height,
bbox_min_score = bbox_min_score,
bbox_min_size = bbox_min_size,
max_candidates = max_candidates)
else:
boxes, scores = self.boxes_from_bitmap(
hmap[batch_index],
segmentation[batch_index],
width,
height,
bbox_min_score = bbox_min_score,
bbox_min_size = bbox_min_size,
max_candidates = max_candidates)
boxes_batch.append(boxes)
scores_batch.append(scores)
boxes_batch, scores_batch = zip(*[zip(*[(box, score)
for (box,score) in zip(boxes, scores) if score > 0]
) if any(scores > 0) else [(),()]
for (boxes, scores) in zip(boxes_batch, scores_batch)]
)
return boxes_batch, scores_batch
def binarize(self, tensor, threshold):
'''
Apply threshold to return boolean tensor.
Parameters
----------
tensor : torch.tensor
input tensor.
threshold : float
Threshold.
Returns
-------
torch.tensor
Boolean tensor.
'''
return tensor > threshold
def polygons_from_bitmap(self,
hmap,
segmentation,
dest_width,
dest_height,
bbox_min_score = 0.2,
bbox_min_size = 3,
max_candidates = 0):
'''
Translate boolean tensor to fine polygon indicating text bounding boxes
Parameters
----------
hmap : torch.tensor
Probability heatmap tensor.
segmentation : torch.tensor
Segmentataion tensor.
dest_width : TYPE
target width of the output.
dest_height : TYPE
target width of the output.
bbox_min_score : float, optional
Minimum score for each detected bounding box to be considered as a
valid text bounding box. The default is 0.2.
bbox_min_size : int, optional
Minimum size for each detected bounding box to be considered as a
valid text bounding box. The default is 3.
max_candidates : int, optional
Maximum number of detected bounding boxes to be considered as
candidates for valid text bounding box. Setting it to 0 implies
no maximum. The default is 0.
Returns
-------
boxes_batch : list of lists
Polygon bounding boxes of each text box.
scores_batch : list of floats
Confidence scores of each text box.
'''
assert segmentation.size(0) == 1
bitmap = segmentation.cpu().numpy()[0] # The first channel
hmap = hmap.cpu().detach().numpy()[0]
height, width = bitmap.shape
boxes = []
scores = []
contours, _ = cv2.findContours(
(bitmap*255).astype(np.uint8),
cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
if max_candidates > 0:
contours = contours[:max_candidates]
for contour in contours:
epsilon = 0.002 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
points = approx.reshape((-1, 2))
if points.shape[0] < 4:
continue
score = self.box_score_fast(hmap, points.reshape(-1, 2))
if score < bbox_min_score:
continue
if points.shape[0] > 2:
box = self.unclip(points, unclip_ratio=2.0)
if len(box) > 1:
continue
else:
continue
box = box.reshape(-1, 2)
_, sside = self.get_mini_boxes(box.reshape((-1, 1, 2)))
if sside < bbox_min_size + 2:
continue
if not isinstance(dest_width, int):
dest_width = dest_width.item()
dest_height = dest_height.item()
box[:, 0] = np.clip(
np.round(box[:, 0] / width * dest_width), 0, dest_width)
box[:, 1] = np.clip(
np.round(box[:, 1] / height * dest_height), 0, dest_height)
boxes.append(box.tolist())
scores.append(score)
return boxes, scores
def boxes_from_bitmap(self,
hmap,
segmentation,
dest_width,
dest_height,
bbox_min_score = 0.2,
bbox_min_size = 3,
max_candidates = 0):
'''
Translate boolean tensor to fine polygon indicating text bounding boxes
Parameters
----------
hmap : torch.tensor
Probability heatmap tensor.
segmentation : torch.tensor
Segmentataion tensor.
dest_width : TYPE
target width of the output.
dest_height : TYPE
target width of the output.
bbox_min_score : float, optional
Minimum score for each detected bounding box to be considered as a
valid text bounding box. The default is 0.2.
bbox_min_size : int, optional
Minimum size for each detected bounding box to be considered as a
valid text bounding box. The default is 3.
max_candidates : int, optional
Maximum number of detected bounding boxes to be considered as
candidates for valid text bounding box. Setting it to 0 implies
no maximum. The default is 0.
Returns
-------
boxes_batch : list of lists
Polygon bounding boxes of each text box.
scores_batch : list of floats
Confidence scores of each text box.
'''
assert segmentation.size(0) == 1
bitmap = segmentation.cpu().numpy()[0] # The first channel
hmap = hmap.cpu().detach().numpy()[0]
height, width = bitmap.shape
contours, _ = cv2.findContours(
(bitmap*255).astype(np.uint8),
cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
if max_candidates > 0:
num_contours = min(len(contours), max_candidates)
else:
num_contours = len(contours)
boxes = np.zeros((num_contours, 4, 2), dtype=np.int16)
scores = np.zeros((num_contours,), dtype=np.float32)
for index in range(num_contours):
contour = contours[index]
points, sside = self.get_mini_boxes(contour)
if sside < bbox_min_size:
continue
points = np.array(points)
score = self.box_score_fast(hmap, points.reshape(-1, 2))
if score < bbox_min_score:
continue
box = self.unclip(points).reshape(-1, 1, 2)
box, sside = self.get_mini_boxes(box)
if sside < bbox_min_size + 2:
continue
box = np.array(box)
if not isinstance(dest_width, int):
dest_width = dest_width.item()
dest_height = dest_height.item()
box[:, 0] = np.clip(
np.round(box[:, 0] / width * dest_width), 0, dest_width)
box[:, 1] = np.clip(
np.round(box[:, 1] / height * dest_height), 0, dest_height)
boxes[index, :, :] = box.astype(np.int16)
scores[index] = score
return boxes.tolist(), scores
def unclip(self, box, unclip_ratio=1.5):
poly = Polygon(box)
distance = poly.area * unclip_ratio / poly.length
offset = pyclipper.PyclipperOffset()
offset.AddPath(box, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
expanded = np.array(offset.Execute(distance))
return expanded
def get_mini_boxes(self, contour):
bounding_box = cv2.minAreaRect(contour)
points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])
index_1, index_2, index_3, index_4 = 0, 1, 2, 3
if points[1][1] > points[0][1]:
index_1 = 0
index_4 = 1
else:
index_1 = 1
index_4 = 0
if points[3][1] > points[2][1]:
index_2 = 2
index_3 = 3
else:
index_2 = 3
index_3 = 2
box = [points[index_1], points[index_2],
points[index_3], points[index_4]]
return box, min(bounding_box[1])
def box_score_fast(self, hmap, box_):
'''
Calculate total score of each bounding box
Parameters
----------
hmap : torch.tensor
Probability heatmap tensor.
box_ : list
Rectanguar bounding box.
Returns
-------
float
Confidence score.
'''
h, w = hmap.shape[:2]
box = box_.copy()
xmin = np.clip(np.floor(box[:, 0].min()).astype(np.int32), 0, w - 1)
xmax = np.clip(np.ceil(box[:, 0].max()).astype(np.int32), 0, w - 1)
ymin = np.clip(np.floor(box[:, 1].min()).astype(np.int32), 0, h - 1)
ymax = np.clip(np.ceil(box[:, 1].max()).astype(np.int32), 0, h - 1)
mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
box[:, 0] = box[:, 0] - xmin
box[:, 1] = box[:, 1] - ymin
cv2.fillPoly(mask, box.reshape(1, -1, 2).astype(np.int32), 1)
return cv2.mean(hmap[ymin:ymax+1, xmin:xmax+1], mask)[0]
def image2hmap(self, image_tensor):
'''
Run the model to obtain a heatmap tensor from a image tensor. The heatmap
tensor indicates the probability of each pixel being a part of text area.
Parameters
----------
image_tensor : torch.tensor
Image tensor.
Returns
-------
torch.tensor
Probability heatmap tensor.
'''
return self.model.forward(image_tensor, training=False)
def inference(self,
image,
text_threshold = 0.2,
bbox_min_score = 0.2,
bbox_min_size = 3,
max_candidates = 0,
detection_size = None,
as_polygon = False,
return_scores = False):
'''
Wrapper to run the model on an input image to get text bounding boxes.
Parameters
----------
image : path-to-file, PIL.Image, or np.ndarray
Image to load or convert.
text_threshold : float, optional
Minimum probability for each pixel of heatmap tensor to be considered
as a valid text pixel. The default is 0.2.
bbox_min_score : float, optional
Minimum score for each detected bounding box to be considered as a
valid text bounding box. The default is 0.2.
bbox_min_size : int, optional
Minimum size for each detected bounding box to be considered as a
valid text bounding box. The default is 3.
max_candidates : int, optional
Maximum number of detected bounding boxes to be considered as
candidates for valid text bounding box. Setting it to 0 implies
no maximum. The default is 0.
detection_size : int, optional
Target detection size. Please see docstring under method resize_image()
for explanation. The default is None.
as_polygon : boolean, optional
If true, return the bounding boxes as find polygons, otherwise, return
as rectagular. The default is False.
return_scores : boolean, optional
If true, return confidence score along with the text bounding boxes.
The default is False.
Returns
-------
list of lists
Text bounding boxes. If return_scores is set to true, another list
of lists will also be returned.
'''
if not isinstance(image, list):
image = [image]
image_tensor, original_shapes = self.load_images(image, detection_size = detection_size)
with torch.no_grad():
hmap = self.image2hmap(image_tensor)
batch_boxes, batch_scores = self.hmap2bbox(image_tensor,
original_shapes,
hmap,
text_threshold = text_threshold,
bbox_min_score = bbox_min_score,
bbox_min_size = bbox_min_size,
max_candidates = max_candidates,
as_polygon=as_polygon)
if return_scores:
return batch_boxes, batch_scores
else:
return batch_boxes
The provided code snippet includes necessary dependencies for implementing the `get_detector` function. Write a Python function `def get_detector(trained_model, backbone = 'resnet18', device='cpu', quantize=True, cudnn_benchmark=False)` to solve the following problem:
A wrapper to initialize DBNet text detection model Parameters ---------- trained_model : str Path to trained weight to use. backbone : str Backbone to use. Options are 'resnet18' or 'resnet50'. The default is 'resnet18'. device : str, optional Device to use. Options are "cpu" and "cuda". The default is 'cpu'. quantize : boolean, optional If use, apply model quantization method to the model. The default is True. cudnn_benchmark : boolen, optional DESCRIPTION. The default is False. Returns ------- dbnet : obj DBNet text detection object.
Here is the function:
def get_detector(trained_model, backbone = 'resnet18', device='cpu', quantize=True, cudnn_benchmark=False):
'''
A wrapper to initialize DBNet text detection model
Parameters
----------
trained_model : str
Path to trained weight to use.
backbone : str
Backbone to use. Options are 'resnet18' or 'resnet50'. The default is 'resnet18'.
device : str, optional
Device to use. Options are "cpu" and "cuda". The default is 'cpu'.
quantize : boolean, optional
If use, apply model quantization method to the model. The default is True.
cudnn_benchmark : boolen, optional
DESCRIPTION. The default is False.
Returns
-------
dbnet : obj
DBNet text detection object.
'''
dbnet = DBNet(initialize_model = False,
dynamic_import_relative_path = os.path.join("easyocr", "DBNet"),
device = device,
verbose = 0)
if backbone not in ['resnet18', 'resnet50']:
raise ValueError("Invalid backbone. Options are 'resnet18' or 'resnet50'.")
dbnet.initialize_model(dbnet.configs[backbone]['model'],
trained_model)
if torch.device(device).type == 'cpu':
if quantize:
try:
torch.quantization.quantize_dynamic(dbnet, dtype=torch.qint8, inplace=True)
except:
pass
else:
dbnet.model = torch.nn.DataParallel(dbnet.model).to(device)
cudnn.benchmark = cudnn_benchmark
dbnet.model.eval()
return dbnet | A wrapper to initialize DBNet text detection model Parameters ---------- trained_model : str Path to trained weight to use. backbone : str Backbone to use. Options are 'resnet18' or 'resnet50'. The default is 'resnet18'. device : str, optional Device to use. Options are "cpu" and "cuda". The default is 'cpu'. quantize : boolean, optional If use, apply model quantization method to the model. The default is True. cudnn_benchmark : boolen, optional DESCRIPTION. The default is False. Returns ------- dbnet : obj DBNet text detection object. |
1,245 | import os
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from .DBNet.DBNet import DBNet
def test_net(image,
detector,
threshold = 0.2,
bbox_min_score = 0.2,
bbox_min_size = 3,
max_candidates = 0,
canvas_size = None,
poly = False,
device = 'cpu'
):
'''
A wrapper for DBNet inference routine.
Parameters
----------
image : np.ndarray or list of np.ndarray
OpenCV BGR image array or list of it.
detector : obj
DBNet text detection object.
threshold : float, optional
Minimum probability for each pixel of heatmap tensor to be considered
as a valid text pixel. The default is 0.2.
bbox_min_score : float, optional
Minimum score for each detected bounding box to be considered as a
valid text bounding box. The default is 0.2.
bbox_min_size : int, optional
Minimum size for each detected bounding box to be considered as a
valid text bounding box. The default is 3.
max_candidates : int, optional
Maximum number of detected bounding boxes to be considered as
candidates for valid text bounding boxes. Setting to 0 implies
no maximum. The default is 0.
canvas_size : int, optional
Target detection size. Input image will be resized such that it's
shorter side is equal to the closest multiple of 32 to the provided
canvas_size. If detection_size is not provided, it will be resized to
the closest multiple of 32 each side. If the original size exceeds the
min-/max-detection sizes (specified in DBNet_inference.yaml), it will be
resized to be within the min-/max-sizes. The default is None.
poly : boolean, optional
If true, return the bounding boxes as find polygons, otherwise, return
as rectagular. The default is False.
device : str, optional
Device to use. Options are "cpu" and "cuda". The default is 'cpu'.
Returns
-------
bboxes : list of lists
List of text bounding boxes in format [left, right, top, bottom].
polys : list of lists
List of polygon text bounding boxes. If argument poly is set to false,
this output will also hold the value of output bboxes
'''
if isinstance(image, np.ndarray) and len(image.shape) == 4: # image is batch of np arrays
image_arrs = image
else: # image is single numpy array
image_arrs = [image]
# resize
images, original_shapes = zip(*[detector.resize_image(img, canvas_size) for img in image_arrs])
# preprocessing
images = [np.transpose(detector.normalize_image(n_img), (2, 0, 1)) for n_img in images]
image_tensor = torch.from_numpy(np.array(images)).to(device)
# forward pass
with torch.no_grad():
hmap = detector.image2hmap(image_tensor.to(device))
bboxes, _ = detector.hmap2bbox(
image_tensor,
original_shapes,
hmap,
text_threshold = threshold,
bbox_min_score = bbox_min_score,
bbox_min_size = bbox_min_size,
max_candidates = max_candidates,
as_polygon=False)
if poly:
polys, _ = detector.hmap2bbox(
image_tensor,
original_shapes,
hmap,
text_threshold = threshold,
bbox_min_score = bbox_min_score,
bbox_min_size = bbox_min_size,
max_candidates = max_candidates,
as_polygon=True)
else:
polys = bboxes
return bboxes, polys
The provided code snippet includes necessary dependencies for implementing the `get_textbox` function. Write a Python function `def get_textbox(detector, image, canvas_size = None, poly = False, threshold = 0.2, bbox_min_score = 0.2, bbox_min_size = 3, max_candidates = 0, device = 'cpu', **kwargs )` to solve the following problem:
A compatibility wrapper to allow supporting calling this method while providing argument for other detector classes and reformat output accordingly. Parameters ---------- detector : obj DBNet text detection object. image : np.ndarray or list of np.ndarray OpenCV BGR image array or list of it. canvas_size : int, optional Target detection size. Please see docstring under method resize_image() for explanation. The default is None. poly : boolean, optional If true, return the bounding boxes as find polygons, otherwise, return as rectagular. The default is False. threshold : float, optional Minimum probability for each pixel of heatmap tensor to be considered as a valid text pixel. The default is 0.2. bbox_min_score : float, optional Minimum score for each detected bounding box to be considered as a valid text bounding box. The default is 0.2. bbox_min_size : int, optional Minimum size for each detected bounding box to be considered as a valid text bounding box. The default is 3. max_candidates : int, optional Maximum number of detected bounding boxes to be considered as candidates for valid text bounding box. Setting it to 0 implies no maximum. The default is 0. device : str, optional Device to use. Options are "cpu" and "cuda". The default is 'cpu'. **kwargs : keyword arguments Unused. Added to support calling this method while providing argument for other detector class. Returns ------- result : list of lists List of text bounding boxes in format [left, right, top, bottom].
Here is the function:
def get_textbox(detector,
image,
canvas_size = None,
poly = False,
threshold = 0.2,
bbox_min_score = 0.2,
bbox_min_size = 3,
max_candidates = 0,
device = 'cpu',
**kwargs
):
'''
A compatibility wrapper to allow supporting calling this method while
providing argument for other detector classes and reformat output accordingly.
Parameters
----------
detector : obj
DBNet text detection object.
image : np.ndarray or list of np.ndarray
OpenCV BGR image array or list of it.
canvas_size : int, optional
Target detection size. Please see docstring under method resize_image()
for explanation. The default is None.
poly : boolean, optional
If true, return the bounding boxes as find polygons, otherwise, return
as rectagular. The default is False.
threshold : float, optional
Minimum probability for each pixel of heatmap tensor to be considered
as a valid text pixel. The default is 0.2.
bbox_min_score : float, optional
Minimum score for each detected bounding box to be considered as a
valid text bounding box. The default is 0.2.
bbox_min_size : int, optional
Minimum size for each detected bounding box to be considered as a
valid text bounding box. The default is 3.
max_candidates : int, optional
Maximum number of detected bounding boxes to be considered as
candidates for valid text bounding box. Setting it to 0 implies
no maximum. The default is 0.
device : str, optional
Device to use. Options are "cpu" and "cuda". The default is 'cpu'.
**kwargs : keyword arguments
Unused. Added to support calling this method while providing argument
for other detector class.
Returns
-------
result : list of lists
List of text bounding boxes in format [left, right, top, bottom].
'''
if torch.device(device).type != detector.device:
raise RuntimeError(' '.join([
"DBNet detector is initialized with {} device, but detection routine",
"is called with device = {}.",
"To use this detector both have to be the same."
]).format(detector.device, device))
_, polys_list = test_net(image,
detector,
threshold = threshold,
bbox_min_score = bbox_min_score,
bbox_min_size = bbox_min_size,
max_candidates =max_candidates,
canvas_size = canvas_size,
poly = poly,
device = device
)
result = [[np.array(box).astype(np.int32).reshape((-1)) for box in polys] for polys in polys_list]
return result | A compatibility wrapper to allow supporting calling this method while providing argument for other detector classes and reformat output accordingly. Parameters ---------- detector : obj DBNet text detection object. image : np.ndarray or list of np.ndarray OpenCV BGR image array or list of it. canvas_size : int, optional Target detection size. Please see docstring under method resize_image() for explanation. The default is None. poly : boolean, optional If true, return the bounding boxes as find polygons, otherwise, return as rectagular. The default is False. threshold : float, optional Minimum probability for each pixel of heatmap tensor to be considered as a valid text pixel. The default is 0.2. bbox_min_score : float, optional Minimum score for each detected bounding box to be considered as a valid text bounding box. The default is 0.2. bbox_min_size : int, optional Minimum size for each detected bounding box to be considered as a valid text bounding box. The default is 3. max_candidates : int, optional Maximum number of detected bounding boxes to be considered as candidates for valid text bounding box. Setting it to 0 implies no maximum. The default is 0. device : str, optional Device to use. Options are "cpu" and "cuda". The default is 'cpu'. **kwargs : keyword arguments Unused. Added to support calling this method while providing argument for other detector class. Returns ------- result : list of lists List of text bounding boxes in format [left, right, top, bottom]. |
1,246 | import setuptools
import os
import os
requires = """torch>=1.8.0
transformers>=4.10.0
datasets>=1.17.0
sentencepiece>=0.1.96
tqdm>=4.62.2
decorator
rich
web.py
gitpython
scipy # need?
scikit-learn # need?
delta_center_client==0.0.4
bigmodelvis
"""
def get_requirements():
ret = [x for x in requires.split("\n") if len(x)>0]
print("requirements:", ret)
return ret | null |
1,247 | import sys
import datetime
import sphinx_rtd_theme
import doctest
import opendelta
rst_context = {'opendelta': opendelta}
def skip(app, what, name, obj, skip, options):
skip = include_only_tagged(app, what, name, obj, skip, options) or\
skip2(app, what, name, obj, skip, options)
return skip
def setup(app):
def rst_jinja_render(app, docname, source):
src = source[0]
rendered = app.builder.templates.render_string(src, rst_context)
source[0] = rendered
app.connect('autodoc-skip-member', skip)
app.connect("source-read", rst_jinja_render) | null |
1,248 | import torch
import math
def glorot_normal(tensor: torch.Tensor):
return torch.nn.init.xavier_normal_(tensor, gain=math.sqrt(2)) | null |
1,249 | import torch
import math
def glorot_uniform(tensor: torch.Tensor):
return torch.nn.init.xavier_uniform_(tensor, gain=math.sqrt(2)) | null |
1,250 | import torch
import torch.nn as nn
from typing import Union, Optional
import torch.nn.functional as F
import torch
import math
from opendelta.delta_models.layers.init import glorot_uniform, glorot_normal
def kronecker_product(a, b):
"""
Kronecker product of matrices a and b with leading batch dimensions.
Batch dimensions are broadcast. The number of them mush
:type a: torch.Tensor
:type b: torch.Tensor
:rtype: torch.Tensor
"""
#return torch.stack([torch.kron(ai, bi) for ai, bi in zip(a,b)], dim=0)
siz1 = torch.Size(torch.tensor(a.shape[-2:]) * torch.tensor(b.shape[-2:]))
res = a.unsqueeze(-1).unsqueeze(-3) * b.unsqueeze(-2).unsqueeze(-4)
siz0 = res.shape[:-4]
out = res.reshape(siz0 + siz1)
return out
def kronecker_product_einsum_batched(A: torch.Tensor, B: torch.Tensor):
"""
Batched Version of Kronecker Products
:param A: has shape (b, a, c)
:param B: has shape (b, k, p)
:return: (b, ak, cp)
"""
assert A.dim() == 3 and B.dim() == 3
res = torch.einsum('bac,bkp->bakcp', A, B).view(A.size(0),
A.size(1)*B.size(1),
A.size(2)*B.size(2))
return res
The provided code snippet includes necessary dependencies for implementing the `matvec_product` function. Write a Python function `def matvec_product(W: torch.Tensor, x: torch.Tensor, bias: Optional[torch.Tensor], phm_rule, #: Union[torch.Tensor], kronecker_prod=False) -> torch.Tensor` to solve the following problem:
Functional method to compute the generalized matrix-vector product based on the paper "Parameterization of Hypercomplex Multiplications (2020)" https://openreview.net/forum?id=rcQdycl0zyk y = Hx + b , where W is generated through the sum of kronecker products from the Parameterlist W, i.e. W is a an order-3 tensor of size (phm_dim, in_features, out_features) x has shape (batch_size, phm_dim*in_features) phm_rule is an order-3 tensor of shape (phm_dim, phm_dim, phm_dim) H = sum_{i=0}^{d} mul_rule \otimes W[i], where \otimes is the kronecker product
Here is the function:
def matvec_product(W: torch.Tensor, x: torch.Tensor,
bias: Optional[torch.Tensor],
phm_rule, #: Union[torch.Tensor],
kronecker_prod=False) -> torch.Tensor:
"""
Functional method to compute the generalized matrix-vector product based on the paper
"Parameterization of Hypercomplex Multiplications (2020)"
https://openreview.net/forum?id=rcQdycl0zyk
y = Hx + b , where W is generated through the sum of kronecker products from the Parameterlist W, i.e.
W is a an order-3 tensor of size (phm_dim, in_features, out_features)
x has shape (batch_size, phm_dim*in_features)
phm_rule is an order-3 tensor of shape (phm_dim, phm_dim, phm_dim)
H = sum_{i=0}^{d} mul_rule \otimes W[i], where \otimes is the kronecker product
"""
if kronecker_prod:
H = kronecker_product(phm_rule, W).sum(0)
else:
H = kronecker_product_einsum_batched(phm_rule, W).sum(0)
y = torch.matmul(input=x.to(H.dtype), other=H).to(x.dtype)
if bias is not None:
y += bias
return y | Functional method to compute the generalized matrix-vector product based on the paper "Parameterization of Hypercomplex Multiplications (2020)" https://openreview.net/forum?id=rcQdycl0zyk y = Hx + b , where W is generated through the sum of kronecker products from the Parameterlist W, i.e. W is a an order-3 tensor of size (phm_dim, in_features, out_features) x has shape (batch_size, phm_dim*in_features) phm_rule is an order-3 tensor of shape (phm_dim, phm_dim, phm_dim) H = sum_{i=0}^{d} mul_rule \otimes W[i], where \otimes is the kronecker product |
1,251 | from collections import OrderedDict
from multiprocessing.sharedctypes import Value
import os
from opendelta.delta_configs import BaseDeltaConfig
from opendelta.utils.inspect import inspect_module_statistics
from opendelta.utils.model_md5 import gen_model_hash
from opendelta.utils.signature import get_arg_names, signature
from typing import Optional, Union
from opendelta.utils.cuda import get_device
from opendelta.utils.name_based_addressing import *
import torch.nn as nn
import torch
from functools import wraps
from opendelta.utils.decorate import decorate
from opendelta.utils.structure_mapping import transform
from transformers.file_utils import PushToHubMixin
from transformers.deepspeed import deepspeed_config, is_deepspeed_zero3_enabled
from opendelta import SaveLoadMixin
from opendelta import logging
from opendelta.utils.structure_mapping import CommonStructureMap
from opendelta.utils.interactive.web import interactive
from opendelta.utils.data_parallel import new_replicate_for_data_parallel
from opendelta.utils.cuda import move_dict_to_cuda
import sys
from opendelta.utils.data_parallel import caller_map
from opendelta.utils.backend import BackendMapping
The provided code snippet includes necessary dependencies for implementing the `is_leaf_module` function. Write a Python function `def is_leaf_module(module)` to solve the following problem:
r"""Whether the module is a leaf module
Here is the function:
def is_leaf_module(module):
r"""Whether the module is a leaf module
"""
return len([n for n,_ in module.named_children()]) == 0 | r"""Whether the module is a leaf module |
1,252 | from collections import OrderedDict
from multiprocessing.sharedctypes import Value
import os
from opendelta.delta_configs import BaseDeltaConfig
from opendelta.utils.inspect import inspect_module_statistics
from opendelta.utils.model_md5 import gen_model_hash
from opendelta.utils.signature import get_arg_names, signature
from typing import Optional, Union
from opendelta.utils.cuda import get_device
from opendelta.utils.name_based_addressing import *
import torch.nn as nn
import torch
from functools import wraps
from opendelta.utils.decorate import decorate
from opendelta.utils.structure_mapping import transform
from transformers.file_utils import PushToHubMixin
from transformers.deepspeed import deepspeed_config, is_deepspeed_zero3_enabled
from opendelta import SaveLoadMixin
from opendelta import logging
from opendelta.utils.structure_mapping import CommonStructureMap
from opendelta.utils.interactive.web import interactive
from opendelta.utils.data_parallel import new_replicate_for_data_parallel
from opendelta.utils.cuda import move_dict_to_cuda
import sys
from opendelta.utils.data_parallel import caller_map
from opendelta.utils.backend import BackendMapping
def non_module_param(module: nn.Module):
module_names = [n for n, _ in module.named_modules()]
ret = []
for n, p in module.named_parameters():
if not is_child_key(n, module_names):
ret.append((n,p))
return ret | null |
1,253 |
The provided code snippet includes necessary dependencies for implementing the `create_hub_repo_name` function. Write a Python function `def create_hub_repo_name(root = "DeltaHub", dataset = None, delta_type = None, model_name_or_path = None, center_value_only_tags = None, center_key_value_tags = None )` to solve the following problem:
r"""Currently, it's only a simple concatenation of the arguments.
Here is the function:
def create_hub_repo_name(root = "DeltaHub",
dataset = None,
delta_type = None,
model_name_or_path = None,
center_value_only_tags = None,
center_key_value_tags = None
):
r"""Currently, it's only a simple concatenation of the arguments.
"""
repo_name = []
repo_name.append(f"{delta_type}")
model_name_or_path = model_name_or_path.split("/")[-1]
repo_name.append(f"{model_name_or_path}")
repo_name.append(f"{dataset}")
repo_name.extend(list(center_value_only_tags) if center_value_only_tags else [None])
repo_name.extend([f"{k}-{v}" for k,v in center_key_value_tags.items()] if center_key_value_tags else [None])
repo_name = "_".join(repo_name)
repo_name = root+"/"+repo_name
return repo_name | r"""Currently, it's only a simple concatenation of the arguments. |
1,254 | from typing import List, Union
import re
The provided code snippet includes necessary dependencies for implementing the `superstring_in` function. Write a Python function `def superstring_in(str_a: str , list_b: List[str])` to solve the following problem:
r"""check whether there is any string in list b containing str_a. Args: Returns:
Here is the function:
def superstring_in(str_a: str , list_b: List[str]):
r"""check whether there is any string in list b containing str_a.
Args:
Returns:
"""
return any(str_a in str_b for str_b in list_b) | r"""check whether there is any string in list b containing str_a. Args: Returns: |
1,255 | from typing import List, Union
import re
The provided code snippet includes necessary dependencies for implementing the `is_child_key` function. Write a Python function `def is_child_key(str_a: str , list_b: List[str])` to solve the following problem:
r"""check whether a string in ``list_b`` is the child key in ``str_a`` Args: Returns:
Here is the function:
def is_child_key(str_a: str , list_b: List[str]):
r"""check whether a string in ``list_b`` is the child key in ``str_a``
Args:
Returns:
"""
return any(str_b in str_a and (str_b==str_a or str_a[len(str_b)]==".") for str_b in list_b) | r"""check whether a string in ``list_b`` is the child key in ``str_a`` Args: Returns: |
1,256 | from typing import List, Union
import re
def endswith_in_normal(str_a: str , list_b: List[str]):
r"""check whether ``str_a`` has a substring that is in list_b.
Args:
Returns:
"""
return any(str_a.endswith(str_b) and (str_a==str_b or str_a[-len(str_b)-1] == ".") for str_b in list_b)
def endswith_in_regex(str_a: str , list_b: List[str]):
r"""check whether ``str_a`` has a substring that is in list_b.
Args:
Returns:
"""
for str_b in list_b:
ret = re.search(re.compile(str_b), str_a)
if ret is not None:
b = ret.group()
if ret.span()[1] == len(str_a) and (b == str_a or (str_a==b or str_a[-len(b)-1] == ".")):
# the latter is to judge whether it is a full sub key in the str_a, e.g. str_a=`attn.c_attn` and list_b=[`attn`] will given False
return True
return False
def endswith_in(str_a: str, list_b: List[str]):
return endswith_in_regex(str_a, [b[3:] for b in list_b if b.startswith("[r]")]) or \
endswith_in_normal(str_a, [b for b in list_b if not b.startswith("[r]")]) | null |
1,257 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
_lock = threading.Lock()
_default_handler: Optional[logging.Handler] = None
def _get_library_root_logger() -> logging.Logger:
logging.Logger.warning_advice = warning_advice
import logging
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
logging.Logger.warning_advice = warning_advice
def _reset_library_root_logger() -> None:
global _default_handler
with _lock:
if not _default_handler:
return
library_root_logger = _get_library_root_logger()
library_root_logger.removeHandler(_default_handler)
library_root_logger.setLevel(logging.NOTSET)
_default_handler = None | null |
1,258 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
log_levels = {
"debug": logging.DEBUG,
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
"critical": logging.CRITICAL,
}
def get_log_levels_dict():
return log_levels | null |
1,259 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_root_logger() -> logging.Logger:
return logging.getLogger(_get_library_name())
def _configure_library_root_logger() -> None:
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
_default_handler = logging.StreamHandler() # Set sys.stderr as stream.
_default_handler.flush = sys.stderr.flush
formatter = logging.Formatter(
"[%(levelname)s|(OpenDelta)%(module)s:%(lineno)d]%(asctime)s >> %(message)s")
_default_handler.setFormatter(formatter)
# Apply our default configuration to the library root logger.
library_root_logger = _get_library_root_logger()
library_root_logger.addHandler(_default_handler)
library_root_logger.setLevel(_get_default_logging_level())
library_root_logger.propagate = False
The provided code snippet includes necessary dependencies for implementing the `get_verbosity` function. Write a Python function `def get_verbosity() -> int` to solve the following problem:
Return the current level for the 🤗 Transformers's root logger as an int. Returns: :obj:`int`: The logging level. <Tip> 🤗 Transformers has following logging levels: - 50: ``transformers.logging.CRITICAL`` or ``transformers.logging.FATAL`` - 40: ``transformers.logging.ERROR`` - 30: ``transformers.logging.WARNING`` or ``transformers.logging.WARN`` - 20: ``transformers.logging.INFO`` - 10: ``transformers.logging.DEBUG`` </Tip>
Here is the function:
def get_verbosity() -> int:
"""
Return the current level for the 🤗 Transformers's root logger as an int.
Returns:
:obj:`int`: The logging level.
<Tip>
🤗 Transformers has following logging levels:
- 50: ``transformers.logging.CRITICAL`` or ``transformers.logging.FATAL``
- 40: ``transformers.logging.ERROR``
- 30: ``transformers.logging.WARNING`` or ``transformers.logging.WARN``
- 20: ``transformers.logging.INFO``
- 10: ``transformers.logging.DEBUG``
</Tip>"""
_configure_library_root_logger()
return _get_library_root_logger().getEffectiveLevel() | Return the current level for the 🤗 Transformers's root logger as an int. Returns: :obj:`int`: The logging level. <Tip> 🤗 Transformers has following logging levels: - 50: ``transformers.logging.CRITICAL`` or ``transformers.logging.FATAL`` - 40: ``transformers.logging.ERROR`` - 30: ``transformers.logging.WARNING`` or ``transformers.logging.WARN`` - 20: ``transformers.logging.INFO`` - 10: ``transformers.logging.DEBUG`` </Tip> |
1,260 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def set_verbosity(verbosity: int) -> None:
"""
Set the verbosity level for the 🤗 Transformers's root logger.
Args:
verbosity (:obj:`int`):
Logging level, e.g., one of:
- ``transformers.logging.CRITICAL`` or ``transformers.logging.FATAL``
- ``transformers.logging.ERROR``
- ``transformers.logging.WARNING`` or ``transformers.logging.WARN``
- ``transformers.logging.INFO``
- ``transformers.logging.DEBUG``
"""
_configure_library_root_logger()
_get_library_root_logger().setLevel(verbosity)
The provided code snippet includes necessary dependencies for implementing the `set_verbosity_info` function. Write a Python function `def set_verbosity_info()` to solve the following problem:
Set the verbosity to the ``INFO`` level.
Here is the function:
def set_verbosity_info():
"""Set the verbosity to the ``INFO`` level."""
return set_verbosity(INFO) | Set the verbosity to the ``INFO`` level. |
1,261 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def set_verbosity(verbosity: int) -> None:
"""
Set the verbosity level for the 🤗 Transformers's root logger.
Args:
verbosity (:obj:`int`):
Logging level, e.g., one of:
- ``transformers.logging.CRITICAL`` or ``transformers.logging.FATAL``
- ``transformers.logging.ERROR``
- ``transformers.logging.WARNING`` or ``transformers.logging.WARN``
- ``transformers.logging.INFO``
- ``transformers.logging.DEBUG``
"""
_configure_library_root_logger()
_get_library_root_logger().setLevel(verbosity)
The provided code snippet includes necessary dependencies for implementing the `set_verbosity_warning` function. Write a Python function `def set_verbosity_warning()` to solve the following problem:
Set the verbosity to the ``WARNING`` level.
Here is the function:
def set_verbosity_warning():
"""Set the verbosity to the ``WARNING`` level."""
return set_verbosity(WARNING) | Set the verbosity to the ``WARNING`` level. |
1,262 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def set_verbosity(verbosity: int) -> None:
"""
Set the verbosity level for the 🤗 Transformers's root logger.
Args:
verbosity (:obj:`int`):
Logging level, e.g., one of:
- ``transformers.logging.CRITICAL`` or ``transformers.logging.FATAL``
- ``transformers.logging.ERROR``
- ``transformers.logging.WARNING`` or ``transformers.logging.WARN``
- ``transformers.logging.INFO``
- ``transformers.logging.DEBUG``
"""
_configure_library_root_logger()
_get_library_root_logger().setLevel(verbosity)
The provided code snippet includes necessary dependencies for implementing the `set_verbosity_debug` function. Write a Python function `def set_verbosity_debug()` to solve the following problem:
Set the verbosity to the ``DEBUG`` level.
Here is the function:
def set_verbosity_debug():
"""Set the verbosity to the ``DEBUG`` level."""
return set_verbosity(DEBUG) | Set the verbosity to the ``DEBUG`` level. |
1,263 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def set_verbosity(verbosity: int) -> None:
"""
Set the verbosity level for the 🤗 Transformers's root logger.
Args:
verbosity (:obj:`int`):
Logging level, e.g., one of:
- ``transformers.logging.CRITICAL`` or ``transformers.logging.FATAL``
- ``transformers.logging.ERROR``
- ``transformers.logging.WARNING`` or ``transformers.logging.WARN``
- ``transformers.logging.INFO``
- ``transformers.logging.DEBUG``
"""
_configure_library_root_logger()
_get_library_root_logger().setLevel(verbosity)
The provided code snippet includes necessary dependencies for implementing the `set_verbosity_error` function. Write a Python function `def set_verbosity_error()` to solve the following problem:
Set the verbosity to the ``ERROR`` level.
Here is the function:
def set_verbosity_error():
"""Set the verbosity to the ``ERROR`` level."""
return set_verbosity(ERROR) | Set the verbosity to the ``ERROR`` level. |
1,264 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
_default_handler: Optional[logging.Handler] = None
def _get_library_root_logger() -> logging.Logger:
return logging.getLogger(_get_library_name())
def _configure_library_root_logger() -> None:
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
_default_handler = logging.StreamHandler() # Set sys.stderr as stream.
_default_handler.flush = sys.stderr.flush
formatter = logging.Formatter(
"[%(levelname)s|(OpenDelta)%(module)s:%(lineno)d]%(asctime)s >> %(message)s")
_default_handler.setFormatter(formatter)
# Apply our default configuration to the library root logger.
library_root_logger = _get_library_root_logger()
library_root_logger.addHandler(_default_handler)
library_root_logger.setLevel(_get_default_logging_level())
library_root_logger.propagate = False
The provided code snippet includes necessary dependencies for implementing the `disable_default_handler` function. Write a Python function `def disable_default_handler() -> None` to solve the following problem:
Disable the default handler of the HuggingFace Transformers's root logger.
Here is the function:
def disable_default_handler() -> None:
"""Disable the default handler of the HuggingFace Transformers's root logger."""
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().removeHandler(_default_handler) | Disable the default handler of the HuggingFace Transformers's root logger. |
1,265 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
_default_handler: Optional[logging.Handler] = None
def _get_library_root_logger() -> logging.Logger:
return logging.getLogger(_get_library_name())
def _configure_library_root_logger() -> None:
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
_default_handler = logging.StreamHandler() # Set sys.stderr as stream.
_default_handler.flush = sys.stderr.flush
formatter = logging.Formatter(
"[%(levelname)s|(OpenDelta)%(module)s:%(lineno)d]%(asctime)s >> %(message)s")
_default_handler.setFormatter(formatter)
# Apply our default configuration to the library root logger.
library_root_logger = _get_library_root_logger()
library_root_logger.addHandler(_default_handler)
library_root_logger.setLevel(_get_default_logging_level())
library_root_logger.propagate = False
The provided code snippet includes necessary dependencies for implementing the `enable_default_handler` function. Write a Python function `def enable_default_handler() -> None` to solve the following problem:
Enable the default handler of the HuggingFace Transformers's root logger.
Here is the function:
def enable_default_handler() -> None:
"""Enable the default handler of the HuggingFace Transformers's root logger."""
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().addHandler(_default_handler) | Enable the default handler of the HuggingFace Transformers's root logger. |
1,266 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_root_logger() -> logging.Logger:
return logging.getLogger(_get_library_name())
def _configure_library_root_logger() -> None:
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
_default_handler = logging.StreamHandler() # Set sys.stderr as stream.
_default_handler.flush = sys.stderr.flush
formatter = logging.Formatter(
"[%(levelname)s|(OpenDelta)%(module)s:%(lineno)d]%(asctime)s >> %(message)s")
_default_handler.setFormatter(formatter)
# Apply our default configuration to the library root logger.
library_root_logger = _get_library_root_logger()
library_root_logger.addHandler(_default_handler)
library_root_logger.setLevel(_get_default_logging_level())
library_root_logger.propagate = False
logging.Logger.warning_advice = warning_advice
import logging
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
logging.Logger.warning_advice = warning_advice
The provided code snippet includes necessary dependencies for implementing the `add_handler` function. Write a Python function `def add_handler(handler: logging.Handler) -> None` to solve the following problem:
adds a handler to the HuggingFace Transformers's root logger.
Here is the function:
def add_handler(handler: logging.Handler) -> None:
"""adds a handler to the HuggingFace Transformers's root logger."""
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(handler) | adds a handler to the HuggingFace Transformers's root logger. |
1,267 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_root_logger() -> logging.Logger:
return logging.getLogger(_get_library_name())
def _configure_library_root_logger() -> None:
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
_default_handler = logging.StreamHandler() # Set sys.stderr as stream.
_default_handler.flush = sys.stderr.flush
formatter = logging.Formatter(
"[%(levelname)s|(OpenDelta)%(module)s:%(lineno)d]%(asctime)s >> %(message)s")
_default_handler.setFormatter(formatter)
# Apply our default configuration to the library root logger.
library_root_logger = _get_library_root_logger()
library_root_logger.addHandler(_default_handler)
library_root_logger.setLevel(_get_default_logging_level())
library_root_logger.propagate = False
logging.Logger.warning_advice = warning_advice
import logging
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
logging.Logger.warning_advice = warning_advice
The provided code snippet includes necessary dependencies for implementing the `remove_handler` function. Write a Python function `def remove_handler(handler: logging.Handler) -> None` to solve the following problem:
removes given handler from the HuggingFace Transformers's root logger.
Here is the function:
def remove_handler(handler: logging.Handler) -> None:
"""removes given handler from the HuggingFace Transformers's root logger."""
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(handler) | removes given handler from the HuggingFace Transformers's root logger. |
1,268 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_root_logger() -> logging.Logger:
return logging.getLogger(_get_library_name())
def _configure_library_root_logger() -> None:
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
_default_handler = logging.StreamHandler() # Set sys.stderr as stream.
_default_handler.flush = sys.stderr.flush
formatter = logging.Formatter(
"[%(levelname)s|(OpenDelta)%(module)s:%(lineno)d]%(asctime)s >> %(message)s")
_default_handler.setFormatter(formatter)
# Apply our default configuration to the library root logger.
library_root_logger = _get_library_root_logger()
library_root_logger.addHandler(_default_handler)
library_root_logger.setLevel(_get_default_logging_level())
library_root_logger.propagate = False
The provided code snippet includes necessary dependencies for implementing the `disable_propagation` function. Write a Python function `def disable_propagation() -> None` to solve the following problem:
Disable propagation of the library log outputs. Note that log propagation is disabled by default.
Here is the function:
def disable_propagation() -> None:
"""
Disable propagation of the library log outputs. Note that log propagation is disabled by default.
"""
_configure_library_root_logger()
_get_library_root_logger().propagate = False | Disable propagation of the library log outputs. Note that log propagation is disabled by default. |
1,269 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_root_logger() -> logging.Logger:
return logging.getLogger(_get_library_name())
def _configure_library_root_logger() -> None:
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
_default_handler = logging.StreamHandler() # Set sys.stderr as stream.
_default_handler.flush = sys.stderr.flush
formatter = logging.Formatter(
"[%(levelname)s|(OpenDelta)%(module)s:%(lineno)d]%(asctime)s >> %(message)s")
_default_handler.setFormatter(formatter)
# Apply our default configuration to the library root logger.
library_root_logger = _get_library_root_logger()
library_root_logger.addHandler(_default_handler)
library_root_logger.setLevel(_get_default_logging_level())
library_root_logger.propagate = False
The provided code snippet includes necessary dependencies for implementing the `enable_propagation` function. Write a Python function `def enable_propagation() -> None` to solve the following problem:
Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to prevent double logging if the root logger has been configured.
Here is the function:
def enable_propagation() -> None:
"""
Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to
prevent double logging if the root logger has been configured.
"""
_configure_library_root_logger()
_get_library_root_logger().propagate = True | Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to prevent double logging if the root logger has been configured. |
1,270 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_root_logger() -> logging.Logger:
return logging.getLogger(_get_library_name())
logging.Logger.warning_advice = warning_advice
import logging
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
logging.Logger.warning_advice = warning_advice
The provided code snippet includes necessary dependencies for implementing the `enable_explicit_format` function. Write a Python function `def enable_explicit_format() -> None` to solve the following problem:
Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows: ``` [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE ``` All handlers currently bound to the root logger are affected by this method.
Here is the function:
def enable_explicit_format() -> None:
"""
Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows:
```
[LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE
```
All handlers currently bound to the root logger are affected by this method.
"""
handlers = _get_library_root_logger().handlers
for handler in handlers:
formatter = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s")
handler.setFormatter(formatter) | Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows: ``` [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE ``` All handlers currently bound to the root logger are affected by this method. |
1,271 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
def _get_library_root_logger() -> logging.Logger:
return logging.getLogger(_get_library_name())
The provided code snippet includes necessary dependencies for implementing the `reset_format` function. Write a Python function `def reset_format() -> None` to solve the following problem:
Resets the formatting for HuggingFace Transformers's loggers. All handlers currently bound to the root logger are affected by this method.
Here is the function:
def reset_format() -> None:
"""
Resets the formatting for HuggingFace Transformers's loggers.
All handlers currently bound to the root logger are affected by this method.
"""
handlers = _get_library_root_logger().handlers
for handler in handlers:
handler.setFormatter(None) | Resets the formatting for HuggingFace Transformers's loggers. All handlers currently bound to the root logger are affected by this method. |
1,272 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
The provided code snippet includes necessary dependencies for implementing the `warning_advice` function. Write a Python function `def warning_advice(self, *args, **kwargs)` to solve the following problem:
This method is identical to ``logger.warning()``, but if env var TRANSFORMERS_NO_ADVISORY_WARNINGS=1 is set, this warning will not be printed
Here is the function:
def warning_advice(self, *args, **kwargs):
"""
This method is identical to ``logger.warning()``, but if env var TRANSFORMERS_NO_ADVISORY_WARNINGS=1 is set, this
warning will not be printed
"""
no_advisory_warnings = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS", False)
if no_advisory_warnings:
return
self.warning(*args, **kwargs) | This method is identical to ``logger.warning()``, but if env var TRANSFORMERS_NO_ADVISORY_WARNINGS=1 is set, this warning will not be printed |
1,273 | import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
log_levels = {
"debug": logging.DEBUG,
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
"critical": logging.CRITICAL,
}
def _get_library_name() -> str:
return __name__.split(".")[0]
def _configure_library_root_logger() -> None:
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
_default_handler = logging.StreamHandler() # Set sys.stderr as stream.
_default_handler.flush = sys.stderr.flush
formatter = logging.Formatter(
"[%(levelname)s|(OpenDelta)%(module)s:%(lineno)d]%(asctime)s >> %(message)s")
_default_handler.setFormatter(formatter)
# Apply our default configuration to the library root logger.
library_root_logger = _get_library_root_logger()
library_root_logger.addHandler(_default_handler)
library_root_logger.setLevel(_get_default_logging_level())
library_root_logger.propagate = False
logging.Logger.warning_advice = warning_advice
import logging
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
logging.Logger.warning_advice = warning_advice
The provided code snippet includes necessary dependencies for implementing the `get_logger` function. Write a Python function `def get_logger(name: Optional[str] = None, verbosity='info') -> logging.Logger` to solve the following problem:
Return a logger with the specified name. This function is not supposed to be directly accessed unless you are writing a custom transformers module.
Here is the function:
def get_logger(name: Optional[str] = None, verbosity='info') -> logging.Logger:
"""
Return a logger with the specified name.
This function is not supposed to be directly accessed unless you are writing a custom transformers module.
"""
if name is None:
name = _get_library_name()
_configure_library_root_logger()
logger = logging.getLogger(name)
logger.setLevel(log_levels[verbosity])
return logger | Return a logger with the specified name. This function is not supposed to be directly accessed unless you are writing a custom transformers module. |
1,274 | from DeltaCenter import OssClient
from .file_utils import default_cache_path
default_cache_path = "{}/.cache/delta_center/".format(os.path.expanduser('~'))
def download(finetuned_delta_path, cache_dir=None, force_download=False):
if cache_dir is None:
cache_dir = default_cache_path
path_to_unzip_file = OssClient.download(finetuned_delta_path, dest=cache_dir, force_download=force_download)
return path_to_unzip_file | null |
1,275 | from bigmodelvis import Visualization
import web
import re, os
def dfs(o, depth, last, old_name):
html = ""
module_names = expand_part(o.module_name)
if depth > 0:
old_last_1 = last[-1]
if len(module_names) > 1:
module_names = [o.module_name] + module_names
for ith, module_name in enumerate(module_names):
if ith == 0:
html += f'<div>'
elif ith == 1:
html += f'<div class="expandable-sibling">'
for i in range(depth-1):
html += prefix0 if last[i] else prefix1
if depth > 0:
last[-1] = old_last_1 & (ith == 0 or ith == len(module_names)-1)
html += prefix3 if last[-1] else prefix2
length = len(o.children)
if length > 0:
html += f'<button class="collapsible button_inline">[+]</button>'
name = old_name + module_name
if ith > 0:
label = f'[red]{module_name}{o.label[o.label.index("[",1):]}'
else:
label = o.label
html += f'<button class="selectable button_inline" id="{name}">{colorfy(label)}</button>'
if len(module_names) > 1 and ith == 0:
html += '<button class="expandable button_inline">[*]</button>'
html += '<br/>'
html += f'<div class="content">'
for i, child in enumerate(o.children):
last = last + [i == length-1]
html += dfs(child, depth+1, last, name + ".")
last.pop()
html += "</div>"
if ith == 0 or (ith > 1 and ith == len(module_names)-1):
html += "</div>"
return html
app = PortApplication(urls, globals())
names = []
def interactive(model, port=8888):
tree = Visualization(model).structure_graph(printTree=False)
global html
html = dfs(tree, 0, [], "")
print()
print("If on your machine, open the link below for interactive modification.\n "
"If on remote host, you could use port mapping, "
"or run in vscode terminal, which automatically do port mapping for you.")
app.run(port)
global names
print("modified_modules:")
print(names)
return names | null |
1,276 | from typing import OrderedDict
import copy
import opendelta.utils.logging as logging
from bigmodelvis import Visualization
from opendelta.utils.common_structures import CoreMappings
def transform(org_key, mapping, strict=True, warning=False, verbose=False):
chain = org_key.split(".")
query = ""
node = mapping
new_chain = []
virtual_key, virtual_chain, in_virtual_order = None, None, None
for elem in chain:
query += elem
if query in node:
node = node[query]
new_elem = node["__name__"]
if new_elem == "":
if strict:
if warning:
print(f"'{org_key}' has no common mapping.")
return
else:
new_chain.append(query)
else:
splited_new_elem = new_elem.split(".")
splited_new_elem = [e+"@" for e in splited_new_elem]
special_token = '.'.join(splited_new_elem)
if '__virtual__' in node:
virtual_chain = copy.deepcopy(new_chain)
virtual_chain.append(".".join([e+'@' for e in node["__virtual__"].split(".")]))
in_virtual_order = node['__order__']
new_chain.append(special_token) # special token for transformed key
query = ""
elif "$" in node:
node = node["$"]
new_chain.append(query)
query = ""
else:
query += "."
if query!="":
if strict:
if warning:
print("A part of the orginial key hasn't been matched!")
return
else:
new_chain.append(query.strip(".")) # tailing query
new_key = ".".join(new_chain)
if verbose:
print(f"{org_key} => {new_key}")
if virtual_chain is not None:
virtual_key = ".".join(virtual_chain)
return new_key, virtual_key, in_virtual_order | null |
1,277 | from opendelta.utils.decorate import decorate
from collections import OrderedDict
def sequential_caller(_org_func, org_module, delta_name, *args, **kwargs):
args = args[1:] # the first argument here is ``self``
delta_module = getattr(org_module, delta_name)
if hasattr(delta_module, "pre_forward"):
args, kwargs = delta_module.pre_forward(*args, **kwargs)
ret = _org_func(*args, **kwargs)
if hasattr(delta_module, "post_forward"):
ret = delta_module.post_forward(ret)
return ret | null |
1,278 | from opendelta.utils.decorate import decorate
from collections import OrderedDict
def before_caller(_org_func, org_module, delta_name, *args, **kwargs):
args = args[1:] # the first argument here is ``self``
delta_module = getattr(org_module, delta_name)
if hasattr(delta_module, "pre_forward"):
args, kwargs = delta_module.pre_forward(*args, **kwargs)
ret = _org_func(*args, **kwargs)
return ret | null |
1,279 | from opendelta.utils.decorate import decorate
from collections import OrderedDict
def after_caller(_org_func, org_module, delta_name, *args, **kwargs):
args = args[1:] # the first argument here is ``self``
delta_module = getattr(org_module, delta_name)
ret = _org_func(*args, **kwargs)
if hasattr(delta_module, "post_forward"):
ret = delta_module.post_forward(ret)
return ret | null |
1,280 | from opendelta.utils.decorate import decorate
from collections import OrderedDict
def parallel_caller(_org_func, org_module, delta_name, *args, **kwargs):
args = args[1:] # the first argument here is ``self``
delta_module = getattr(org_module, delta_name)
ret_1 = _org_func(*args, **kwargs)
ret_2 = delta_module.forward(*args, **kwargs)
return ret_1 + ret_2 | null |
1,281 | from opendelta.utils.decorate import decorate
from collections import OrderedDict
caller_map = {
"sequential": sequential_caller,
"parallel": parallel_caller,
"before": before_caller,
"after": after_caller,
}
def decorate(func, caller, extras=(), kwsyntax=False):
"""
Decorates a function/generator/coroutine using a caller.
If kwsyntax is True calling the decorated functions with keyword
syntax will pass the named arguments inside the ``kw`` dictionary,
even if such argument are positional, similarly to what functools.wraps
does. By default kwsyntax is False and the the arguments are untouched.
**The difference between this function and decorator.decorate is that
is support nested decorate.
"""
sig = inspect.signature(func)
if iscoroutinefunction(caller):
async def fun(*args, **kw):
if not kwsyntax:
args, kw = fix(args, kw, sig)
return await caller(func, *(extras + args), **kw)
elif isgeneratorfunction(caller):
def fun(*args, **kw):
if not kwsyntax:
args, kw = fix(args, kw, sig)
for res in caller(func, *(extras + args), **kw):
yield res
else:
def fun(*args, **kw):
if not kwsyntax:
args, kw = fix(args, kw, sig)
return caller(func, *(extras + args), **kw)
fun.__name__ = func.__name__
fun.__doc__ = func.__doc__
__wrapped__ = func # support nested wrap
fun.__signature__ = sig
fun.__qualname__ = func.__qualname__
# builtin functions like defaultdict.__setitem__ lack many attributes
try:
fun.__defaults__ = func.__defaults__
except AttributeError:
pass
try:
fun.__kwdefaults__ = func.__kwdefaults__
except AttributeError:
pass
try:
fun.__annotations__ = func.__annotations__
except AttributeError:
pass
try:
fun.__module__ = func.__module__
except AttributeError:
pass
try:
fun.__dict__.update(func.__dict__)
except AttributeError:
pass
fun.__wrapped__ = __wrapped__ # support nested wrap
return fun
The provided code snippet includes necessary dependencies for implementing the `new_replicate_for_data_parallel` function. Write a Python function `def new_replicate_for_data_parallel(self)` to solve the following problem:
r""" self is the parent module.
Here is the function:
def new_replicate_for_data_parallel(self):
r""" self is the parent module.
"""
# rewrite the replicate in DataParallel.
replica = self.__new__(type(self))
org_forward = replica.forward
replica.__dict__ = self.__dict__.copy()
assert replica.forward != org_forward
replica.__dict__['forward'] = org_forward
for _delta_info in self._delta_infos:
if _delta_info['state'] == 'on':
if _delta_info['method'] in caller_map.keys():
caller = caller_map[_delta_info['method']]
new_forward = decorate(replica.forward, caller, extras=(replica, _delta_info['delta_name']), kwsyntax=True)
else:
raise NotImplementedError(f"data_parallel for _delta_info['method']=='{_delta_info['method']}' is not supported")
replica.__dict__['forward'] = new_forward.__get__(replica, type(replica))
# replicas do not have parameters themselves, the replicas reference the original
# module.
replica._parameters = OrderedDict()
replica._buffers = replica._buffers.copy()
replica._modules = replica._modules.copy()
replica._is_replica = True
return replica | r""" self is the parent module. |
1,282 | import inspect
from collections import namedtuple
def signature(f):
r"""Get the function f 's input arguments. A useful gadget
when some function slot might be instantiated into multiple functions.
Args:
f (:obj:`function`) : the function to get the input arguments.
Returns:
namedtuple : of args, default, varargs, keywords, respectively.s
"""
sig = inspect.signature(f)
args = [
p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
]
varargs = [
p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.VAR_POSITIONAL
]
varargs = varargs[0] if varargs else None
keywords = [
p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.VAR_KEYWORD
]
keywords = keywords[0] if keywords else None
defaults = [
p.default for p in sig.parameters.values()
if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
and p.default is not p.empty
] or None
argspec = namedtuple('Signature', ['args', 'defaults',
'varargs', 'keywords'])
return argspec(args, defaults, varargs, keywords)
The provided code snippet includes necessary dependencies for implementing the `get_arg_names` function. Write a Python function `def get_arg_names(f)` to solve the following problem:
r""" Get a functions argument name, remove the ``self`` argument
Here is the function:
def get_arg_names(f):
r""" Get a functions argument name, remove the ``self`` argument
"""
args = signature(f).args
if args[0] == "self":
args = args[1:]
return args | r""" Get a functions argument name, remove the ``self`` argument |
1,283 | import inspect
from collections import namedtuple
The provided code snippet includes necessary dependencies for implementing the `get_arg_names_inside_func` function. Write a Python function `def get_arg_names_inside_func(func)` to solve the following problem:
r""" Get the functions argument name inside the function itself. Remove ``self`` argument.
Here is the function:
def get_arg_names_inside_func(func):
r""" Get the functions argument name inside the function itself. Remove ``self`` argument.
"""
arg_names = func.__code__.co_varnames[: func.__code__.co_argcount]
if arg_names[0] == "self":
arg_names = arg_names[1:]
return arg_names | r""" Get the functions argument name inside the function itself. Remove ``self`` argument. |
1,284 | import hashlib
def gen_parameter_hash(generator, md5=None):
r"""Get parameter hash. From https://zhuanlan.zhihu.com/p/392942816
"""
if md5 is None:
md5 = hashlib.md5()
for arg in generator:
x = arg.data
if hasattr(x, "cpu"):
md5.update(x.cpu().numpy().data.tobytes())
elif hasattr(x, "numpy"):
md5.update(x.numpy().data.tobytes())
elif hasattr(x, "data"):
md5.update(x.data.tobytes())
else:
try:
md5.update(x.encode("utf-8"))
except:
md5.update(str(x).encode("utf-8"))
return md5
The provided code snippet includes necessary dependencies for implementing the `gen_model_hash` function. Write a Python function `def gen_model_hash(model, with_parameters=True)` to solve the following problem:
r"""Get model hash (structure and parameter)
Here is the function:
def gen_model_hash(model, with_parameters=True):
r"""Get model hash (structure and parameter)
"""
str_model_structure = str(model).replace("\n","").replace(" ","").replace("\t","").encode('utf-8')
md5 = hashlib.md5(str_model_structure)
if with_parameters:
md5 = gen_parameter_hash(model.parameters(), md5=md5)
md5_code = md5.hexdigest()
return md5_code | r"""Get model hash (structure and parameter) |
1,285 | import torch
import torch.nn as nn
from typing import Optional
import opendelta.utils.logging as logging
logger = logging.get_logger(__name__)
def num_trainable_parameters(module: Optional[nn.Module]=None):
r"""[NODOC] A small sugar function to get the number of trainable parameter in the backbone model. Often used to
compute the trainable rate.
Args:
module (:obj:`nn.Module`): of which module we want to know the number of trainable paramemters.
Returns:
:obj:`List[nn.Parameter]`
"""
pnum_tot = 0
for param in module.parameters():
if param.requires_grad:
pnum_tot += param.numel()
return pnum_tot
def num_total_parameters(module: Optional[nn.Module]=None):
r"""[NODOC] A small sugar function to get the number of trainable parameter in the backbone model. Often used to
compute the trainable rate.
Args:
module (:obj:`nn.Module`): of which module we want to know the number of trainable paramemters.
Returns:
:obj:`List[nn.Parameter]`
"""
pnum_tot = 0
for param in module.parameters():
pnum_tot += param.numel()
return pnum_tot
def num_delta_parameters(module: Optional[nn.Module]=None):
r"""[NODOC] A small sugar function to get the number of trainable parameter in the backbone model. Often used to
compute the trainable rate.
Args:
module (:obj:`nn.Module`): of which module we want to know the number of trainable paramemters.
Returns:
:obj:`List[nn.Parameter]`
"""
pnum_tot = 0
for param in module.parameters():
if hasattr(param, "_is_delta"):
pnum_tot += param.numel()
return pnum_tot
The provided code snippet includes necessary dependencies for implementing the `inspect_module_statistics` function. Write a Python function `def inspect_module_statistics(module: Optional[nn.Module]=None, verbose=True)` to solve the following problem:
r"""Get the statistics of the parameters in the delta modules. Args: module (:obj:`nn.Module`, *optional*): The module to compute the statistics. Returns: :obj:`dict`: The statistics of the parameters in the delta modules.
Here is the function:
def inspect_module_statistics(module: Optional[nn.Module]=None, verbose=True):
r"""Get the statistics of the parameters in the delta modules.
Args:
module (:obj:`nn.Module`, *optional*): The module to compute the statistics.
Returns:
:obj:`dict`: The statistics of the parameters in the delta modules.
"""
stat = {}
n_trainable = num_trainable_parameters(module)
n_total = num_total_parameters(module)
stat['total_parameters'] = n_total
stat['trainable_parameters'] = n_trainable
stat['trainable_ratio'] = n_trainable/n_total
n_delta = num_delta_parameters(module)
n_total = num_total_parameters(module)
stat['delta_parameters'] = n_delta
stat['delta_ratio'] = n_delta/n_total
cudamem = 0
maxcudamem = 0
for device_id in range(torch.cuda.device_count()):
cudamem += torch.cuda.memory_allocated(f"cuda:{device_id}")/1024**3
maxcudamem += torch.cuda.max_memory_allocated(f"cuda:{device_id}")/1024**3
stat['cudamem'] = cudamem
stat['maxcudamem'] = maxcudamem
if verbose:
logger.info(stat)
return stat | r"""Get the statistics of the parameters in the delta modules. Args: module (:obj:`nn.Module`, *optional*): The module to compute the statistics. Returns: :obj:`dict`: The statistics of the parameters in the delta modules. |
1,286 | from typing import Union
import torch.nn as nn
import torch
def get_device(module : Union[nn.Module, nn.Parameter]):
if not (isinstance(module, nn.Module) \
or isinstance(module, nn.Parameter)):
raise RuntimeError("module is not a instance of torch.nn.Module")
if hasattr(module, 'device'):
return module.device
else:
params_devices = [p.device for p in module.parameters()]
if len(params_devices) == 0:
return None
elif len(set(params_devices))==1:
return params_devices[0]
else:
raise RuntimeError("The module is paralleled acrossed device, please get device in a inner module") | null |
1,287 | from typing import Union
import torch.nn as nn
import torch
def get_dtype(module : Union[nn.Module, nn.Parameter]):
if not (isinstance(module, nn.Module) \
or isinstance(module, nn.Parameter)):
raise RuntimeError("module is not a instance of torch.nn.Module")
if hasattr(module, 'dtype'):
return module.dtype
else:
params_dtypes = [p.dtype for p in module.parameters()]
if len(params_dtypes) == 0:
return None
elif len(set(params_dtypes))==1:
return params_dtypes[0]
else:
raise RuntimeError("The module has multiple dtype, please get device in a inner module") | null |
1,288 | from typing import Union
import torch.nn as nn
import torch
def move_dict_to_cuda(dict_of_tensor, device):
for key in dict_of_tensor:
if isinstance(dict_of_tensor[key], torch.Tensor):
dict_of_tensor[key] = dict_of_tensor[key].to(device)
return dict_of_tensor | null |
1,289 | from copy import deepcopy
from typing import Any, Dict, OrderedDict
from bigmodelvis import Visualization
import torch.nn as nn
from opendelta.utils.logging import get_logger
import importlib
from opendelta.delta_configs import BaseDeltaConfig
from opendelta.basemodel import DeltaBase
def get_values(model_mapping):
result = []
for model in model_mapping.values():
if isinstance(model, (list, tuple)):
result += list(model)
else:
result.append(model)
return result | null |
1,290 | from copy import deepcopy
from typing import Any, Dict, OrderedDict
from bigmodelvis import Visualization
import torch.nn as nn
from opendelta.utils.logging import get_logger
import importlib
from opendelta.delta_configs import BaseDeltaConfig
from opendelta.basemodel import DeltaBase
def getattribute_from_module(module, attr):
if attr is None:
return None
if isinstance(attr, tuple):
return tuple(getattribute_from_module(module, a) for a in attr)
if hasattr(module, attr):
return getattr(module, attr)
# Some of the mappings have entries model_type -> object of another model type. In that case we try to grab the
# object at the top level.
transformers_module = importlib.import_module("transformers")
return getattribute_from_module(transformers_module, attr) | null |
1,291 | from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import f1_score, matthews_corrcoef
import datasets
def simple_accuracy(preds, labels):
return float((preds == labels).mean())
def acc_and_f1(preds, labels):
acc = simple_accuracy(preds, labels)
f1 = float(f1_score(y_true=labels, y_pred=preds))
return {
"accuracy": acc,
"f1": f1,
} | null |
1,292 | from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import f1_score, matthews_corrcoef
import datasets
def pearson_and_spearman(preds, labels):
pearson_corr = float(pearsonr(preds, labels)[0])
spearman_corr = float(spearmanr(preds, labels)[0])
return {
"pearson": pearson_corr,
"spearmanr": spearman_corr,
} | null |
1,293 | import argparse
import dataclasses
import json
import logging
import os
from pathlib import Path
import random
import re
import sys
from dataclasses import dataclass, field
from typing import Optional
import datasets
import numpy as np
from datasets import load_dataset, load_metric
import transformers
from transformers import (
AutoConfig,
AutoModelForSequenceClassification,
AutoTokenizer,
DataCollatorWithPadding,
EvalPrediction,
HfArgumentParser,
PretrainedConfig,
# Trainer,
TrainingArguments,
default_data_collator,
set_seed,
)
from transformers.trainer import Trainer
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version
from transformers.utils.versions import require_version
def main():
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
parser = RemainArgHfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
json_file=os.path.abspath(sys.argv[1])
model_args, data_args, training_args, delta_args = parser.parse_json_file(json_file, return_remaining_args=True) #args = arg_string, return_remaining_strings=True) #parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
model_args, data_args, training_args, delta_args = parser.parse_args_into_dataclasses()
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
)
log_level = training_args.get_process_log_level()
logger.setLevel(log_level)
datasets.utils.logging.set_verbosity(log_level)
transformers.utils.logging.set_verbosity(log_level)
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
# Detecting last checkpoint.
last_checkpoint = None
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
last_checkpoint = get_last_checkpoint(training_args.output_dir)
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
raise ValueError(
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
"Use --overwrite_output_dir to overcome."
)
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
logger.info(
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
)
# Set seed before initializing model.
set_seed(training_args.seed)
# Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
# or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use as labels the column called 'label' and as pair of sentences the
# sentences in columns called 'sentence1' and 'sentence2' if such column exists or the first two columns not named
# label if at least two columns are provided.
#
# If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this
# single column. You can easily tweak this behavior (see below)
#
# In distributed training, the load_dataset function guarantee that only one local process can concurrently
# download the dataset.
if data_args.task_name is not None:
# Downloading and loading a dataset from the hub.
raw_datasets = load_dataset("glue", data_args.task_name, cache_dir=model_args.cache_dir)
# if you encounter error here
# download the dataset, save to disk and then load_from_disk
# from datasets import load_from_disk
# raw_datasets = load_from_disk(f"../../../../huggingface_datasets/saved_to_disk/glue.{data_args.task_name}")
elif data_args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
raw_datasets = load_dataset(
data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir
)
else:
# Loading a dataset from your local files.
# CSV/JSON training and evaluation files are needed.
data_files = {"train": data_args.train_file, "validation": data_args.validation_file}
# Get the test dataset: you can provide your own CSV/JSON test file (see below)
# when you use `do_predict` without specifying a GLUE benchmark task.
if training_args.do_predict:
if data_args.test_file is not None:
train_extension = data_args.train_file.split(".")[-1]
test_extension = data_args.test_file.split(".")[-1]
assert (
test_extension == train_extension
), "`test_file` should have the same extension (csv or json) as `train_file`."
data_files["test"] = data_args.test_file
else:
raise ValueError("Need either a GLUE task or a test file for `do_predict`.")
for key in data_files.keys():
logger.info(f"load a local file for {key}: {data_files[key]}")
if data_args.train_file.endswith(".csv"):
# Loading a dataset from local csv files
raw_datasets = load_dataset("csv", data_files=data_files, cache_dir=model_args.cache_dir)
else:
# Loading a dataset from local json files
raw_datasets = load_dataset("json", data_files=data_files, cache_dir=model_args.cache_dir)
# See more about loading any type of standard or custom dataset at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Labels
if data_args.task_name is not None:
is_regression = data_args.task_name == "stsb"
if not is_regression:
label_list = raw_datasets["train"].features["label"].names
num_labels = len(label_list)
else:
num_labels = 1
else:
# Trying to have good defaults here, don't hesitate to tweak to your needs.
is_regression = raw_datasets["train"].features["label"].dtype in ["float32", "float64"]
if is_regression:
num_labels = 1
else:
# A useful fast method:
# https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.unique
label_list = raw_datasets["train"].unique("label")
label_list.sort() # Let's sort it for determinism
num_labels = len(label_list)
# Load pretrained model and tokenizer
#
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
config = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
num_labels=num_labels,
finetuning_task=data_args.task_name,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
use_auth_token=True if model_args.use_auth_token else None,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
use_auth_token=True if model_args.use_auth_token else None,
)
model = AutoModelForSequenceClassification.from_pretrained(
model_args.model_name_or_path,
from_tf=bool(".ckpt" in model_args.model_name_or_path),
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
use_auth_token=True if model_args.use_auth_token else None,
)
if delta_args.delta_type.lower() != "none":
from opendelta import AutoDeltaConfig
from opendelta.auto_delta import AutoDeltaModel
delta_config = AutoDeltaConfig.from_dict(vars(delta_args))
delta_model = AutoDeltaModel.from_config(delta_config, backbone_model=model)
delta_model.freeze_module(set_state_dict = True)
delta_model.log(delta_ratio=True, trainable_ratio=True, visualization=True)
# Preprocessing the raw_datasets
if data_args.task_name is not None:
sentence1_key, sentence2_key = task_to_keys[data_args.task_name]
else:
# Again, we try to have some nice defaults but don't hesitate to tweak to your use case.
non_label_column_names = [name for name in raw_datasets["train"].column_names if name != "label"]
if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names:
sentence1_key, sentence2_key = "sentence1", "sentence2"
else:
if len(non_label_column_names) >= 2:
sentence1_key, sentence2_key = non_label_column_names[:2]
else:
sentence1_key, sentence2_key = non_label_column_names[0], None
# Padding strategy
if data_args.pad_to_max_length:
padding = "max_length"
else:
# We will pad later, dynamically at batch creation, to the max sequence length in each batch
padding = False
# Some models have set the order of the labels to use, so let's make sure we do use it.
label_to_id = None
if (
model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id
and data_args.task_name is not None
and not is_regression
):
# Some have all caps in their config, some don't.
label_name_to_id = {k.lower(): v for k, v in model.config.label2id.items()}
if list(sorted(label_name_to_id.keys())) == list(sorted(label_list)):
label_to_id = {i: int(label_name_to_id[label_list[i]]) for i in range(num_labels)}
else:
logger.warning(
"Your model seems to have been trained with labels, but they don't match the dataset: ",
f"model labels: {list(sorted(label_name_to_id.keys()))}, dataset labels: {list(sorted(label_list))}."
"\nIgnoring the model labels as a result.",
)
elif data_args.task_name is None and not is_regression:
label_to_id = {v: i for i, v in enumerate(label_list)}
if label_to_id is not None:
model.config.label2id = label_to_id
model.config.id2label = {id: label for label, id in config.label2id.items()}
elif data_args.task_name is not None and not is_regression:
model.config.label2id = {l: i for i, l in enumerate(label_list)}
model.config.id2label = {id: label for label, id in config.label2id.items()}
if data_args.max_seq_length > tokenizer.model_max_length:
logger.warning(
f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
)
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
def preprocess_function(examples):
# Tokenize the texts
args = (
(examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key])
)
result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True)
# Map labels to IDs (not necessary for GLUE tasks)
if label_to_id is not None and "label" in examples:
result["label"] = [(label_to_id[l] if l != -1 else -1) for l in examples["label"]]
return result
with training_args.main_process_first(desc="dataset map pre-processing"):
raw_datasets = raw_datasets.map(
preprocess_function,
batched=True,
load_from_cache_file=not data_args.overwrite_cache,
desc="Running tokenizer on dataset",
)
if training_args.do_train:
if "train" not in raw_datasets:
raise ValueError("--do_train requires a train dataset")
train_dataset = raw_datasets["train"]
if data_args.max_train_samples is not None:
train_dataset = train_dataset.select(range(data_args.max_train_samples))
if training_args.do_eval:
if "validation" not in raw_datasets and "validation_matched" not in raw_datasets:
raise ValueError("--do_eval requires a validation dataset")
eval_dataset = raw_datasets["validation_matched" if data_args.task_name == "mnli" else "validation"]
if data_args.max_eval_samples is not None:
eval_dataset = eval_dataset.select(range(data_args.max_eval_samples))
if training_args.do_predict or data_args.task_name is not None or data_args.test_file is not None:
if "test" not in raw_datasets and "test_matched" not in raw_datasets:
raise ValueError("--do_predict requires a test dataset")
predict_dataset = raw_datasets["test_matched" if data_args.task_name == "mnli" else "test"]
if data_args.max_predict_samples is not None:
predict_dataset = predict_dataset.select(range(data_args.max_predict_samples))
# Log a few random samples from the training set:
if training_args.do_train:
for index in random.sample(range(len(train_dataset)), 3):
logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
# Get the metric function
if data_args.task_name is not None:
# metric = load_metric("glue", data_args.task_name)
metric = load_metric("./metrics/glue.py", data_args.task_name)
else:
metric = load_metric("accuracy")
# You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
# predictions and label_ids field) and has to return a dictionary string to float.
def compute_metrics(p: EvalPrediction):
preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1)
if data_args.task_name is not None:
result = metric.compute(predictions=preds, references=p.label_ids)
if len(result) > 1:
result["combined_score"] = np.mean(list(result.values())).item()
return result
elif is_regression:
return {"mse": ((preds - p.label_ids) ** 2).mean().item()}
else:
return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item()}
# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
if data_args.pad_to_max_length:
data_collator = default_data_collator
elif training_args.fp16:
data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8)
else:
data_collator = None
# Initialize our Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset if training_args.do_train else None,
eval_dataset=eval_dataset if training_args.do_eval else None,
compute_metrics=compute_metrics,
tokenizer=tokenizer,
data_collator=data_collator,
)
# Training
if training_args.do_train:
checkpoint = None
if training_args.resume_from_checkpoint is not None:
checkpoint = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
checkpoint = last_checkpoint
train_result = trainer.train(resume_from_checkpoint=checkpoint)
metrics = train_result.metrics
max_train_samples = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
)
metrics["train_samples"] = min(max_train_samples, len(train_dataset))
trainer.save_model() # Saves the tokenizer too for easy upload
trainer.log_metrics("train", metrics)
trainer.save_metrics("train", metrics)
trainer.save_state()
results = {}
# Evaluation
if training_args.do_eval:
logger.info("*** Evaluate ***")
# Loop to handle MNLI double evaluation (matched, mis-matched)
tasks = [data_args.task_name]
eval_datasets = [eval_dataset]
if data_args.task_name == "mnli":
tasks.append("mnli-mm")
eval_datasets.append(raw_datasets["validation_mismatched"])
for eval_dataset, task in zip(eval_datasets, tasks):
metrics = trainer.evaluate(eval_dataset=eval_dataset)
max_eval_samples = (
data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
)
metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
trainer.log_metrics("eval", metrics)
trainer.save_metrics("eval", metrics)
results['eval'] = metrics
if training_args.do_predict:
logger.info("*** Predict ***")
# Loop to handle MNLI double evaluation (matched, mis-matched)
tasks = [data_args.task_name]
predict_datasets = [predict_dataset]
if data_args.task_name == "mnli":
tasks.append("mnli-mm")
predict_datasets.append(raw_datasets["test_mismatched"])
for predict_dataset, task in zip(predict_datasets, tasks):
# Removing the `label` columns because it contains -1 and Trainer won't like that.
predict_dataset = predict_dataset.remove_columns("label")
predictions = trainer.predict(predict_dataset, metric_key_prefix="predict").predictions
predictions = np.squeeze(predictions) if is_regression else np.argmax(predictions, axis=1)
output_predict_file = os.path.join(training_args.output_dir, f"predict_results_{task}.txt")
if trainer.is_world_process_zero():
with open(output_predict_file, "w") as writer:
logger.info(f"***** Predict results {task} *****")
writer.write("index\tprediction\n")
for index, item in enumerate(predictions):
if is_regression:
writer.write(f"{index}\t{item:3.3f}\n")
else:
item = label_list[item]
writer.write(f"{index}\t{item}\n")
# from IPython import embed; embed()
# kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-classification"}
# if data_args.task_name is not None:
# kwargs["language"] = "en"
# kwargs["dataset_tags"] = "glue"
# kwargs["dataset_args"] = data_args.task_name
# kwargs["dataset"] = f"GLUE {data_args.task_name.upper()}"
# kwargs["delta_type"] = delta_args.delta_type
repo_name = create_hub_repo_name(root="DeltaHub",
dataset=data_args.task_name,
delta_type = delta_args.delta_type,
model_name_or_path= model_args.model_name_or_path)
if training_args.push_to_hub: # TODO add description here
delta_model.save_finetuned(push_to_hub=True, save_directory=repo_name, use_auth_token=True)
# trainer.push_to_hub(**kwargs)
else:
delta_model.save_finetuned(push_to_hub=False, save_directory=repo_name, use_auth_token=True)
def _mp_fn(index):
# For xla_spawn (TPUs)
main() | null |
1,294 | import collections
import string
import regex as re
import numpy as np
def _normalize_answer(text, punc_chars, punc_repl):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(s):
return re.sub(r"\b(a|an|the)\b", " ", s)
def replace_punctuation(s):
to_replace = set(punc_chars)
return "".join(punc_repl if ch in to_replace else ch for ch in s)
def white_space_fix(s):
return " ".join(s.split())
text = text.lower()
text = replace_punctuation(text)
text = remove_articles(text)
text = white_space_fix(text)
return text
The provided code snippet includes necessary dependencies for implementing the `normalize_trivia_qa` function. Write a Python function `def normalize_trivia_qa(answer)` to solve the following problem:
Normalization used in official TriviaQA evaluation script.
Here is the function:
def normalize_trivia_qa(answer):
"""Normalization used in official TriviaQA evaluation script."""
return _normalize_answer(
answer, punc_chars=string.punctuation + "‘’´`_", punc_repl=" ").strip() | Normalization used in official TriviaQA evaluation script. |
1,295 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
The provided code snippet includes necessary dependencies for implementing the `accuracy` function. Write a Python function `def accuracy(predictions, targets) -> dict` to solve the following problem:
Computes the average accuracy.
Here is the function:
def accuracy(predictions, targets) -> dict:
"""Computes the average accuracy."""
return {"accuracy": 100 * ((np.array(predictions) == np.array(targets)).mean())} | Computes the average accuracy. |
1,296 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
def string_to_float(string, default=-1., **unused_kwargs):
"""Converts string to float, using default when conversion not possible."""
try:
return float(string)
except ValueError:
return default
The provided code snippet includes necessary dependencies for implementing the `pearson_corrcoef` function. Write a Python function `def pearson_corrcoef(predictions, targets) -> dict` to solve the following problem:
Computes Pearson correlation coefficient.
Here is the function:
def pearson_corrcoef(predictions, targets) -> dict:
"""Computes Pearson correlation coefficient."""
from examples_seq2seq.data_processors.postprocessors import string_to_float
targets = [string_to_float(target) for target in targets]
predictions= [string_to_float(prediction) for prediction in predictions]
pearson_corrcoef = 100 * scipy.stats.pearsonr(targets, predictions)[0]
# Note that if all the predictions will be the same, spearman
# correlation is nan, to gaurad against this, we check the output
# and return 0 in this case.
if math.isnan(pearson_corrcoef):
pearson_corrcoef = 0
return {"pearson": pearson_corrcoef} | Computes Pearson correlation coefficient. |
1,297 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
def string_to_float(string, default=-1., **unused_kwargs):
"""Converts string to float, using default when conversion not possible."""
try:
return float(string)
except ValueError:
return default
The provided code snippet includes necessary dependencies for implementing the `spearman_corrcoef` function. Write a Python function `def spearman_corrcoef(predictions, targets) -> dict` to solve the following problem:
Computes Spearman correlation coefficient.
Here is the function:
def spearman_corrcoef(predictions, targets) -> dict:
"""Computes Spearman correlation coefficient."""
# TODO: we need to do postprocessors in a clean way for each dataset.
from examples_seq2seq.data_processors.postprocessors import string_to_float
targets = [string_to_float(target) for target in targets]
predictions= [string_to_float(prediction) for prediction in predictions]
spearman_corrcoef = 100 * scipy.stats.spearmanr(targets, predictions)[0]
# Note that if all the predictions will be the same, spearman
# correlation is nan, to gaurad against this, we check the output
# and return 0 in this case.
if math.isnan(spearman_corrcoef):
spearman_corrcoef = 0
return {"spearmanr": spearman_corrcoef} | Computes Spearman correlation coefficient. |
1,298 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
The provided code snippet includes necessary dependencies for implementing the `matthews_corrcoef` function. Write a Python function `def matthews_corrcoef(predictions, targets) -> dict` to solve the following problem:
Computes the Matthews correlation coefficient.
Here is the function:
def matthews_corrcoef(predictions, targets) -> dict:
"""Computes the Matthews correlation coefficient."""
return {"matthews_correlation": 100 * sklearn.metrics.matthews_corrcoef(targets, predictions)} | Computes the Matthews correlation coefficient. |
1,299 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
f normalize_squad(answer):
"""Normalization used in official SQuAD evaluation script."""
return _normalize_answer(answer, punc_chars=string.punctuation, punc_repl="")
def qa_metrics(targets, predictions):
"""Computes exact match and f1 QA scores, expecting pre-normalized text."""
if len(targets) != len(predictions):
raise ValueError("Number of targets and predictions must match.")
em = np.mean([
_metric_max_over_ground_truths(_exact_match_score, t, p)
for p, t in zip(predictions, targets)
])
f1 = np.mean([
_metric_max_over_ground_truths(_f1_score, t, p)
for p, t in zip(predictions, targets)
])
em *= 100
f1 *= 100
return {"em": em, "f1": f1}
The provided code snippet includes necessary dependencies for implementing the `squad` function. Write a Python function `def squad(predictions, targets)` to solve the following problem:
Computes SQuAD metrics, maximizing over answers per question. Args: targets: list of lists of strings predictions: list of strings Returns: dict with score_key: squad score across all targets and predictions
Here is the function:
def squad(predictions, targets):
"""Computes SQuAD metrics, maximizing over answers per question.
Args:
targets: list of lists of strings
predictions: list of strings
Returns:
dict with score_key: squad score across all targets and predictions
"""
targets = [[normalize_squad(t) for t in u] for u in targets]
predictions = [normalize_squad(p) for p in predictions]
return qa_metrics(targets, predictions) | Computes SQuAD metrics, maximizing over answers per question. Args: targets: list of lists of strings predictions: list of strings Returns: dict with score_key: squad score across all targets and predictions |
1,300 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
The provided code snippet includes necessary dependencies for implementing the `exact_match` function. Write a Python function `def exact_match(predictions, targets)` to solve the following problem:
Computes whether the targets match predictions exactly.
Here is the function:
def exact_match(predictions, targets):
"""Computes whether the targets match predictions exactly."""
return {"em": 100 * float(np.array_equal(targets, predictions))} | Computes whether the targets match predictions exactly. |
1,301 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
def sklearn_metrics_wrapper(metric_str,
metric_dict_str=None,
metric_post_process_fn=None,
**metric_fn_kwargs):
"""Wraps any sklearn.metric function and returns a t5 metric function.
Args:
metric_str: string, the function from `sklearn.metrics` to use.
metric_dict_str: optional string, if not specified `metric_str` is used as
the key in the returned dictionary.
metric_post_process_fn: callable, if specified the final computed metric
will be passed through this.
**metric_fn_kwargs: kwargs, passed to the metric function we are calling.
Returns:
the function that calculates the metric in a dict.
"""
if not hasattr(sklearn.metrics, metric_str):
raise ValueError("sklearn.metrics does not have: %s" % metric_str)
def fn(predictions, targets):
metric_fn = getattr(sklearn.metrics, metric_str)
metric_val = metric_fn(targets, predictions, **metric_fn_kwargs)
if metric_post_process_fn is not None:
metric_val = metric_post_process_fn(metric_val)
return {metric_dict_str or metric_str: metric_val}
return fn
The provided code snippet includes necessary dependencies for implementing the `mean_multiclass_f1` function. Write a Python function `def mean_multiclass_f1(num_classes, **metric_fn_kwargs)` to solve the following problem:
Computes the unweighted average of the F1 per class.
Here is the function:
def mean_multiclass_f1(num_classes, **metric_fn_kwargs):
"""Computes the unweighted average of the F1 per class."""
return sklearn_metrics_wrapper(
"fbeta_score",
metric_dict_str="f1_multiclass",
metric_post_process_fn=lambda x: 100 * x,
beta=1,
labels=range(num_classes),
average="macro",
**metric_fn_kwargs) | Computes the unweighted average of the F1 per class. |
1,302 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
def f1_score_with_invalid(predictions, targets) -> dict:
"""Computes F1 score, with any prediction != 0 or 1 is counted as incorrect.
Args:
targets: list of targets, either 0 or 1
predictions: list of predictions, any integer value
Returns:
F1 score, where any prediction != 0 or 1 is counted as wrong.
"""
def binary_reverse(labels):
return ['0' if label == '1' else '1' for label in labels]
targets, predictions = np.asarray(targets), np.asarray(predictions)
# Get indices of invalid predictions.
invalid_idx_mask = np.logical_and(predictions != '0', predictions != '1')
# For any prediction != 0 or 1, we set the prediction to the opposite of its corresponding target.
predictions[invalid_idx_mask] = binary_reverse(targets[invalid_idx_mask])
targets = targets.astype(np.int32)
predictions = predictions.astype(np.int32)
return {"f1": 100 * sklearn.metrics.f1_score(targets, predictions)}
The provided code snippet includes necessary dependencies for implementing the `multirc_f1_over_all_answers` function. Write a Python function `def multirc_f1_over_all_answers(targets, predictions)` to solve the following problem:
Special metric for MultiRC which computes F1 score over all examples. This is necessary because the targets/predictions for MultiRC are dicts and the f1_score_with_invalid expects a list of True/False labels, not dicts. As a result we just need to key in the "value" for each of the example dicts before feeding into f1_score_with_invalid. Args: targets: list of dicts, where each dict has a "value" key. predictions: list of dicts, where each dict has a "value" key. Returns: F1 score over values, where any prediction != 0 or 1 is counted as wrong.
Here is the function:
def multirc_f1_over_all_answers(targets, predictions):
"""Special metric for MultiRC which computes F1 score over all examples.
This is necessary because the targets/predictions for MultiRC are dicts and
the f1_score_with_invalid expects a list of True/False labels, not dicts. As
a result we just need to key in the "value" for each of the example dicts
before feeding into f1_score_with_invalid.
Args:
targets: list of dicts, where each dict has a "value" key.
predictions: list of dicts, where each dict has a "value" key.
Returns:
F1 score over values, where any prediction != 0 or 1 is counted as wrong.
"""
return f1_score_with_invalid(
[t["value"] for t in targets], [p["value"] for p in predictions]
) | Special metric for MultiRC which computes F1 score over all examples. This is necessary because the targets/predictions for MultiRC are dicts and the f1_score_with_invalid expects a list of True/False labels, not dicts. As a result we just need to key in the "value" for each of the example dicts before feeding into f1_score_with_invalid. Args: targets: list of dicts, where each dict has a "value" key. predictions: list of dicts, where each dict has a "value" key. Returns: F1 score over values, where any prediction != 0 or 1 is counted as wrong. |
1,303 | import numpy as np
import scipy
import math
import sklearn
import collections
from logging import getLogger
from .qa_utils import normalize_squad, qa_metrics
import sklearn.metrics
The provided code snippet includes necessary dependencies for implementing the `mean_group_metric` function. Write a Python function `def mean_group_metric(metric_fn, group_key="group", value_key="value")` to solve the following problem:
Returns a metric that averages `metric_fn` on sub-groups of results. The sub-groups are defined by aggregating results (targets and predictions) by accessing the feature specified by `group_key` in the target dicts. **WARNING**: Using this function can produce unreliable results if you do not pass in full groups. For example, if you evaluate over a random subsample of a validation set and do not retain all of the examples in each group, you may get results which aren't directly comparable to using the full validation set. Args: metric_fn: function, the metric to compute on the subgroups. group_key: string, the key for the grouping value in the target dictionary. value_key: string, the key for the value in the dictionaries.
Here is the function:
def mean_group_metric(metric_fn, group_key="group", value_key="value"):
"""Returns a metric that averages `metric_fn` on sub-groups of results.
The sub-groups are defined by aggregating results (targets and predictions)
by accessing the feature specified by `group_key` in the target dicts.
**WARNING**: Using this function can produce unreliable results if you do not
pass in full groups. For example, if you evaluate over a random subsample of a
validation set and do not retain all of the examples in each group, you may
get results which aren't directly comparable to using the full validation set.
Args:
metric_fn: function, the metric to compute on the subgroups.
group_key: string, the key for the grouping value in the target dictionary.
value_key: string, the key for the value in the dictionaries.
"""
def my_metric(targets, predictions):
"""Computes mean of `metric_fn` over subgroups of results."""
grouped_values = collections.defaultdict(lambda: ([], []))
for targ, pred in zip(targets, predictions):
g = targ[group_key]
grouped_values[g][0].append(targ[value_key])
grouped_values[g][1].append(pred[value_key])
group_scores = collections.defaultdict(list)
for (targets, predictions) in grouped_values.values():
for metric, score in metric_fn(targets, predictions).items():
group_scores[metric].append(score)
return {metric: np.mean(scores) for metric, scores in group_scores.items()}
return my_metric | Returns a metric that averages `metric_fn` on sub-groups of results. The sub-groups are defined by aggregating results (targets and predictions) by accessing the feature specified by `group_key` in the target dicts. **WARNING**: Using this function can produce unreliable results if you do not pass in full groups. For example, if you evaluate over a random subsample of a validation set and do not retain all of the examples in each group, you may get results which aren't directly comparable to using the full validation set. Args: metric_fn: function, the metric to compute on the subgroups. group_key: string, the key for the grouping value in the target dictionary. value_key: string, the key for the value in the dictionaries. |
1,304 | import functools
import logging
import torch
import os
import sys
import subprocess
from typing import Optional, List
from datasets import load_dataset, load_metric, concatenate_datasets
import transformers
from transformers import (
AutoConfig,
AutoModelForSeq2SeqLM,
AutoTokenizer,
HfArgumentParser,
MBartTokenizer,
default_data_collator,
set_seed,
)
from transformers.trainer_utils import is_main_process, get_last_checkpoint
from examples_seq2seq.data_processors import AutoTask, TaskDataCollatorForSeq2Seq, AutoPostProcessor
from examples_seq2seq.seq2seq_trainer import Seq2SeqTrainer
from examples_seq2seq.trainers.trainer_utils import save_training_config
from dataclasses import dataclass, field
from transformers.models.t5.modeling_t5 import T5Config, T5ForConditionalGeneration
from examples_seq2seq.trainers.model_args import ModelArguments
from examples_seq2seq.trainers.trainer_args import TrainingArguments, DataTrainingArguments
import tensorboardX
def run_command(command):
output = subprocess.getoutput(command)
return output | null |
1,305 | import numpy as np
from typing import Union, NamedTuple, Tuple, Dict, Any
import os
import regex as re
import logging
from dataclasses import fields
import torch.nn as nn
import json
The provided code snippet includes necessary dependencies for implementing the `create_dir` function. Write a Python function `def create_dir(output_dir)` to solve the following problem:
Checks whether to the output_dir already exists and creates it if not. Args: output_dir: path to the output_dir
Here is the function:
def create_dir(output_dir):
"""
Checks whether to the output_dir already exists and creates it if not.
Args:
output_dir: path to the output_dir
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir) | Checks whether to the output_dir already exists and creates it if not. Args: output_dir: path to the output_dir |
1,306 | import numpy as np
from typing import Union, NamedTuple, Tuple, Dict, Any
import os
import regex as re
import logging
from dataclasses import fields
import torch.nn as nn
import json
def get_last_checkpoint(output_dir):
if os.path.exists(os.path.join(output_dir, 'pytorch_model.bin')):
return output_dir
return None | null |
1,307 | import numpy as np
from typing import Union, NamedTuple, Tuple, Dict, Any
import os
import regex as re
import logging
from dataclasses import fields
import torch.nn as nn
import json
The provided code snippet includes necessary dependencies for implementing the `pad_punctuation` function. Write a Python function `def pad_punctuation(text)` to solve the following problem:
Re-implementation of _pad_punctuation in t5. This function adds spaces around punctuation. While this pads punctuation as expected, it has the unexpected effected of padding certain unicode characters with accents, with spaces as well. For instance: "François" becomes "Fran ç ois
Here is the function:
def pad_punctuation(text):
"""Re-implementation of _pad_punctuation in t5. This function adds spaces
around punctuation. While this pads punctuation as expected, it has the
unexpected effected of padding certain unicode characters with accents, with
spaces as well. For instance: "François" becomes "Fran ç ois"""
# Pad everything except for: underscores (_), whitespace (\s),
# numbers (\p{N}), letters (\p{L}) and accent characters (\p{M}).
text = re.sub(r'([^_\s\p{N}\p{L}\p{M}])', r' \1 ', text)
# Collapse consecutive whitespace into one space.
text = re.sub(r'\s+', ' ', text)
return text | Re-implementation of _pad_punctuation in t5. This function adds spaces around punctuation. While this pads punctuation as expected, it has the unexpected effected of padding certain unicode characters with accents, with spaces as well. For instance: "François" becomes "Fran ç ois |
1,308 | import numpy as np
from typing import Union, NamedTuple, Tuple, Dict, Any
import os
import regex as re
import logging
from dataclasses import fields
import torch.nn as nn
import json
def save_json(filepath, dictionary):
with open(filepath, "w") as outfile:
json.dump(dictionary, outfile)
def read_json(filepath):
f = open(filepath,)
return json.load(f)
def save_training_config(config_file, output_dir):
json_data = read_json(config_file)
save_json(os.path.join(output_dir, "training_config.json"), json_data) | null |
1,309 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `round_stsb_target` function. Write a Python function `def round_stsb_target(label)` to solve the following problem:
STSB maps two sentences to a floating point number between 1 and 5 representing their semantic similarity. Since we are treating all tasks as text-to-text tasks we need to convert this floating point number to a string. The vast majority of the similarity score labels in STSB are in the set [0, 0.2, 0.4, ..., 4.8, 5.0]. So, we first round the number to the closest entry in this set, and then we convert the result to a string (literally e.g. "3.4"). This converts STSB roughly into a 26-class classification dataset. Args: label: original label. Returns: A preprocessed label.
Here is the function:
def round_stsb_target(label):
"""STSB maps two sentences to a floating point number between 1 and 5
representing their semantic similarity. Since we are treating all tasks as
text-to-text tasks we need to convert this floating point number to a string.
The vast majority of the similarity score labels in STSB are in the set
[0, 0.2, 0.4, ..., 4.8, 5.0]. So, we first round the number to the closest
entry in this set, and then we convert the result to a string (literally e.g.
"3.4"). This converts STSB roughly into a 26-class classification dataset.
Args:
label: original label.
Returns:
A preprocessed label.
"""
return np.round((label * 5) / 5, decimals=1) | STSB maps two sentences to a floating point number between 1 and 5 representing their semantic similarity. Since we are treating all tasks as text-to-text tasks we need to convert this floating point number to a string. The vast majority of the similarity score labels in STSB are in the set [0, 0.2, 0.4, ..., 4.8, 5.0]. So, we first round the number to the closest entry in this set, and then we convert the result to a string (literally e.g. "3.4"). This converts STSB roughly into a 26-class classification dataset. Args: label: original label. Returns: A preprocessed label. |
1,310 | import os
import setuptools
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
def setup_package():
long_description = "examples_seq2seq"
setuptools.setup(
name='examples_seq2seq',
version='0.0.1',
description='seq2seq example',
long_description=long_description,
long_description_content_type='text/markdown',
author='Shengding Hu',
license='MIT License',
packages=setuptools.find_packages(
exclude=['docs', 'tests', 'scripts']),
dependency_links=[
'https://download.pytorch.org/whl/torch_stable.html',
],
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7.10',
],
keywords='text nlp machinelearning',
cmdclass={"build_ext": BuildExtension},
install_requires=[
"pyarrow==7.0.0",
"datasets==1.17.0"
],
) | null |
1,311 | import itertools
import torch
import tqdm
import multiprocessing
import numpy as np
import scipy.spatial as spatial
import scipy.special as special
import scipy.stats as stats
import logging
logger = logging.getLogger(__name__)
def select_likely_words(train_logits, train_labels, k_likely=1000, vocab=None, is_regression=False):
"""Pre-select likely words based on conditional likelihood."""
indices = []
if is_regression:
median = np.median(train_labels)
train_labels = (train_labels > median).astype(np.int)
num_labels = np.max(train_labels) + 1
for idx in range(num_labels):
label_logits = train_logits[train_labels == idx]
scores = label_logits.mean(axis=0)
kept = []
for i in np.argsort(-scores):
text = vocab[i]
if not text.startswith("Ġ"):
continue
kept.append(i)
indices.append(kept[:k_likely])
return indices
def select_neighbors(distances, k_neighbors, valid):
"""Select k nearest neighbors based on distance (filtered to be within the 'valid' set)."""
indices = np.argsort(distances)
neighbors = []
for i in indices:
if i not in valid:
continue
neighbors.append(i)
if k_neighbors > 0:
return neighbors[:k_neighbors]
return neighbors
def init(train_logits, train_labels):
global logits, labels
logits = train_logits
labels = train_labels
def eval_pairing_acc(pairing):
global logits, labels
label_logits = np.take(logits, pairing, axis=-1)
preds = np.argmax(label_logits, axis=-1)
correct = np.sum(preds == labels)
return correct / len(labels)
def eval_pairing_corr(pairing):
global logits, labels
if pairing[0] == pairing[1]:
return -1
label_logits = np.take(logits, pairing, axis=-1)
label_probs = special.softmax(label_logits, axis=-1)[:, 1]
pearson_corr = stats.pearsonr(label_probs, labels)[0]
return pearson_corr
def find_labels(
model,
train_logits,
train_labels,
seed_labels=None,
k_likely=1000,
k_neighbors=None,
top_n=-1,
vocab=None,
is_regression=False,
):
# Get top indices based on conditional likelihood using the LM.
likely_indices = select_likely_words(
train_logits=train_logits,
train_labels=train_labels,
k_likely=k_likely,
vocab=vocab,
is_regression=is_regression)
logger.info("Top labels (conditional) per class:")
for i, inds in enumerate(likely_indices):
logger.info("\t| Label %d: %s", i, ", ".join([vocab[i] for i in inds[:10]]))
# Convert to sets.
valid_indices = [set(inds) for inds in likely_indices]
# If specified, further re-rank according to nearest neighbors of seed labels.
# Otherwise, keep ranking as is (based on conditional likelihood only).
if seed_labels:
assert(vocab is not None)
seed_ids = [vocab.index(l) for l in seed_labels]
vocab_vecs = model.lm_head.decoder.weight.detach().cpu().numpy()
seed_vecs = np.take(vocab_vecs, seed_ids, axis=0)
# [num_labels, vocab_size]
label_distances = spatial.distance.cdist(seed_vecs, vocab_vecs, metric="cosine")
# Establish label candidates (as k nearest neighbors).
label_candidates = []
logger.info("Re-ranked by nearest neighbors:")
for i, distances in enumerate(label_distances):
label_candidates.append(select_neighbors(distances, k_neighbors, valid_indices[i]))
logger.info("\t| Label: %s", seed_labels[i])
logger.info("\t| Neighbors: %s", " ".join([vocab[idx] for idx in label_candidates[i]]))
else:
label_candidates = likely_indices
# Brute-force search all valid pairings.
pairings = list(itertools.product(*label_candidates))
if is_regression:
eval_pairing = eval_pairing_corr
metric = "corr"
else:
eval_pairing = eval_pairing_acc
metric = "acc"
# Score each pairing.
pairing_scores = []
with multiprocessing.Pool(initializer=init, initargs=(train_logits, train_labels)) as workers:
with tqdm.tqdm(total=len(pairings)) as pbar:
chunksize = max(10, int(len(pairings) / 1000))
for score in workers.imap(eval_pairing, pairings, chunksize=chunksize):
pairing_scores.append(score)
pbar.update()
# Take top-n.
best_idx = np.argsort(-np.array(pairing_scores))[:top_n]
best_scores = [pairing_scores[i] for i in best_idx]
best_pairings = [pairings[i] for i in best_idx]
logger.info("Automatically searched pairings:")
for i, indices in enumerate(best_pairings):
logger.info("\t| %s (%s = %2.2f)", " ".join([vocab[j] for j in indices]), metric, best_scores[i])
return best_pairings | null |
1,312 | import collections
import inspect
import math
import os
import re
import shutil
import warnings
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from packaging import version
from torch import nn
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.dataset import Dataset
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data.sampler import RandomSampler, SequentialSampler
import transformers
from transformers import EvaluationStrategy
from transformers.data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator
from transformers.file_utils import WEIGHTS_NAME, is_datasets_available, is_in_notebook, is_torch_tpu_available
from transformers.integrations import (
default_hp_search_backend,
is_comet_available,
is_optuna_available,
is_ray_available,
is_tensorboard_available,
is_wandb_available,
run_hp_search_optuna,
run_hp_search_ray,
)
from transformers.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from transformers.modeling_utils import PreTrainedModel
from transformers.optimization import AdamW, get_linear_schedule_with_warmup
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.trainer_callback import (
CallbackHandler,
DefaultFlowCallback,
PrinterCallback,
ProgressCallback,
TrainerCallback,
TrainerControl,
TrainerState,
)
from transformers.trainer_pt_utils import (
DistributedTensorGatherer,
SequentialDistributedSampler,
distributed_broadcast_scalars,
distributed_concat,
get_tpu_sampler,
nested_concat,
nested_detach,
nested_numpify,
nested_xla_mesh_reduce,
reissue_pt_warnings,
)
from transformers.trainer_utils import (
PREFIX_CHECKPOINT_DIR,
BestRun,
EvalPrediction,
HPSearchBackend,
PredictionOutput,
TrainOutput,
default_compute_objective,
default_hp_space,
set_seed,
)
from transformers.training_args import TrainingArguments
from transformers.utils import logging
from tqdm import tqdm, trange
The provided code snippet includes necessary dependencies for implementing the `default_dev_objective` function. Write a Python function `def default_dev_objective(metrics)` to solve the following problem:
Objective used for picking the best model on development sets
Here is the function:
def default_dev_objective(metrics):
"""
Objective used for picking the best model on development sets
"""
if "eval_mnli/acc" in metrics:
return metrics["eval_mnli/acc"]
elif "eval_mnli-mm/acc" in metrics:
return metrics["eval_mnli-mm/acc"]
elif "eval_f1" in metrics:
return metrics["eval_f1"]
elif "eval_mcc" in metrics:
return metrics["eval_mcc"]
elif "eval_pearson" in metrics:
return metrics["eval_pearson"]
elif "eval_acc" in metrics:
return metrics["eval_acc"]
raise Exception("No metric founded for {}".format(metrics)) | Objective used for picking the best model on development sets |
Subsets and Splits