python_code
stringlengths
0
456k
#!/usr/bin/env python ''' example to detect upright people in images using HOG features ''' # Python 2/3 compatibility from __future__ import print_function import numpy as np import cv2 as cv def inside(r, q): rx, ry, rw, rh = r qx, qy, qw, qh = q return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh from tests_common import NewOpenCVTests, intersectionRate class peopledetect_test(NewOpenCVTests): def test_peopledetect(self): hog = cv.HOGDescriptor() hog.setSVMDetector( cv.HOGDescriptor_getDefaultPeopleDetector() ) dirPath = 'samples/data/' samples = ['basketball1.png', 'basketball2.png'] testPeople = [ [[23, 76, 164, 477], [440, 22, 637, 478]], [[23, 76, 164, 477], [440, 22, 637, 478]] ] eps = 0.5 for sample in samples: img = self.get_sample(dirPath + sample, 0) found, _w = hog.detectMultiScale(img, winStride=(8,8), padding=(32,32), scale=1.05) found_filtered = [] for ri, r in enumerate(found): for qi, q in enumerate(found): if ri != qi and inside(r, q): break else: found_filtered.append(r) matches = 0 for i in range(len(found_filtered)): for j in range(len(testPeople)): found_rect = (found_filtered[i][0], found_filtered[i][1], found_filtered[i][0] + found_filtered[i][2], found_filtered[i][1] + found_filtered[i][3]) if intersectionRate(found_rect, testPeople[j][0]) > eps or intersectionRate(found_rect, testPeople[j][1]) > eps: matches += 1 self.assertGreater(matches, 0) if __name__ == '__main__': NewOpenCVTests.bootstrap()
#!/usr/bin/env python ''' face detection using haar cascades ''' # Python 2/3 compatibility from __future__ import print_function import numpy as np import cv2 as cv def detect(img, cascade): rects = cascade.detectMultiScale(img, scaleFactor=1.275, minNeighbors=4, minSize=(30, 30), flags=cv.CASCADE_SCALE_IMAGE) if len(rects) == 0: return [] rects[:,2:] += rects[:,:2] return rects from tests_common import NewOpenCVTests, intersectionRate class facedetect_test(NewOpenCVTests): def test_facedetect(self): cascade_fn = self.repoPath + '/data/haarcascades/haarcascade_frontalface_alt.xml' nested_fn = self.repoPath + '/data/haarcascades/haarcascade_eye.xml' cascade = cv.CascadeClassifier(cascade_fn) nested = cv.CascadeClassifier(nested_fn) samples = ['samples/data/lena.jpg', 'cv/cascadeandhog/images/mona-lisa.png'] faces = [] eyes = [] testFaces = [ #lena [[218, 200, 389, 371], [ 244, 240, 294, 290], [ 309, 246, 352, 289]], #lisa [[167, 119, 307, 259], [188, 153, 229, 194], [236, 153, 277, 194]] ] for sample in samples: img = self.get_sample( sample) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) gray = cv.GaussianBlur(gray, (5, 5), 0) rects = detect(gray, cascade) faces.append(rects) if not nested.empty(): for x1, y1, x2, y2 in rects: roi = gray[y1:y2, x1:x2] subrects = detect(roi.copy(), nested) for rect in subrects: rect[0] += x1 rect[2] += x1 rect[1] += y1 rect[3] += y1 eyes.append(subrects) faces_matches = 0 eyes_matches = 0 eps = 0.8 for i in range(len(faces)): for j in range(len(testFaces)): if intersectionRate(faces[i][0], testFaces[j][0]) > eps: faces_matches += 1 #check eyes if len(eyes[i]) == 2: if intersectionRate(eyes[i][0], testFaces[j][1]) > eps and intersectionRate(eyes[i][1] , testFaces[j][2]) > eps: eyes_matches += 1 elif intersectionRate(eyes[i][1], testFaces[j][1]) > eps and intersectionRate(eyes[i][0], testFaces[j][2]) > eps: eyes_matches += 1 self.assertEqual(faces_matches, 2) self.assertEqual(eyes_matches, 2) if __name__ == '__main__': NewOpenCVTests.bootstrap()
#!/usr/bin/env python ''' =============================================================================== QR code detect and decode pipeline. =============================================================================== ''' import os import numpy as np import cv2 as cv from tests_common import NewOpenCVTests class qrcode_detector_test(NewOpenCVTests): def test_detect(self): img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/link_ocv.jpg')) self.assertFalse(img is None) detector = cv.QRCodeDetector() retval, points = detector.detect(img) self.assertTrue(retval) self.assertEqual(points.shape, (1, 4, 2)) def test_detect_and_decode(self): img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/link_ocv.jpg')) self.assertFalse(img is None) detector = cv.QRCodeDetector() retval, points, straight_qrcode = detector.detectAndDecode(img) self.assertEqual(retval, "https://opencv.org/") self.assertEqual(points.shape, (1, 4, 2)) def test_detect_multi(self): img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/multiple/6_qrcodes.png')) self.assertFalse(img is None) detector = cv.QRCodeDetector() retval, points = detector.detectMulti(img) self.assertTrue(retval) self.assertEqual(points.shape, (6, 4, 2)) def test_detect_and_decode_multi(self): img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/multiple/6_qrcodes.png')) self.assertFalse(img is None) detector = cv.QRCodeDetector() retval, decoded_data, points, straight_qrcode = detector.detectAndDecodeMulti(img) self.assertTrue(retval) self.assertEqual(len(decoded_data), 6) self.assertEqual(decoded_data[0], "TWO STEPS FORWARD") self.assertEqual(decoded_data[1], "EXTRA") self.assertEqual(decoded_data[2], "SKIP") self.assertEqual(decoded_data[3], "STEP FORWARD") self.assertEqual(decoded_data[4], "STEP BACK") self.assertEqual(decoded_data[5], "QUESTION") self.assertEqual(points.shape, (6, 4, 2))
############################################################################### # # IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. # # By downloading, copying, installing or using the software you agree to this license. # If you do not agree to this license, do not download, install, # copy or use the software. # # # License Agreement # For Open Source Computer Vision Library # # Copyright (C) 2013, OpenCV Foundation, all rights reserved. # Third party copyrights are property of their respective owners. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistribution's of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # * Redistribution's in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * The name of the copyright holders may not be used to endorse or promote products # derived from this software without specific prior written permission. # # This software is provided by the copyright holders and contributors "as is" and # any express or implied warranties, including, but not limited to, the implied # warranties of merchantability and fitness for a particular purpose are disclaimed. # In no event shall the Intel Corporation or contributors be liable for any direct, # indirect, incidental, special, exemplary, or consequential damages # (including, but not limited to, procurement of substitute goods or services; # loss of use, data, or profits; or business interruption) however caused # and on any theory of liability, whether in contract, strict liability, # or tort (including negligence or otherwise) arising in any way out of # the use of this software, even if advised of the possibility of such damage. # ############################################################################### # AUTHOR: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu # # LICENSE AGREEMENT # Copyright (c) 2015, 2015 The Regents of the University of California (Regents) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the University nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################### from __future__ import print_function import sys, re, os from templates import * if sys.version_info[0] >= 3: from io import StringIO else: from cStringIO import StringIO func_table = {} # Ignore these functions due to Embind limitations for now ignore_list = ['locate', #int& 'minEnclosingCircle', #float& 'checkRange', 'minMaxLoc', #double* 'floodFill', # special case, implemented in core_bindings.cpp 'phaseCorrelate', 'randShuffle', 'calibrationMatrixValues', #double& 'undistortPoints', # global redefinition 'CamShift', #Rect& 'meanShift' #Rect& ] def makeWhiteList(module_list): wl = {} for m in module_list: for k in m.keys(): if k in wl: wl[k] += m[k] else: wl[k] = m[k] return wl white_list = None exec(open(os.environ["OPENCV_JS_WHITELIST"]).read()) assert(white_list) # Features to be exported export_enums = False export_consts = True with_wrapped_functions = True with_default_params = True with_vec_from_js_array = True wrapper_namespace = "Wrappers" type_dict = { 'InputArray': 'const cv::Mat&', 'OutputArray': 'cv::Mat&', 'InputOutputArray': 'cv::Mat&', 'InputArrayOfArrays': 'const std::vector<cv::Mat>&', 'OutputArrayOfArrays': 'std::vector<cv::Mat>&', 'String': 'std::string', 'const String&':'const std::string&' } def normalize_class_name(name): return re.sub(r"^cv\.", "", name).replace(".", "_") class ClassProp(object): def __init__(self, decl): self.tp = decl[0].replace("*", "_ptr").strip() self.name = decl[1] self.readonly = True if "/RW" in decl[3]: self.readonly = False class ClassInfo(object): def __init__(self, name, decl=None): self.cname = name.replace(".", "::") self.name = self.wname = normalize_class_name(name) self.ismap = False self.issimple = False self.isalgorithm = False self.methods = {} self.ext_constructors = {} self.props = [] self.consts = {} customname = False self.jsfuncs = {} self.constructor_arg_num = set() self.has_smart_ptr = False if decl: self.bases = decl[1].split()[1:] if len(self.bases) > 1: self.bases = [self.bases[0].strip(",")] # return sys.exit(-1) if self.bases and self.bases[0].startswith("cv::"): self.bases[0] = self.bases[0][4:] if self.bases and self.bases[0] == "Algorithm": self.isalgorithm = True for m in decl[2]: if m.startswith("="): self.wname = m[1:] customname = True elif m == "/Map": self.ismap = True elif m == "/Simple": self.issimple = True self.props = [ClassProp(p) for p in decl[3]] if not customname and self.wname.startswith("Cv"): self.wname = self.wname[2:] def handle_ptr(tp): if tp.startswith('Ptr_'): tp = 'Ptr<' + "::".join(tp.split('_')[1:]) + '>' return tp def handle_vector(tp): if tp.startswith('vector_'): tp = handle_vector(tp[tp.find('_') + 1:]) tp = 'std::vector<' + "::".join(tp.split('_')) + '>' return tp class ArgInfo(object): def __init__(self, arg_tuple): self.tp = handle_ptr(arg_tuple[0]).strip() self.name = arg_tuple[1] self.defval = arg_tuple[2] self.isarray = False self.arraylen = 0 self.arraycvt = None self.inputarg = True self.outputarg = False self.returnarg = False self.const = False self.reference = False for m in arg_tuple[3]: if m == "/O": self.inputarg = False self.outputarg = True self.returnarg = True elif m == "/IO": self.inputarg = True self.outputarg = True self.returnarg = True elif m.startswith("/A"): self.isarray = True self.arraylen = m[2:].strip() elif m.startswith("/CA"): self.isarray = True self.arraycvt = m[2:].strip() elif m == "/C": self.const = True elif m == "/Ref": self.reference = True if self.tp == "Mat": if self.outputarg: self.tp = "cv::Mat&" elif self.inputarg: self.tp = "const cv::Mat&" if self.tp == "vector_Mat": if self.outputarg: self.tp = "std::vector<cv::Mat>&" elif self.inputarg: self.tp = "const std::vector<cv::Mat>&" self.tp = handle_vector(self.tp).strip() if self.const: self.tp = "const " + self.tp if self.reference: self.tp = self.tp + "&" self.py_inputarg = False self.py_outputarg = False class FuncVariant(object): def __init__(self, class_name, name, decl, is_constructor, is_class_method, is_const, is_virtual, is_pure_virtual, ref_return, const_return): self.class_name = class_name self.name = self.wname = name self.is_constructor = is_constructor self.is_class_method = is_class_method self.is_const = is_const self.is_virtual = is_virtual self.is_pure_virtual = is_pure_virtual self.refret = ref_return self.constret = const_return self.rettype = handle_vector(handle_ptr(decl[1]).strip()).strip() if self.rettype == "void": self.rettype = "" self.args = [] self.array_counters = {} for a in decl[3]: ainfo = ArgInfo(a) if ainfo.isarray and not ainfo.arraycvt: c = ainfo.arraylen c_arrlist = self.array_counters.get(c, []) if c_arrlist: c_arrlist.append(ainfo.name) else: self.array_counters[c] = [ainfo.name] self.args.append(ainfo) class FuncInfo(object): def __init__(self, class_name, name, cname, namespace, isconstructor): self.class_name = class_name self.name = name self.cname = cname self.namespace = namespace self.variants = [] self.is_constructor = isconstructor def add_variant(self, variant): self.variants.append(variant) class Namespace(object): def __init__(self): self.funcs = {} self.enums = {} self.consts = {} class JSWrapperGenerator(object): def __init__(self): self.bindings = [] self.wrapper_funcs = [] self.classes = {} self.namespaces = {} self.enums = {} self.parser = hdr_parser.CppHeaderParser() self.class_idx = 0 def add_class(self, stype, name, decl): class_info = ClassInfo(name, decl) class_info.decl_idx = self.class_idx self.class_idx += 1 if class_info.name in self.classes: print("Generator error: class %s (cpp_name=%s) already exists" \ % (class_info.name, class_info.cname)) sys.exit(-1) self.classes[class_info.name] = class_info if class_info.bases: chunks = class_info.bases[0].split('::') base = '_'.join(chunks) while base not in self.classes and len(chunks) > 1: del chunks[-2] base = '_'.join(chunks) if base not in self.classes: print("Generator error: unable to resolve base %s for %s" % (class_info.bases[0], class_info.name)) sys.exit(-1) else: class_info.bases[0] = "::".join(chunks) class_info.isalgorithm |= self.classes[base].isalgorithm def split_decl_name(self, name): chunks = name.split('.') namespace = chunks[:-1] classes = [] while namespace and '.'.join(namespace) not in self.parser.namespaces: classes.insert(0, namespace.pop()) return namespace, classes, chunks[-1] def add_enum(self, decl): name = decl[0].rsplit(" ", 1)[1] namespace, classes, val = self.split_decl_name(name) namespace = '.'.join(namespace) ns = self.namespaces.setdefault(namespace, Namespace()) if len(name) == 0: name = "<unnamed>" if name.endswith("<unnamed>"): i = 0 while True: i += 1 candidate_name = name.replace("<unnamed>", "unnamed_%u" % i) if candidate_name not in ns.enums: name = candidate_name break; cname = name.replace('.', '::') type_dict[normalize_class_name(name)] = cname if name in ns.enums: print("Generator warning: enum %s (cname=%s) already exists" \ % (name, cname)) # sys.exit(-1) else: ns.enums[name] = [] for item in decl[3]: ns.enums[name].append(item) const_decls = decl[3] for decl in const_decls: name = decl[0] self.add_const(name.replace("const ", "").strip(), decl) def add_const(self, name, decl): cname = name.replace('.','::') namespace, classes, name = self.split_decl_name(name) namespace = '.'.join(namespace) name = '_'.join(classes+[name]) ns = self.namespaces.setdefault(namespace, Namespace()) if name in ns.consts: print("Generator error: constant %s (cname=%s) already exists" \ % (name, cname)) sys.exit(-1) ns.consts[name] = cname def add_func(self, decl): namespace, classes, barename = self.split_decl_name(decl[0]) cpp_name = "::".join(namespace + classes + [barename]) name = barename class_name = '' bare_class_name = '' if classes: class_name = normalize_class_name('.'.join(namespace + classes)) bare_class_name = classes[-1] namespace = '.'.join(namespace) is_constructor = name == bare_class_name is_class_method = False is_const_method = False is_virtual_method = False is_pure_virtual_method = False const_return = False ref_return = False for m in decl[2]: if m == "/S": is_class_method = True elif m == "/C": is_const_method = True elif m == "/V": is_virtual_method = True elif m == "/PV": is_pure_virtual_method = True elif m == "/Ref": ref_return = True elif m == "/CRet": const_return = True elif m.startswith("="): name = m[1:] if class_name: cpp_name = barename func_map = self.classes[class_name].methods else: func_map = self.namespaces.setdefault(namespace, Namespace()).funcs func = func_map.setdefault(name, FuncInfo(class_name, name, cpp_name, namespace, is_constructor)) variant = FuncVariant(class_name, name, decl, is_constructor, is_class_method, is_const_method, is_virtual_method, is_pure_virtual_method, ref_return, const_return) func.add_variant(variant) def save(self, path, name, buf): f = open(path + "/" + name, "wt") f.write(buf.getvalue()) f.close() def gen_function_binding_with_wrapper(self, func, class_info): binding_text = None wrapper_func_text = None bindings = [] wrappers = [] for index, variant in enumerate(func.variants): factory = False if class_info and 'Ptr<' in variant.rettype: factory = True base_class_name = variant.rettype base_class_name = base_class_name.replace("Ptr<","").replace(">","").strip() if base_class_name in self.classes: self.classes[base_class_name].has_smart_ptr = True else: print(base_class_name, ' not found in classes for registering smart pointer using ', class_info.name, 'instead') self.classes[class_info.name].has_smart_ptr = True def_args = [] has_def_param = False # Return type ret_type = 'void' if variant.rettype.strip() == '' else variant.rettype if ret_type.startswith('Ptr'): #smart pointer ptr_type = ret_type.replace('Ptr<', '').replace('>', '') if ptr_type in type_dict: ret_type = type_dict[ptr_type] for key in type_dict: if key in ret_type: ret_type = ret_type.replace(key, type_dict[key]) arg_types = [] unwrapped_arg_types = [] for arg in variant.args: arg_type = None if arg.tp in type_dict: arg_type = type_dict[arg.tp] else: arg_type = arg.tp # Add default value if with_default_params and arg.defval != '': def_args.append(arg.defval); arg_types.append(arg_type) unwrapped_arg_types.append(arg_type) # Function attribure func_attribs = '' if '*' in ''.join(arg_types): func_attribs += ', allow_raw_pointers()' if variant.is_pure_virtual: func_attribs += ', pure_virtual()' # Wrapper function wrap_func_name = (func.class_name+"_" if class_info != None else "") + func.name.split("::")[-1] + "_wrapper" js_func_name = func.name # TODO: Name functions based wrap directives or based on arguments list if index > 0: wrap_func_name += str(index) js_func_name += str(index) c_func_name = 'Wrappers::' + wrap_func_name # Binding template- raw_arg_names = ['arg' + str(i + 1) for i in range(0, len(variant.args))] arg_names = [] w_signature = [] casted_arg_types = [] for arg_type, arg_name in zip(arg_types, raw_arg_names): casted_arg_name = arg_name if with_vec_from_js_array: # Only support const vector reference as input parameter match = re.search(r'const std::vector<(.*)>&', arg_type) if match: type_in_vect = match.group(1) if type_in_vect in ['int', 'float', 'double', 'char', 'uchar', 'String', 'std::string']: casted_arg_name = 'emscripten::vecFromJSArray<' + type_in_vect + '>(' + arg_name + ')' arg_type = re.sub(r'std::vector<(.*)>', 'emscripten::val', arg_type) w_signature.append(arg_type + ' ' + arg_name) arg_names.append(casted_arg_name) casted_arg_types.append(arg_type) arg_types = casted_arg_types # Argument list, signature arg_names_casted = [c if a == b else c + '.as<' + a + '>()' for a, b, c in zip(unwrapped_arg_types, arg_types, arg_names)] # Add self object to the parameters if class_info and not factory: arg_types = [class_info.cname + '&'] + arg_types w_signature = [class_info.cname + '& arg0 '] + w_signature for j in range(0, len(def_args) + 1): postfix = '' if j > 0: postfix = '_' + str(j); ################################### # Wrapper if factory: # TODO or static name = class_info.cname+'::' if variant.class_name else "" cpp_call_text = static_class_call_template.substitute(scope=name, func=func.cname, args=', '.join(arg_names[:len(arg_names)-j])) elif class_info: cpp_call_text = class_call_template.substitute(obj='arg0', func=func.cname, args=', '.join(arg_names[:len(arg_names)-j])) else: cpp_call_text = call_template.substitute(func=func.cname, args=', '.join(arg_names[:len(arg_names)-j])) wrapper_func_text = wrapper_function_template.substitute(ret_val=ret_type, func=wrap_func_name+postfix, signature=', '.join(w_signature[:len(w_signature)-j]), cpp_call=cpp_call_text, const='' if variant.is_const else '') ################################### # Binding if class_info: if factory: # print("Factory Function: ", c_func_name, len(variant.args) - j, class_info.name) if variant.is_pure_virtual: # FIXME: workaround for pure virtual in constructor # e.g. DescriptorMatcher_clone_wrapper continue # consider the default parameter variants args_num = len(variant.args) - j if args_num in class_info.constructor_arg_num: # FIXME: workaournd for constructor overload with same args number # e.g. DescriptorMatcher continue class_info.constructor_arg_num.add(args_num) binding_text = ctr_template.substitute(const='const' if variant.is_const else '', cpp_name=c_func_name+postfix, ret=ret_type, args=','.join(arg_types[:len(arg_types)-j]), optional=func_attribs) else: binding_template = overload_class_static_function_template if variant.is_class_method else \ overload_class_function_template binding_text = binding_template.substitute(js_name=js_func_name, const='' if variant.is_const else '', cpp_name=c_func_name+postfix, ret=ret_type, args=','.join(arg_types[:len(arg_types)-j]), optional=func_attribs) else: binding_text = overload_function_template.substitute(js_name=js_func_name, cpp_name=c_func_name+postfix, const='const' if variant.is_const else '', ret=ret_type, args=', '.join(arg_types[:len(arg_types)-j]), optional=func_attribs) bindings.append(binding_text) wrappers.append(wrapper_func_text) return [bindings, wrappers] def gen_function_binding(self, func, class_info): if not class_info == None : func_name = class_info.cname+'::'+func.cname else : func_name = func.cname binding_text = None binding_text_list = [] for index, variant in enumerate(func.variants): factory = False #TODO if variant.is_class_method and variant.rettype == ('Ptr<' + class_info.name + '>'): if (not class_info == None) and variant.rettype == ('Ptr<' + class_info.name + '>') or (func.name.startswith("create") and variant.rettype): factory = True base_class_name = variant.rettype base_class_name = base_class_name.replace("Ptr<","").replace(">","").strip() if base_class_name in self.classes: self.classes[base_class_name].has_smart_ptr = True else: print(base_class_name, ' not found in classes for registering smart pointer using ', class_info.name, 'instead') self.classes[class_info.name].has_smart_ptr = True # Return type ret_type = 'void' if variant.rettype.strip() == '' else variant.rettype ret_type = ret_type.strip() if ret_type.startswith('Ptr'): #smart pointer ptr_type = ret_type.replace('Ptr<', '').replace('>', '') if ptr_type in type_dict: ret_type = type_dict[ptr_type] for key in type_dict: if key in ret_type: ret_type = ret_type.replace(key, type_dict[key]) if variant.constret and ret_type.startswith('const') == False: ret_type = 'const ' + ret_type if variant.refret and ret_type.endswith('&') == False: ret_type += '&' arg_types = [] orig_arg_types = [] def_args = [] for arg in variant.args: if arg.tp in type_dict: arg_type = type_dict[arg.tp] else: arg_type = arg.tp #if arg.outputarg: # arg_type += '&' orig_arg_types.append(arg_type) if with_default_params and arg.defval != '': def_args.append(arg.defval) arg_types.append(orig_arg_types[-1]) # Function attribure func_attribs = '' if '*' in ''.join(orig_arg_types): func_attribs += ', allow_raw_pointers()' if variant.is_pure_virtual: func_attribs += ', pure_virtual()' #TODO better naming #if variant.name in self.jsfunctions: #else js_func_name = variant.name c_func_name = func.cname if (factory and variant.is_class_method == False) else func_name ################################### Binding for j in range(0, len(def_args) + 1): postfix = '' if j > 0: postfix = '_' + str(j); if factory: binding_text = ctr_template.substitute(const='const' if variant.is_const else '', cpp_name=c_func_name+postfix, ret=ret_type, args=','.join(arg_types[:len(arg_types)-j]), optional=func_attribs) else: binding_template = overload_class_static_function_template if variant.is_class_method else \ overload_function_template if class_info == None else overload_class_function_template binding_text = binding_template.substitute(js_name=js_func_name, const='const' if variant.is_const else '', cpp_name=c_func_name+postfix, ret=ret_type, args=','.join(arg_types[:len(arg_types)-1]), optional=func_attribs) binding_text_list.append(binding_text) return binding_text_list def print_decls(self, decls): """ Prints the list of declarations, retrieived by the parse() method """ for d in decls: print(d[0], d[1], ";".join(d[2])) for a in d[3]: print(" ", a[0], a[1], a[2], end="") if a[3]: print("; ".join(a[3])) else: print() def gen(self, dst_file, src_files, core_bindings): # step 1: scan the headers and extract classes, enums and functions headers = [] for hdr in src_files: decls = self.parser.parse(hdr) # print(hdr); # self.print_decls(decls); if len(decls) == 0: continue headers.append(hdr[hdr.rindex('opencv2/'):]) for decl in decls: name = decl[0] type = name[:name.find(" ")] if type == "struct" or type == "class": # class/structure case name = name[name.find(" ") + 1:].strip() self.add_class(type, name, decl) elif name.startswith("enum"): # enumerations self.add_enum(decl) elif name.startswith("const"): # constant self.add_const(name.replace("const ", "").strip(), decl) else: # class/global function self.add_func(decl) # step 2: generate bindings # Global functions for ns_name, ns in sorted(self.namespaces.items()): if ns_name.split('.')[0] != 'cv': continue for name, func in sorted(ns.funcs.items()): if name in ignore_list: continue if not name in white_list['']: continue ext_cnst = False # Check if the method is an external constructor for variant in func.variants: if "Ptr<" in variant.rettype: # Register the smart pointer base_class_name = variant.rettype base_class_name = base_class_name.replace("Ptr<","").replace(">","").strip() self.classes[base_class_name].has_smart_ptr = True # Adds the external constructor class_name = func.name.replace("create", "") if not class_name in self.classes: self.classes[base_class_name].methods[func.cname] = func else: self.classes[class_name].methods[func.cname] = func ext_cnst = True if ext_cnst: continue if with_wrapped_functions: binding, wrapper = self.gen_function_binding_with_wrapper(func, class_info=None) self.bindings += binding self.wrapper_funcs += wrapper else: binding = self.gen_function_binding(func, class_info=None) self.bindings+=binding # generate code for the classes and their methods class_list = list(self.classes.items()) for name, class_info in class_list: class_bindings = [] if not name in white_list: continue # Generate bindings for methods for method_name, method in class_info.methods.items(): if method.cname in ignore_list: continue if not method.name in white_list[method.class_name]: continue if method.is_constructor: for variant in method.variants: args = [] for arg in variant.args: arg_type = type_dict[arg.tp] if arg.tp in type_dict else arg.tp args.append(arg_type) # print('Constructor: ', class_info.name, len(variant.args)) args_num = len(variant.args) if args_num in class_info.constructor_arg_num: continue class_info.constructor_arg_num.add(args_num) class_bindings.append(constructor_template.substitute(signature=', '.join(args))) else: if with_wrapped_functions and (len(method.variants) > 1 or len(method.variants[0].args)>0 or "String" in method.variants[0].rettype): binding, wrapper = self.gen_function_binding_with_wrapper(method, class_info=class_info) self.wrapper_funcs = self.wrapper_funcs + wrapper class_bindings = class_bindings + binding else: binding = self.gen_function_binding(method, class_info=class_info) class_bindings = class_bindings + binding # Regiseter Smart pointer if class_info.has_smart_ptr: class_bindings.append(smart_ptr_reg_template.substitute(cname=class_info.cname, name=class_info.name)) # Attach external constructors # for method_name, method in class_info.ext_constructors.items(): # print("ext constructor", method_name) #if class_info.ext_constructors: # Generate bindings for properties for property in class_info.props: _class_property = class_property_enum_template if property.tp in type_dict else class_property_template class_bindings.append(_class_property.substitute(js_name=property.name, cpp_name='::'.join( [class_info.cname, property.name]))) dv = '' base = Template("""base<$base>""") assert len(class_info.bases) <= 1 , "multiple inheritance not supported" if len(class_info.bases) == 1: dv = "," + base.substitute(base=', '.join(class_info.bases)) self.bindings.append(class_template.substitute(cpp_name=class_info.cname, js_name=name, class_templates=''.join(class_bindings), derivation=dv)) if export_enums: # step 4: generate bindings for enums # TODO anonymous enums are ignored for now. for ns_name, ns in sorted(self.namespaces.items()): if ns_name.split('.')[0] != 'cv': continue for name, enum in sorted(ns.enums.items()): if not name.endswith('.anonymous'): name = name.replace("cv.", "") enum_values = [] for enum_val in enum: value = enum_val[0][enum_val[0].rfind(".")+1:] enum_values.append(enum_item_template.substitute(val=value, cpp_val=name.replace('.', '::')+'::'+value)) self.bindings.append(enum_template.substitute(cpp_name=name.replace(".", "::"), js_name=name.replace(".", "_"), enum_items=''.join(enum_values))) else: print(name) #TODO: represent anonymous enums with constants if export_consts: # step 5: generate bindings for consts for ns_name, ns in sorted(self.namespaces.items()): if ns_name.split('.')[0] != 'cv': continue for name, const in sorted(ns.consts.items()): # print("Gen consts: ", name, const) self.bindings.append(const_template.substitute(js_name=name, value=const)) with open(core_bindings) as f: ret = f.read() header_includes = '\n'.join(['#include "{}"'.format(hdr) for hdr in headers]) ret = ret.replace('@INCLUDES@', header_includes) defis = '\n'.join(self.wrapper_funcs) ret += wrapper_codes_template.substitute(ns=wrapper_namespace, defs=defis) ret += emscripten_binding_template.substitute(binding_name='testBinding', bindings=''.join(self.bindings)) # print(ret) text_file = open(dst_file, "w") text_file.write(ret) text_file.close() if __name__ == "__main__": if len(sys.argv) < 4: print("Usage:\n", \ os.path.basename(sys.argv[0]), \ "<full path to hdr_parser.py> <bindings.cpp> <headers.txt> <core_bindings.cpp>") print("Current args are: ", ", ".join(["'"+a+"'" for a in sys.argv])) exit(0) dstdir = "." hdr_parser_path = os.path.abspath(sys.argv[1]) if hdr_parser_path.endswith(".py"): hdr_parser_path = os.path.dirname(hdr_parser_path) sys.path.append(hdr_parser_path) import hdr_parser bindingsCpp = sys.argv[2] headers = open(sys.argv[3], 'r').read().split(';') coreBindings = sys.argv[4] generator = JSWrapperGenerator() generator.gen(bindingsCpp, headers, coreBindings)
############################################################################### # # IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. # # By downloading, copying, installing or using the software you agree to this license. # If you do not agree to this license, do not download, install, # copy or use the software. # # # License Agreement # For Open Source Computer Vision Library # # Copyright (C) 2013, OpenCV Foundation, all rights reserved. # Third party copyrights are property of their respective owners. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistribution's of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # * Redistribution's in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * The name of the copyright holders may not be used to endorse or promote products # derived from this software without specific prior written permission. # # This software is provided by the copyright holders and contributors "as is" and # any express or implied warranties, including, but not limited to, the implied # warranties of merchantability and fitness for a particular purpose are disclaimed. # In no event shall the Intel Corporation or contributors be liable for any direct, # indirect, incidental, special, exemplary, or consequential damages # (including, but not limited to, procurement of substitute goods or services; # loss of use, data, or profits; or business interruption) however caused # and on any theory of liability, whether in contract, strict liability, # or tort (including negligence or otherwise) arising in any way out of # the use of this software, even if advised of the possibility of such damage. # ############################################################################### # AUTHOR: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu # # LICENSE AGREEMENT # Copyright (c) 2015, 2015 The Regents of the University of California (Regents) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the University nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################### import os, sys, re, json, shutil from subprocess import Popen, PIPE, STDOUT def make_umd(opencvjs, cvjs): src = open(opencvjs, 'r+b') dst = open(cvjs, 'w+b') content = src.read() dst.seek(0) # inspired by https://github.com/umdjs/umd/blob/95563fd6b46f06bda0af143ff67292e7f6ede6b7/templates/returnExportsGlobal.js dst.write((""" (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(function () { return (root.cv = factory()); }); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); } else if (typeof window === 'object') { // Browser globals root.cv = factory(); } else if (typeof importScripts === 'function') { // Web worker root.cv = factory; } else { // Other shells, e.g. d8 root.cv = factory(); } }(this, function () { %s if (typeof Module === 'undefined') Module = {}; return cv(Module); })); """ % (content)).lstrip()) if __name__ == "__main__": if len(sys.argv) > 2: opencvjs = sys.argv[1] cvjs = sys.argv[2] if not os.path.isfile(opencvjs): print('opencv.js file not found! Have you compiled the opencv_js module?') exit() make_umd(opencvjs, cvjs);
############################################################################### # # IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. # # By downloading, copying, installing or using the software you agree to this license. # If you do not agree to this license, do not download, install, # copy or use the software. # # # License Agreement # For Open Source Computer Vision Library # # Copyright (C) 2013, OpenCV Foundation, all rights reserved. # Third party copyrights are property of their respective owners. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistribution's of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # * Redistribution's in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * The name of the copyright holders may not be used to endorse or promote products # derived from this software without specific prior written permission. # # This software is provided by the copyright holders and contributors "as is" and # any express or implied warranties, including, but not limited to, the implied # warranties of merchantability and fitness for a particular purpose are disclaimed. # In no event shall the Intel Corporation or contributors be liable for any direct, # indirect, incidental, special, exemplary, or consequential damages # (including, but not limited to, procurement of substitute goods or services; # loss of use, data, or profits; or business interruption) however caused # and on any theory of liability, whether in contract, strict liability, # or tort (including negligence or otherwise) arising in any way out of # the use of this software, even if advised of the possibility of such damage. # ############################################################################### # AUTHOR: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu # # LICENSE AGREEMENT # Copyright (c) 2015, 2015 The Regents of the University of California (Regents) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the University nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################## from string import Template wrapper_codes_template = Template("namespace $ns {\n$defs\n}") call_template = Template("""$func($args)""") class_call_template = Template("""$obj.$func($args)""") static_class_call_template = Template("""$scope$func($args)""") wrapper_function_template = Template(""" $ret_val $func($signature)$const { return $cpp_call; } """) wrapper_function_with_def_args_template = Template(""" $ret_val $func($signature)$const { $check_args } """) wrapper_overload_def_values = [ Template("""return $cpp_call;"""), Template("""if ($arg0.isUndefined()) return $cpp_call; else $next"""), Template("""if ($arg0.isUndefined() && $arg1.isUndefined()) return $cpp_call; else $next"""), Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined()) return $cpp_call; else $next"""), Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined()) return $cpp_call; else $next"""), Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined() && $arg4.isUndefined()) return $cpp_call; else $next"""), Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined() && $arg4.isUndefined() && $arg5.isUndefined() ) return $cpp_call; else $next"""), Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined() && $arg4.isUndefined() && $arg5.isUndefined() && $arg6.isUndefined() ) return $cpp_call; else $next"""), Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined() && $arg4.isUndefined() && $arg5.isUndefined()&& $arg6.isUndefined() && $arg7.isUndefined()) return $cpp_call; else $next"""), Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined() && $arg4.isUndefined() && $arg5.isUndefined()&& $arg6.isUndefined() && $arg7.isUndefined() && $arg8.isUndefined()) return $cpp_call; else $next"""), Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined() && $arg4.isUndefined() && $arg5.isUndefined()&& $arg6.isUndefined() && $arg7.isUndefined()&& $arg8.isUndefined() && $arg9.isUndefined()) return $cpp_call; else $next""")] emscripten_binding_template = Template(""" EMSCRIPTEN_BINDINGS($binding_name) {$bindings } """) simple_function_template = Template(""" emscripten::function("$js_name", &$cpp_name); """) smart_ptr_reg_template = Template(""" .smart_ptr<Ptr<$cname>>("Ptr<$name>") """) overload_function_template = Template(""" function("$js_name", select_overload<$ret($args)$const>(&$cpp_name)$optional); """) overload_class_function_template = Template(""" .function("$js_name", select_overload<$ret($args)$const>(&$cpp_name)$optional)""") overload_class_static_function_template = Template(""" .class_function("$js_name", select_overload<$ret($args)$const>(&$cpp_name)$optional)""") class_property_template = Template(""" .property("$js_name", &$cpp_name)""") class_property_enum_template = Template(""" .property("$js_name", binding_utils::underlying_ptr(&$cpp_name))""") ctr_template = Template(""" .constructor(select_overload<$ret($args)$const>(&$cpp_name)$optional)""") smart_ptr_ctr_overload_template = Template(""" .smart_ptr_constructor("$ptr_type", select_overload<$ret($args)$const>(&$cpp_name)$optional)""") function_template = Template(""" .function("$js_name", &$cpp_name)""") static_function_template = Template(""" .class_function("$js_name", &$cpp_name)""") constructor_template = Template(""" .constructor<$signature>()""") enum_item_template = Template(""" .value("$val", $cpp_val)""") enum_template = Template(""" emscripten::enum_<$cpp_name>("$js_name")$enum_items; """) const_template = Template(""" constant("$js_name", static_cast<long>($value)); """) vector_template = Template(""" emscripten::register_vector<$cType>("$js_name"); """) map_template = Template(""" emscripten::register_map<cpp_type_key,$cpp_type_val>("$js_name"); """) class_template = Template(""" emscripten::class_<$cpp_name $derivation>("$js_name")$class_templates; """)
#!/usr/bin/env python from __future__ import print_function import sys, os, re classes_ignore_list = ( 'OpenCV(Test)?Case', 'OpenCV(Test)?Runner', 'CvException', ) funcs_ignore_list = ( '\w+--HashCode', 'Mat--MatLong', '\w+--Equals', 'Core--MinMaxLocResult', ) class JavaParser: def __init__(self): self.clear() def clear(self): self.mdict = {} self.tdict = {} self.mwhere = {} self.twhere = {} self.empty_stubs_cnt = 0 self.r1 = re.compile("\s*public\s+(?:static\s+)?(\w+)\(([^)]*)\)") # c-tor self.r2 = re.compile("\s*(?:(?:public|static|final)\s+){1,3}\S+\s+(\w+)\(([^)]*)\)") self.r3 = re.compile('\s*fail\("Not yet implemented"\);') # empty test stub def dict2set(self, d): s = set() for f in d.keys(): if len(d[f]) == 1: s.add(f) else: s |= set(d[f]) return s def get_tests_count(self): return len(self.tdict) def get_empty_stubs_count(self): return self.empty_stubs_cnt def get_funcs_count(self): return len(self.dict2set(self.mdict)), len(self.mdict) def get_not_tested(self): mset = self.dict2set(self.mdict) tset = self.dict2set(self.tdict) nottested = mset - tset out = set() for name in nottested: out.add(name + " " + self.mwhere[name]) return out def parse(self, path): if ".svn" in path: return if os.path.isfile(path): if path.endswith("FeatureDetector.java"): for prefix1 in ("", "Grid", "Pyramid", "Dynamic"): for prefix2 in ("FAST", "STAR", "MSER", "ORB", "SIFT", "SURF", "GFTT", "HARRIS", "SIMPLEBLOB", "DENSE"): parser.parse_file(path,prefix1+prefix2) elif path.endswith("DescriptorExtractor.java"): for prefix1 in ("", "Opponent"): for prefix2 in ("BRIEF", "ORB", "SIFT", "SURF"): parser.parse_file(path,prefix1+prefix2) elif path.endswith("GenericDescriptorMatcher.java"): for prefix in ("OneWay", "Fern"): parser.parse_file(path,prefix) elif path.endswith("DescriptorMatcher.java"): for prefix in ("BruteForce", "BruteForceHamming", "BruteForceHammingLUT", "BruteForceL1", "FlannBased", "BruteForceSL2"): parser.parse_file(path,prefix) else: parser.parse_file(path) elif os.path.isdir(path): for x in os.listdir(path): self.parse(path + "/" + x) return def parse_file(self, fname, prefix = ""): istest = fname.endswith("Test.java") clsname = os.path.basename(fname).replace("Test", "").replace(".java", "") clsname = prefix + clsname[0].upper() + clsname[1:] for cls in classes_ignore_list: if re.match(cls, clsname): return f = open(fname, "rt") linenum = 0 for line in f: linenum += 1 m1 = self.r1.match(line) m2 = self.r2.match(line) m3 = self.r3.match(line) func = '' args_str = '' if m1: func = m1.group(1) args_str = m1.group(2) elif m2: if "public" not in line: continue func = m2.group(1) args_str = m2.group(2) elif m3: self.empty_stubs_cnt += 1 continue else: #if "public" in line: #print "UNRECOGNIZED: " + line continue d = (self.mdict, self.tdict)[istest] w = (self.mwhere, self.twhere)[istest] func = re.sub(r"^test", "", func) func = clsname + "--" + func[0].upper() + func[1:] args_str = args_str.replace("[]", "Array").replace("...", "Array ") args_str = re.sub(r"List<(\w+)>", "ListOf\g<1>", args_str) args_str = re.sub(r"List<(\w+)>", "ListOf\g<1>", args_str) args = [a.split()[0] for a in args_str.split(",") if a] func_ex = func + "".join([a[0].upper() + a[1:] for a in args]) func_loc = fname + " (line: " + str(linenum) + ")" skip = False for fi in funcs_ignore_list: if re.match(fi, func_ex): skip = True break if skip: continue if func in d: d[func].append(func_ex) else: d[func] = [func_ex] w[func_ex] = func_loc w[func] = func_loc f.close() return if __name__ == '__main__': if len(sys.argv) < 2: print("Usage:\n", \ os.path.basename(sys.argv[0]), \ "<Classes/Tests dir1/file1> [<Classes/Tests dir2/file2> ...]\n", "Not tested methods are loggedto stdout.") exit(0) parser = JavaParser() for x in sys.argv[1:]: parser.parse(x) funcs = parser.get_not_tested() if funcs: print ('{} {}'.format("NOT TESTED methods:\n\t", "\n\t".join(sorted(funcs)))) print ("Total methods found: %i (%i)" % parser.get_funcs_count()) print ('{} {}'.format("Not tested methods found:", len(funcs))) print ('{} {}'.format("Total tests found:", parser.get_tests_count())) print ('{} {}'.format("Empty test stubs found:", parser.get_empty_stubs_count()))
#!/usr/bin/env python import sys, re, os.path, errno, fnmatch import json import logging import codecs from shutil import copyfile from pprint import pformat from string import Template if sys.version_info[0] >= 3: from io import StringIO else: import io class StringIO(io.StringIO): def write(self, s): if isinstance(s, str): s = unicode(s) # noqa: F821 return super(StringIO, self).write(s) SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) # list of modules + files remap config = None ROOT_DIR = None FILES_REMAP = {} def checkFileRemap(path): path = os.path.realpath(path) if path in FILES_REMAP: return FILES_REMAP[path] assert path[-3:] != '.in', path return path total_files = 0 updated_files = 0 module_imports = [] module_j_code = None module_jn_code = None # list of class names, which should be skipped by wrapper generator # the list is loaded from misc/java/gen_dict.json defined for the module and its dependencies class_ignore_list = [] # list of constant names, which should be skipped by wrapper generator # ignored constants can be defined using regular expressions const_ignore_list = [] # list of private constants const_private_list = [] # { Module : { public : [[name, val],...], private : [[]...] } } missing_consts = {} # c_type : { java/jni correspondence } # Complex data types are configured for each module using misc/java/gen_dict.json type_dict = { # "simple" : { j_type : "?", jn_type : "?", jni_type : "?", suffix : "?" }, "" : { "j_type" : "", "jn_type" : "long", "jni_type" : "jlong" }, # c-tor ret_type "void" : { "j_type" : "void", "jn_type" : "void", "jni_type" : "void" }, "env" : { "j_type" : "", "jn_type" : "", "jni_type" : "JNIEnv*"}, "cls" : { "j_type" : "", "jn_type" : "", "jni_type" : "jclass"}, "bool" : { "j_type" : "boolean", "jn_type" : "boolean", "jni_type" : "jboolean", "suffix" : "Z" }, "char" : { "j_type" : "char", "jn_type" : "char", "jni_type" : "jchar", "suffix" : "C" }, "int" : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" }, "long" : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" }, "float" : { "j_type" : "float", "jn_type" : "float", "jni_type" : "jfloat", "suffix" : "F" }, "double" : { "j_type" : "double", "jn_type" : "double", "jni_type" : "jdouble", "suffix" : "D" }, "size_t" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" }, "__int64" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" }, "int64" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" }, "double[]": { "j_type" : "double[]", "jn_type" : "double[]", "jni_type" : "jdoubleArray", "suffix" : "_3D" }, 'string' : { # std::string, see "String" in modules/core/misc/java/gen_dict.json 'j_type': 'String', 'jn_type': 'String', 'jni_name': 'n_%(n)s', 'jni_type': 'jstring', 'jni_var': 'const char* utf_%(n)s = env->GetStringUTFChars(%(n)s, 0); std::string n_%(n)s( utf_%(n)s ? utf_%(n)s : "" ); env->ReleaseStringUTFChars(%(n)s, utf_%(n)s)', 'suffix': 'Ljava_lang_String_2', 'j_import': 'java.lang.String' }, 'vector_string': { # std::vector<std::string>, see "vector_String" in modules/core/misc/java/gen_dict.json 'j_type': 'List<String>', 'jn_type': 'List<String>', 'jni_type': 'jobject', 'jni_var': 'std::vector< std::string > %(n)s', 'suffix': 'Ljava_util_List', 'v_type': 'string', 'j_import': 'java.lang.String' }, } # Defines a rule to add extra prefixes for names from specific namespaces. # In example, cv::fisheye::stereoRectify from namespace fisheye is wrapped as fisheye_stereoRectify namespaces_dict = {} # { class : { func : {j_code, jn_code, cpp_code} } } ManualFuncs = {} # { class : { func : { arg_name : {"ctype" : ctype, "attrib" : [attrib]} } } } func_arg_fix = {} def read_contents(fname): with open(fname, 'r') as f: data = f.read() return data def mkdir_p(path): ''' mkdir -p ''' try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise T_JAVA_START_INHERITED = read_contents(os.path.join(SCRIPT_DIR, 'templates/java_class_inherited.prolog')) T_JAVA_START_ORPHAN = read_contents(os.path.join(SCRIPT_DIR, 'templates/java_class.prolog')) T_JAVA_START_MODULE = read_contents(os.path.join(SCRIPT_DIR, 'templates/java_module.prolog')) T_CPP_MODULE = Template(read_contents(os.path.join(SCRIPT_DIR, 'templates/cpp_module.template'))) class GeneralInfo(): def __init__(self, type, decl, namespaces): self.namespace, self.classpath, self.classname, self.name = self.parseName(decl[0], namespaces) # parse doxygen comments self.params={} self.annotation=[] if type == "class": docstring="// C++: class " + self.name + "\n" else: docstring="" if len(decl)>5 and decl[5]: doc = decl[5] #logging.info('docstring: %s', doc) if re.search("(@|\\\\)deprecated", doc): self.annotation.append("@Deprecated") docstring += sanitize_java_documentation_string(doc, type) self.docstring = docstring def parseName(self, name, namespaces): ''' input: full name and available namespaces returns: (namespace, classpath, classname, name) ''' name = name[name.find(" ")+1:].strip() # remove struct/class/const prefix spaceName = "" localName = name # <classes>.<name> for namespace in sorted(namespaces, key=len, reverse=True): if name.startswith(namespace + "."): spaceName = namespace localName = name.replace(namespace + ".", "") break pieces = localName.split(".") if len(pieces) > 2: # <class>.<class>.<class>.<name> return spaceName, ".".join(pieces[:-1]), pieces[-2], pieces[-1] elif len(pieces) == 2: # <class>.<name> return spaceName, pieces[0], pieces[0], pieces[1] elif len(pieces) == 1: # <name> return spaceName, "", "", pieces[0] else: return spaceName, "", "" # error?! def fullName(self, isCPP=False): result = ".".join([self.fullClass(), self.name]) return result if not isCPP else get_cname(result) def fullClass(self, isCPP=False): result = ".".join([f for f in [self.namespace] + self.classpath.split(".") if len(f)>0]) return result if not isCPP else get_cname(result) class ConstInfo(GeneralInfo): def __init__(self, decl, addedManually=False, namespaces=[], enumType=None): GeneralInfo.__init__(self, "const", decl, namespaces) self.cname = get_cname(self.name) self.value = decl[1] self.enumType = enumType self.addedManually = addedManually if self.namespace in namespaces_dict: self.name = '%s_%s' % (namespaces_dict[self.namespace], self.name) def __repr__(self): return Template("CONST $name=$value$manual").substitute(name=self.name, value=self.value, manual="(manual)" if self.addedManually else "") def isIgnored(self): for c in const_ignore_list: if re.match(c, self.name): return True return False def normalize_field_name(name): return name.replace(".","_").replace("[","").replace("]","").replace("_getNativeObjAddr()","_nativeObj") def normalize_class_name(name): return re.sub(r"^cv\.", "", name).replace(".", "_") def get_cname(name): return name.replace(".", "::") def cast_from(t): if t in type_dict and "cast_from" in type_dict[t]: return type_dict[t]["cast_from"] return t def cast_to(t): if t in type_dict and "cast_to" in type_dict[t]: return type_dict[t]["cast_to"] return t class ClassPropInfo(): def __init__(self, decl): # [f_ctype, f_name, '', '/RW'] self.ctype = decl[0] self.name = decl[1] self.rw = "/RW" in decl[3] def __repr__(self): return Template("PROP $ctype $name").substitute(ctype=self.ctype, name=self.name) class ClassInfo(GeneralInfo): def __init__(self, decl, namespaces=[]): # [ 'class/struct cname', ': base', [modlist] ] GeneralInfo.__init__(self, "class", decl, namespaces) self.cname = get_cname(self.name) self.methods = [] self.methods_suffixes = {} self.consts = [] # using a list to save the occurrence order self.private_consts = [] self.imports = set() self.props= [] self.jname = self.name self.smart = None # True if class stores Ptr<T>* instead of T* in nativeObj field self.j_code = None # java code stream self.jn_code = None # jni code stream self.cpp_code = None # cpp code stream for m in decl[2]: if m.startswith("="): self.jname = m[1:] self.base = '' if decl[1]: #self.base = re.sub(r"\b"+self.jname+r"\b", "", decl[1].replace(":", "")).strip() self.base = re.sub(r"^.*:", "", decl[1].split(",")[0]).strip().replace(self.jname, "") def __repr__(self): return Template("CLASS $namespace::$classpath.$name : $base").substitute(**self.__dict__) def getAllImports(self, module): return ["import %s;" % c for c in sorted(self.imports) if not c.startswith('org.opencv.'+module) and (not c.startswith('java.lang.') or c.count('.') != 2)] def addImports(self, ctype): if ctype in type_dict: if "j_import" in type_dict[ctype]: self.imports.add(type_dict[ctype]["j_import"]) if "v_type" in type_dict[ctype]: self.imports.add("java.util.List") self.imports.add("java.util.ArrayList") self.imports.add("org.opencv.utils.Converters") if type_dict[ctype]["v_type"] in ("Mat", "vector_Mat"): self.imports.add("org.opencv.core.Mat") def getAllMethods(self): result = [] result.extend([fi for fi in sorted(self.methods) if fi.isconstructor]) result.extend([fi for fi in sorted(self.methods) if not fi.isconstructor]) return result def addMethod(self, fi): self.methods.append(fi) def getConst(self, name): for cand in self.consts + self.private_consts: if cand.name == name: return cand return None def addConst(self, constinfo): # choose right list (public or private) consts = self.consts for c in const_private_list: if re.match(c, constinfo.name): consts = self.private_consts break consts.append(constinfo) def initCodeStreams(self, Module): self.j_code = StringIO() self.jn_code = StringIO() self.cpp_code = StringIO() if self.base: self.j_code.write(T_JAVA_START_INHERITED) else: if self.name != Module: self.j_code.write(T_JAVA_START_ORPHAN) else: self.j_code.write(T_JAVA_START_MODULE) # misc handling if self.name == Module: for i in module_imports or []: self.imports.add(i) if module_j_code: self.j_code.write(module_j_code) if module_jn_code: self.jn_code.write(module_jn_code) def cleanupCodeStreams(self): self.j_code.close() self.jn_code.close() self.cpp_code.close() def generateJavaCode(self, m, M): return Template(self.j_code.getvalue() + "\n\n" + self.jn_code.getvalue() + "\n}\n").substitute( module = m, name = self.name, jname = self.jname, imports = "\n".join(self.getAllImports(M)), docs = self.docstring, annotation = "\n" + "\n".join(self.annotation) if self.annotation else "", base = self.base) def generateCppCode(self): return self.cpp_code.getvalue() class ArgInfo(): def __init__(self, arg_tuple): # [ ctype, name, def val, [mod], argno ] self.pointer = False ctype = arg_tuple[0] if ctype.endswith("*"): ctype = ctype[:-1] self.pointer = True self.ctype = ctype self.name = arg_tuple[1] self.defval = arg_tuple[2] self.out = "" if "/O" in arg_tuple[3]: self.out = "O" if "/IO" in arg_tuple[3]: self.out = "IO" def __repr__(self): return Template("ARG $ctype$p $name=$defval").substitute(ctype=self.ctype, p=" *" if self.pointer else "", name=self.name, defval=self.defval) class FuncInfo(GeneralInfo): def __init__(self, decl, namespaces=[]): # [ funcname, return_ctype, [modifiers], [args] ] GeneralInfo.__init__(self, "func", decl, namespaces) self.cname = get_cname(decl[0]) self.jname = self.name self.isconstructor = self.name == self.classname if "[" in self.name: self.jname = "getelem" if self.namespace in namespaces_dict: self.jname = '%s_%s' % (namespaces_dict[self.namespace], self.jname) for m in decl[2]: if m.startswith("="): self.jname = m[1:] self.static = ["","static"][ "/S" in decl[2] ] self.ctype = re.sub(r"^CvTermCriteria", "TermCriteria", decl[1] or "") self.args = [] func_fix_map = func_arg_fix.get(self.jname, {}) for a in decl[3]: arg = a[:] arg_fix_map = func_fix_map.get(arg[1], {}) arg[0] = arg_fix_map.get('ctype', arg[0]) #fixing arg type arg[3] = arg_fix_map.get('attrib', arg[3]) #fixing arg attrib self.args.append(ArgInfo(arg)) def __repr__(self): return Template("FUNC <$ctype $namespace.$classpath.$name $args>").substitute(**self.__dict__) def __lt__(self, other): return self.__repr__() < other.__repr__() class JavaWrapperGenerator(object): def __init__(self): self.cpp_files = [] self.clear() def clear(self): self.namespaces = set(["cv"]) self.classes = { "Mat" : ClassInfo([ 'class Mat', '', [], [] ], self.namespaces) } self.module = "" self.Module = "" self.ported_func_list = [] self.skipped_func_list = [] self.def_args_hist = {} # { def_args_cnt : funcs_cnt } def add_class(self, decl): classinfo = ClassInfo(decl, namespaces=self.namespaces) if classinfo.name in class_ignore_list: logging.info('ignored: %s', classinfo) return name = classinfo.name if self.isWrapped(name) and not classinfo.base: logging.warning('duplicated: %s', classinfo) return self.classes[name] = classinfo if name in type_dict and not classinfo.base: logging.warning('duplicated: %s', classinfo) return type_dict.setdefault(name, {}).update( { "j_type" : classinfo.jname, "jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),), "jni_name" : "(*("+classinfo.fullName(isCPP=True)+"*)%(n)s_nativeObj)", "jni_type" : "jlong", "suffix" : "J", "j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname) } ) type_dict.setdefault(name+'*', {}).update( { "j_type" : classinfo.jname, "jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),), "jni_name" : "("+classinfo.fullName(isCPP=True)+"*)%(n)s_nativeObj", "jni_type" : "jlong", "suffix" : "J", "j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname) } ) # missing_consts { Module : { public : [[name, val],...], private : [[]...] } } if name in missing_consts: if 'private' in missing_consts[name]: for (n, val) in missing_consts[name]['private']: classinfo.private_consts.append( ConstInfo([n, val], addedManually=True) ) if 'public' in missing_consts[name]: for (n, val) in missing_consts[name]['public']: classinfo.consts.append( ConstInfo([n, val], addedManually=True) ) # class props for p in decl[3]: if True: #"vector" not in p[0]: classinfo.props.append( ClassPropInfo(p) ) else: logging.warning("Skipped property: [%s]" % name, p) if classinfo.base: classinfo.addImports(classinfo.base) type_dict.setdefault("Ptr_"+name, {}).update( { "j_type" : classinfo.jname, "jn_type" : "long", "jn_args" : (("__int64", ".getNativeObjAddr()"),), "jni_name" : "*((Ptr<"+classinfo.fullName(isCPP=True)+">*)%(n)s_nativeObj)", "jni_type" : "jlong", "suffix" : "J", "j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname) } ) logging.info('ok: class %s, name: %s, base: %s', classinfo, name, classinfo.base) def add_const(self, decl, enumType=None): # [ "const cname", val, [], [] ] constinfo = ConstInfo(decl, namespaces=self.namespaces, enumType=enumType) if constinfo.isIgnored(): logging.info('ignored: %s', constinfo) else: if not self.isWrapped(constinfo.classname): logging.info('class not found: %s', constinfo) constinfo.name = constinfo.classname + '_' + constinfo.name constinfo.classname = '' ci = self.getClass(constinfo.classname) duplicate = ci.getConst(constinfo.name) if duplicate: if duplicate.addedManually: logging.info('manual: %s', constinfo) else: logging.warning('duplicated: %s', constinfo) else: ci.addConst(constinfo) logging.info('ok: %s', constinfo) def add_enum(self, decl): # [ "enum cname", "", [], [] ] enumType = decl[0].rsplit(" ", 1)[1] if enumType.endswith("<unnamed>"): enumType = None else: ctype = normalize_class_name(enumType) type_dict[ctype] = { "cast_from" : "int", "cast_to" : get_cname(enumType), "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" } const_decls = decl[3] for decl in const_decls: self.add_const(decl, enumType) def add_func(self, decl): fi = FuncInfo(decl, namespaces=self.namespaces) classname = fi.classname or self.Module if classname in class_ignore_list: logging.info('ignored: %s', fi) elif classname in ManualFuncs and fi.jname in ManualFuncs[classname]: logging.info('manual: %s', fi) elif not self.isWrapped(classname): logging.warning('not found: %s', fi) else: self.getClass(classname).addMethod(fi) logging.info('ok: %s', fi) # calc args with def val cnt = len([a for a in fi.args if a.defval]) self.def_args_hist[cnt] = self.def_args_hist.get(cnt, 0) + 1 def save(self, path, buf): global total_files, updated_files total_files += 1 if os.path.exists(path): with open(path, "rt") as f: content = f.read() if content == buf: return with codecs.open(path, "w", "utf-8") as f: f.write(buf) updated_files += 1 def gen(self, srcfiles, module, output_path, output_jni_path, output_java_path, common_headers): self.clear() self.module = module self.Module = module.capitalize() # TODO: support UMat versions of declarations (implement UMat-wrapper for Java) parser = hdr_parser.CppHeaderParser(generate_umat_decls=False) self.add_class( ['class ' + self.Module, '', [], []] ) # [ 'class/struct cname', ':bases', [modlist] [props] ] # scan the headers and build more descriptive maps of classes, consts, functions includes = [] for hdr in common_headers: logging.info("\n===== Common header : %s =====", hdr) includes.append('#include "' + hdr + '"') for hdr in srcfiles: decls = parser.parse(hdr) self.namespaces = parser.namespaces logging.info("\n\n===== Header: %s =====", hdr) logging.info("Namespaces: %s", parser.namespaces) if decls: includes.append('#include "' + hdr + '"') else: logging.info("Ignore header: %s", hdr) for decl in decls: logging.info("\n--- Incoming ---\n%s", pformat(decl[:5], 4)) # without docstring name = decl[0] if name.startswith("struct") or name.startswith("class"): self.add_class(decl) elif name.startswith("const"): self.add_const(decl) elif name.startswith("enum"): # enum self.add_enum(decl) else: # function self.add_func(decl) logging.info("\n\n===== Generating... =====") moduleCppCode = StringIO() package_path = os.path.join(output_java_path, module) mkdir_p(package_path) for ci in self.classes.values(): if ci.name == "Mat": continue ci.initCodeStreams(self.Module) self.gen_class(ci) classJavaCode = ci.generateJavaCode(self.module, self.Module) self.save("%s/%s/%s.java" % (output_java_path, module, ci.jname), classJavaCode) moduleCppCode.write(ci.generateCppCode()) ci.cleanupCodeStreams() cpp_file = os.path.abspath(os.path.join(output_jni_path, module + ".inl.hpp")) self.cpp_files.append(cpp_file) self.save(cpp_file, T_CPP_MODULE.substitute(m = module, M = module.upper(), code = moduleCppCode.getvalue(), includes = "\n".join(includes))) self.save(os.path.join(output_path, module+".txt"), self.makeReport()) def makeReport(self): ''' Returns string with generator report ''' report = StringIO() total_count = len(self.ported_func_list)+ len(self.skipped_func_list) report.write("PORTED FUNCs LIST (%i of %i):\n\n" % (len(self.ported_func_list), total_count)) report.write("\n".join(self.ported_func_list)) report.write("\n\nSKIPPED FUNCs LIST (%i of %i):\n\n" % (len(self.skipped_func_list), total_count)) report.write("".join(self.skipped_func_list)) for i in self.def_args_hist.keys(): report.write("\n%i def args - %i funcs" % (i, self.def_args_hist[i])) return report.getvalue() def fullTypeName(self, t): if self.isWrapped(t): return self.getClass(t).fullName(isCPP=True) else: return cast_from(t) def gen_func(self, ci, fi, prop_name=''): logging.info("%s", fi) j_code = ci.j_code jn_code = ci.jn_code cpp_code = ci.cpp_code # c_decl # e.g: void add(Mat src1, Mat src2, Mat dst, Mat mask = Mat(), int dtype = -1) if prop_name: c_decl = "%s %s::%s" % (fi.ctype, fi.classname, prop_name) else: decl_args = [] for a in fi.args: s = a.ctype or ' _hidden_ ' if a.pointer: s += "*" elif a.out: s += "&" s += " " + a.name if a.defval: s += " = "+a.defval decl_args.append(s) c_decl = "%s %s %s(%s)" % ( fi.static, fi.ctype, fi.cname, ", ".join(decl_args) ) # java comment j_code.write( "\n //\n // C++: %s\n //\n\n" % c_decl ) # check if we 'know' all the types if fi.ctype not in type_dict: # unsupported ret type msg = "// Return type '%s' is not supported, skipping the function\n\n" % fi.ctype self.skipped_func_list.append(c_decl + "\n" + msg) j_code.write( " "*4 + msg ) logging.warning("SKIP:" + c_decl.strip() + "\t due to RET type " + fi.ctype) return for a in fi.args: if a.ctype not in type_dict: if not a.defval and a.ctype.endswith("*"): a.defval = 0 if a.defval: a.ctype = '' continue msg = "// Unknown type '%s' (%s), skipping the function\n\n" % (a.ctype, a.out or "I") self.skipped_func_list.append(c_decl + "\n" + msg) j_code.write( " "*4 + msg ) logging.warning("SKIP:" + c_decl.strip() + "\t due to ARG type " + a.ctype + "/" + (a.out or "I")) return self.ported_func_list.append(c_decl) # jn & cpp comment jn_code.write( "\n // C++: %s\n" % c_decl ) cpp_code.write( "\n//\n// %s\n//\n" % c_decl ) # java args args = fi.args[:] # copy j_signatures=[] suffix_counter = int(ci.methods_suffixes.get(fi.jname, -1)) while True: suffix_counter += 1 ci.methods_suffixes[fi.jname] = suffix_counter # java native method args jn_args = [] # jni (cpp) function args jni_args = [ArgInfo([ "env", "env", "", [], "" ]), ArgInfo([ "cls", "", "", [], "" ])] j_prologue = [] j_epilogue = [] c_prologue = [] c_epilogue = [] if type_dict[fi.ctype]["jni_type"] == "jdoubleArray": fields = type_dict[fi.ctype]["jn_args"] c_epilogue.append( \ ("jdoubleArray _da_retval_ = env->NewDoubleArray(%(cnt)i); " + "jdouble _tmp_retval_[%(cnt)i] = {%(args)s}; " + "env->SetDoubleArrayRegion(_da_retval_, 0, %(cnt)i, _tmp_retval_);") % { "cnt" : len(fields), "args" : ", ".join(["(jdouble)_retval_" + f[1] for f in fields]) } ) if fi.classname and fi.ctype and not fi.static: # non-static class method except c-tor # adding 'self' jn_args.append ( ArgInfo([ "__int64", "nativeObj", "", [], "" ]) ) jni_args.append( ArgInfo([ "__int64", "self", "", [], "" ]) ) ci.addImports(fi.ctype) for a in args: if not a.ctype: # hidden continue ci.addImports(a.ctype) if "v_type" in type_dict[a.ctype]: # pass as vector if type_dict[a.ctype]["v_type"] in ("Mat", "vector_Mat"): #pass as Mat or vector_Mat jn_args.append ( ArgInfo([ "__int64", "%s_mat.nativeObj" % a.name, "", [], "" ]) ) jni_args.append ( ArgInfo([ "__int64", "%s_mat_nativeObj" % a.name, "", [], "" ]) ) c_prologue.append( type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";" ) c_prologue.append( "Mat& %(n)s_mat = *((Mat*)%(n)s_mat_nativeObj)" % {"n" : a.name} + ";" ) if "I" in a.out or not a.out: if type_dict[a.ctype]["v_type"] == "vector_Mat": j_prologue.append( "List<Mat> %(n)s_tmplm = new ArrayList<Mat>((%(n)s != null) ? %(n)s.size() : 0);" % {"n" : a.name } ) j_prologue.append( "Mat %(n)s_mat = Converters.%(t)s_to_Mat(%(n)s, %(n)s_tmplm);" % {"n" : a.name, "t" : a.ctype} ) else: if not type_dict[a.ctype]["j_type"].startswith("MatOf"): j_prologue.append( "Mat %(n)s_mat = Converters.%(t)s_to_Mat(%(n)s);" % {"n" : a.name, "t" : a.ctype} ) else: j_prologue.append( "Mat %s_mat = %s;" % (a.name, a.name) ) c_prologue.append( "Mat_to_%(t)s( %(n)s_mat, %(n)s );" % {"n" : a.name, "t" : a.ctype} ) else: if not type_dict[a.ctype]["j_type"].startswith("MatOf"): j_prologue.append( "Mat %s_mat = new Mat();" % a.name ) else: j_prologue.append( "Mat %s_mat = %s;" % (a.name, a.name) ) if "O" in a.out: if not type_dict[a.ctype]["j_type"].startswith("MatOf"): j_epilogue.append("Converters.Mat_to_%(t)s(%(n)s_mat, %(n)s);" % {"t" : a.ctype, "n" : a.name}) j_epilogue.append( "%s_mat.release();" % a.name ) c_epilogue.append( "%(t)s_to_Mat( %(n)s, %(n)s_mat );" % {"n" : a.name, "t" : a.ctype} ) else: #pass as list jn_args.append ( ArgInfo([ a.ctype, a.name, "", [], "" ]) ) jni_args.append ( ArgInfo([ a.ctype, "%s_list" % a.name , "", [], "" ]) ) c_prologue.append(type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";") if "I" in a.out or not a.out: c_prologue.append("%(n)s = List_to_%(t)s(env, %(n)s_list);" % {"n" : a.name, "t" : a.ctype}) if "O" in a.out: c_epilogue.append("Copy_%s_to_List(env,%s,%s_list);" % (a.ctype, a.name, a.name)) else: fields = type_dict[a.ctype].get("jn_args", ((a.ctype, ""),)) if "I" in a.out or not a.out or self.isWrapped(a.ctype): # input arg, pass by primitive fields for f in fields: jn_args.append ( ArgInfo([ f[0], a.name + f[1], "", [], "" ]) ) jni_args.append( ArgInfo([ f[0], a.name + normalize_field_name(f[1]), "", [], "" ]) ) if "O" in a.out and not self.isWrapped(a.ctype): # out arg, pass as double[] jn_args.append ( ArgInfo([ "double[]", "%s_out" % a.name, "", [], "" ]) ) jni_args.append ( ArgInfo([ "double[]", "%s_out" % a.name, "", [], "" ]) ) j_prologue.append( "double[] %s_out = new double[%i];" % (a.name, len(fields)) ) c_epilogue.append( "jdouble tmp_%(n)s[%(cnt)i] = {%(args)s}; env->SetDoubleArrayRegion(%(n)s_out, 0, %(cnt)i, tmp_%(n)s);" % { "n" : a.name, "cnt" : len(fields), "args" : ", ".join(["(jdouble)" + a.name + f[1] for f in fields]) } ) if type_dict[a.ctype]["j_type"] in ('bool', 'int', 'long', 'float', 'double'): j_epilogue.append('if(%(n)s!=null) %(n)s[0] = (%(t)s)%(n)s_out[0];' % {'n':a.name,'t':type_dict[a.ctype]["j_type"]}) else: set_vals = [] i = 0 for f in fields: set_vals.append( "%(n)s%(f)s = %(t)s%(n)s_out[%(i)i]" % {"n" : a.name, "t": ("("+type_dict[f[0]]["j_type"]+")", "")[f[0]=="double"], "f" : f[1], "i" : i} ) i += 1 j_epilogue.append( "if("+a.name+"!=null){ " + "; ".join(set_vals) + "; } ") # calculate java method signature to check for uniqueness j_args = [] for a in args: if not a.ctype: #hidden continue jt = type_dict[a.ctype]["j_type"] if a.out and jt in ('bool', 'int', 'long', 'float', 'double'): jt += '[]' j_args.append( jt + ' ' + a.name ) j_signature = type_dict[fi.ctype]["j_type"] + " " + \ fi.jname + "(" + ", ".join(j_args) + ")" logging.info("java: " + j_signature) if j_signature in j_signatures: if args: args.pop() continue else: break # java part: # private java NATIVE method decl # e.g. # private static native void add_0(long src1, long src2, long dst, long mask, int dtype); jn_code.write( Template( " private static native $type $name($args);\n").substitute( type = type_dict[fi.ctype].get("jn_type", "double[]"), name = fi.jname + '_' + str(suffix_counter), args = ", ".join(["%s %s" % (type_dict[a.ctype]["jn_type"], normalize_field_name(a.name)) for a in jn_args]) ) ) # java part: #java doc comment if fi.docstring: lines = fi.docstring.splitlines() returnTag = False javadocParams = [] toWrite = [] inCode = False for index, line in enumerate(lines): p0 = line.find("@param") if p0 != -1: p0 += 7 p1 = line.find(' ', p0) p1 = len(line) if p1 == -1 else p1 name = line[p0:p1] javadocParams.append(name) for arg in j_args: if arg.endswith(" " + name): toWrite.append(line); break else: if "<code>" in line: inCode = True if "</code>" in line: inCode = False if "@return " in line: returnTag = True if (not inCode and toWrite and not toWrite[-1] and line and not line.startswith("\\") and not line.startswith("<ul>") and not line.startswith("@param")): toWrite.append("<p>"); if index == len(lines) - 1: for arg in j_args: name = arg[arg.rfind(' ') + 1:] if not name in javadocParams: toWrite.append(" * @param " + name + " automatically generated"); if type_dict[fi.ctype]["j_type"] and not returnTag and fi.ctype != "void": toWrite.append(" * @return automatically generated"); toWrite.append(line); for line in toWrite: j_code.write(" "*4 + line + "\n") if fi.annotation: j_code.write(" "*4 + "\n".join(fi.annotation) + "\n") # public java wrapper method impl (calling native one above) # e.g. # public static void add( Mat src1, Mat src2, Mat dst, Mat mask, int dtype ) # { add_0( src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj, dtype ); } ret_type = fi.ctype if fi.ctype.endswith('*'): ret_type = ret_type[:-1] ret_val = type_dict[ret_type]["j_type"] + " retVal = " if j_epilogue else "return " tail = "" ret = "return retVal;" if j_epilogue else "" if "v_type" in type_dict[ret_type]: j_type = type_dict[ret_type]["j_type"] if type_dict[ret_type]["v_type"] in ("Mat", "vector_Mat"): tail = ")" if j_type.startswith('MatOf'): ret_val += j_type + ".fromNativeAddr(" else: ret_val = "Mat retValMat = new Mat(" j_prologue.append( j_type + ' retVal = new Array' + j_type+'();') j_epilogue.append('Converters.Mat_to_' + ret_type + '(retValMat, retVal);') ret = "return retVal;" elif ret_type.startswith("Ptr_"): constructor = type_dict[ret_type]["j_type"] + ".__fromPtr__(" if j_epilogue: ret_val = type_dict[fi.ctype]["j_type"] + " retVal = " + constructor else: ret_val = "return " + constructor tail = ")" elif ret_type == "void": ret_val = "" ret = "" elif ret_type == "": # c-tor if fi.classname and ci.base: ret_val = "super(" tail = ")" else: ret_val = "nativeObj = " ret = "" elif self.isWrapped(ret_type): # wrapped class constructor = self.getClass(ret_type).jname + "(" if j_epilogue: ret_val = type_dict[ret_type]["j_type"] + " retVal = new " + constructor else: ret_val = "return new " + constructor tail = ")" elif "jn_type" not in type_dict[ret_type]: constructor = type_dict[ret_type]["j_type"] + "(" if j_epilogue: ret_val = type_dict[fi.ctype]["j_type"] + " retVal = new " + constructor else: ret_val = "return new " + constructor tail = ")" static = "static" if fi.classname: static = fi.static j_code.write( Template( """ public $static$j_type$j_name($j_args) {$prologue $ret_val$jn_name($jn_args_call)$tail;$epilogue$ret } """ ).substitute( ret = "\n " + ret if ret else "", ret_val = ret_val, tail = tail, prologue = "\n " + "\n ".join(j_prologue) if j_prologue else "", epilogue = "\n " + "\n ".join(j_epilogue) if j_epilogue else "", static = static + " " if static else "", j_type=type_dict[fi.ctype]["j_type"] + " " if type_dict[fi.ctype]["j_type"] else "", j_name=fi.jname, j_args=", ".join(j_args), jn_name=fi.jname + '_' + str(suffix_counter), jn_args_call=", ".join( [a.name for a in jn_args] ), ) ) # cpp part: # jni_func(..) { _retval_ = cv_func(..); return _retval_; } ret = "return _retval_;" if c_epilogue else "" default = "return 0;" if fi.ctype == "void": ret = "" default = "" elif not fi.ctype: # c-tor ret = "return (jlong) _retval_;" elif "v_type" in type_dict[fi.ctype]: # c-tor if type_dict[fi.ctype]["v_type"] in ("Mat", "vector_Mat"): ret = "return (jlong) _retval_;" elif fi.ctype in ['String', 'string']: ret = "return env->NewStringUTF(_retval_.c_str());" default = 'return env->NewStringUTF("");' elif self.isWrapped(fi.ctype): # wrapped class: ret = "return (jlong) new %s(_retval_);" % self.fullTypeName(fi.ctype) elif fi.ctype.startswith('Ptr_'): c_prologue.append("typedef Ptr<%s> %s;" % (self.fullTypeName(fi.ctype[4:]), fi.ctype)) ret = "return (jlong)(new %(ctype)s(_retval_));" % { 'ctype':fi.ctype } elif self.isWrapped(ret_type): # pointer to wrapped class: ret = "return (jlong) _retval_;" elif type_dict[fi.ctype]["jni_type"] == "jdoubleArray": ret = "return _da_retval_;" # hack: replacing func call with property set/get name = fi.name if prop_name: if args: name = prop_name + " = " else: name = prop_name + ";//" cvname = fi.fullName(isCPP=True) retval = self.fullTypeName(fi.ctype) + " _retval_ = " if ret else "return " if fi.ctype == "void": retval = "" elif fi.ctype == "String": retval = "cv::" + self.fullTypeName(fi.ctype) + " _retval_ = " elif fi.ctype == "string": retval = "std::string _retval_ = " elif "v_type" in type_dict[fi.ctype]: # vector is returned retval = type_dict[fi.ctype]['jni_var'] % {"n" : '_ret_val_vector_'} + " = " if type_dict[fi.ctype]["v_type"] in ("Mat", "vector_Mat"): c_epilogue.append("Mat* _retval_ = new Mat();") c_epilogue.append(fi.ctype+"_to_Mat(_ret_val_vector_, *_retval_);") else: if ret: c_epilogue.append("jobject _retval_ = " + fi.ctype + "_to_List(env, _ret_val_vector_);") else: c_epilogue.append("return " + fi.ctype + "_to_List(env, _ret_val_vector_);") if fi.classname: if not fi.ctype: # c-tor retval = fi.fullClass(isCPP=True) + "* _retval_ = " cvname = "new " + fi.fullClass(isCPP=True) elif fi.static: cvname = fi.fullName(isCPP=True) else: cvname = ("me->" if not self.isSmartClass(ci) else "(*me)->") + name c_prologue.append( "%(cls)s* me = (%(cls)s*) self; //TODO: check for NULL" % { "cls" : self.smartWrap(ci, fi.fullClass(isCPP=True))} ) cvargs = [] for a in args: if a.pointer: jni_name = "&%(n)s" else: jni_name = "%(n)s" if not a.out and not "jni_var" in type_dict[a.ctype]: # explicit cast to C type to avoid ambiguous call error on platforms (mingw) # where jni types are different from native types (e.g. jint is not the same as int) jni_name = "(%s)%s" % (cast_to(a.ctype), jni_name) if not a.ctype: # hidden jni_name = a.defval cvargs.append( type_dict[a.ctype].get("jni_name", jni_name) % {"n" : a.name}) if "v_type" not in type_dict[a.ctype]: if ("I" in a.out or not a.out or self.isWrapped(a.ctype)) and "jni_var" in type_dict[a.ctype]: # complex type c_prologue.append(type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";") if a.out and "I" not in a.out and not self.isWrapped(a.ctype) and a.ctype: c_prologue.append("%s %s;" % (a.ctype, a.name)) rtype = type_dict[fi.ctype].get("jni_type", "jdoubleArray") clazz = ci.jname cpp_code.write ( Template( """ ${namespace} JNIEXPORT $rtype JNICALL Java_org_opencv_${module}_${clazz}_$fname ($argst); JNIEXPORT $rtype JNICALL Java_org_opencv_${module}_${clazz}_$fname ($args) { static const char method_name[] = "$module::$fname()"; try { LOGD("%s", method_name);$prologue $retval$cvname($cvargs);$epilogue$ret } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); }$default } """ ).substitute( rtype = rtype, module = self.module.replace('_', '_1'), clazz = clazz.replace('_', '_1'), fname = (fi.jname + '_' + str(suffix_counter)).replace('_', '_1'), args = ", ".join(["%s %s" % (type_dict[a.ctype].get("jni_type"), a.name) for a in jni_args]), argst = ", ".join([type_dict[a.ctype].get("jni_type") for a in jni_args]), prologue = "\n " + "\n ".join(c_prologue) if c_prologue else "", epilogue = "\n " + "\n ".join(c_epilogue) if c_epilogue else "", ret = "\n " + ret if ret else "", cvname = cvname, cvargs = " " + ", ".join(cvargs) + " " if cvargs else "", default = "\n " + default if default else "", retval = retval, namespace = ('using namespace ' + ci.namespace.replace('.', '::') + ';') if ci.namespace else '' ) ) # adding method signature to dictionary j_signatures.append(j_signature) # processing args with default values if args and args[-1].defval: args.pop() else: break def gen_class(self, ci): logging.info("%s", ci) # constants consts_map = {c.name: c for c in ci.private_consts} consts_map.update({c.name: c for c in ci.consts}) def const_value(v): if v in consts_map: target = consts_map[v] assert target.value != v return const_value(target.value) return v if ci.private_consts: logging.info("%s", ci.private_consts) ci.j_code.write(""" private static final int %s;\n\n""" % (",\n"+" "*12).join(["%s = %s" % (c.name, const_value(c.value)) for c in ci.private_consts]) ) if ci.consts: enumTypes = set(map(lambda c: c.enumType, ci.consts)) grouped_consts = {enumType: [c for c in ci.consts if c.enumType == enumType] for enumType in enumTypes} for typeName, consts in grouped_consts.items(): logging.info("%s", consts) if typeName: typeName = typeName.rsplit(".", 1)[-1] ###################### Utilize Java enums ###################### # ci.j_code.write(""" # public enum {1} {{ # {0}; # # private final int id; # {1}(int id) {{ this.id = id; }} # {1}({1} _this) {{ this.id = _this.id; }} # public int getValue() {{ return id; }} # }}\n\n""".format((",\n"+" "*8).join(["%s(%s)" % (c.name, c.value) for c in consts]), typeName) # ) ################################################################ ci.j_code.write(""" // C++: enum {1} public static final int {0};\n\n""".format((",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in consts]), typeName) ) else: ci.j_code.write(""" // C++: enum <unnamed> public static final int {0};\n\n""".format((",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in consts])) ) # methods for fi in ci.getAllMethods(): self.gen_func(ci, fi) # props for pi in ci.props: # getter getter_name = ci.fullName() + ".get_" + pi.name fi = FuncInfo( [getter_name, pi.ctype, [], []], self.namespaces ) # [ funcname, return_ctype, [modifiers], [args] ] self.gen_func(ci, fi, pi.name) if pi.rw: #setter setter_name = ci.fullName() + ".set_" + pi.name fi = FuncInfo( [ setter_name, "void", [], [ [pi.ctype, pi.name, "", [], ""] ] ], self.namespaces) self.gen_func(ci, fi, pi.name) # manual ports if ci.name in ManualFuncs: for func in ManualFuncs[ci.name].keys(): ci.j_code.write ( "\n".join(ManualFuncs[ci.name][func]["j_code"]) ) ci.jn_code.write( "\n".join(ManualFuncs[ci.name][func]["jn_code"]) ) ci.cpp_code.write( "\n".join(ManualFuncs[ci.name][func]["cpp_code"]) ) if ci.name != self.Module or ci.base: # finalize() ci.j_code.write( """ @Override protected void finalize() throws Throwable { delete(nativeObj); } """ ) ci.jn_code.write( """ // native support for java finalize() private static native void delete(long nativeObj); """ ) # native support for java finalize() ci.cpp_code.write( """ // // native support for java finalize() // static void %(cls)s::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_%(module)s_%(j_cls)s_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_%(module)s_%(j_cls)s_delete (JNIEnv*, jclass, jlong self) { delete (%(cls)s*) self; } """ % {"module" : module.replace('_', '_1'), "cls" : self.smartWrap(ci, ci.fullName(isCPP=True)), "j_cls" : ci.jname.replace('_', '_1')} ) def getClass(self, classname): return self.classes[classname or self.Module] def isWrapped(self, classname): name = classname or self.Module return name in self.classes def isSmartClass(self, ci): ''' Check if class stores Ptr<T>* instead of T* in nativeObj field ''' if ci.smart != None: return ci.smart # if parents are smart (we hope) then children are! # if not we believe the class is smart if it has "create" method ci.smart = False if ci.base or ci.name == 'Algorithm': ci.smart = True else: for fi in ci.methods: if fi.name == "create": ci.smart = True break return ci.smart def smartWrap(self, ci, fullname): ''' Wraps fullname with Ptr<> if needed ''' if self.isSmartClass(ci): return "Ptr<" + fullname + ">" return fullname def finalize(self, output_jni_path): list_file = os.path.join(output_jni_path, "opencv_jni.hpp") self.save(list_file, '\n'.join(['#include "%s"' % f for f in self.cpp_files])) def copy_java_files(java_files_dir, java_base_path, default_package_path='org/opencv/'): global total_files, updated_files java_files = [] re_filter = re.compile(r'^.+\.(java|aidl)(.in)?$') for root, dirnames, filenames in os.walk(java_files_dir): java_files += [os.path.join(root, filename) for filename in filenames if re_filter.match(filename)] java_files = [f.replace('\\', '/') for f in java_files] re_package = re.compile(r'^package +(.+);') re_prefix = re.compile(r'^.+[\+/]([^\+]+).(java|aidl)(.in)?$') for java_file in java_files: src = checkFileRemap(java_file) with open(src, 'r') as f: package_line = f.readline() m = re_prefix.match(java_file) target_fname = (m.group(1) + '.' + m.group(2)) if m else os.path.basename(java_file) m = re_package.match(package_line) if m: package = m.group(1) package_path = package.replace('.', '/') else: package_path = default_package_path #print(java_file, package_path, target_fname) dest = os.path.join(java_base_path, os.path.join(package_path, target_fname)) assert dest[-3:] != '.in', dest + ' | ' + target_fname mkdir_p(os.path.dirname(dest)) total_files += 1 if (not os.path.exists(dest)) or (os.stat(src).st_mtime - os.stat(dest).st_mtime > 1): copyfile(src, dest) updated_files += 1 def sanitize_java_documentation_string(doc, type): if type == "class": doc = doc.replace("@param ", "") doc = re.sub(re.compile('\\\\f\\$(.*?)\\\\f\\$', re.DOTALL), '\\(' + r'\1' + '\\)', doc) doc = re.sub(re.compile('\\\\f\\[(.*?)\\\\f\\]', re.DOTALL), '\\(' + r'\1' + '\\)', doc) doc = re.sub(re.compile('\\\\f\\{(.*?)\\\\f\\}', re.DOTALL), '\\(' + r'\1' + '\\)', doc) doc = doc.replace("&", "&amp;") \ .replace("\\<", "&lt;") \ .replace("\\>", "&gt;") \ .replace("<", "&lt;") \ .replace(">", "&gt;") \ .replace("$", "$$") \ .replace("@anchor", "") \ .replace("@brief ", "").replace("\\brief ", "") \ .replace("@cite", "CITE:") \ .replace("@code{.cpp}", "<code>") \ .replace("@code{.txt}", "<code>") \ .replace("@code", "<code>") \ .replace("@copydoc", "") \ .replace("@copybrief", "") \ .replace("@date", "") \ .replace("@defgroup", "") \ .replace("@details ", "") \ .replace("@endcode", "</code>") \ .replace("@endinternal", "") \ .replace("@file", "") \ .replace("@include", "INCLUDE:") \ .replace("@ingroup", "") \ .replace("@internal", "") \ .replace("@overload", "") \ .replace("@param[in]", "@param") \ .replace("@param[out]", "@param") \ .replace("@ref", "REF:") \ .replace("@returns", "@return") \ .replace("@sa", "SEE:") \ .replace("@see", "SEE:") \ .replace("@snippet", "SNIPPET:") \ .replace("@todo", "TODO:") \ .replace("@warning ", "WARNING: ") doc = re.sub(re.compile('\\*\\*([^\\*]+?)\\*\\*', re.DOTALL), '<b>' + r'\1' + '</b>', doc) lines = doc.splitlines() lines = list(map(lambda x: x[x.find('*'):].strip() if x.lstrip().startswith("*") else x, lines)) listInd = []; indexDiff = 0; for index, line in enumerate(lines[:]): if line.strip().startswith("-"): i = line.find("-") if not listInd or i > listInd[-1]: lines.insert(index + indexDiff, " "*len(listInd) + "<ul>") indexDiff += 1 listInd.append(i); lines.insert(index + indexDiff, " "*len(listInd) + "<li>") indexDiff += 1 elif i == listInd[-1]: lines.insert(index + indexDiff, " "*len(listInd) + "</li>") indexDiff += 1 lines.insert(index + indexDiff, " "*len(listInd) + "<li>") indexDiff += 1 elif len(listInd) > 1 and i == listInd[-2]: lines.insert(index + indexDiff, " "*len(listInd) + "</li>") indexDiff += 1 del listInd[-1] lines.insert(index + indexDiff, " "*len(listInd) + "</ul>") indexDiff += 1 lines.insert(index + indexDiff, " "*len(listInd) + "<li>") indexDiff += 1 else: lines.insert(index + indexDiff, " "*len(listInd) + "</li>") indexDiff += 1 del listInd[-1] lines.insert(index + indexDiff, " "*len(listInd) + "</ul>") indexDiff += 1 lines.insert(index + indexDiff, " "*len(listInd) + "<ul>") indexDiff += 1 listInd.append(i); lines.insert(index + indexDiff, " "*len(listInd) + "<li>") indexDiff += 1 lines[index + indexDiff] = lines[index + indexDiff][0:i] + lines[index + indexDiff][i + 1:] else: if listInd and (not line or line == "*" or line.startswith("@note")): lines.insert(index + indexDiff, " "*len(listInd) + "</li>") indexDiff += 1 del listInd[-1] lines.insert(index + indexDiff, " "*len(listInd) + "</ul>") indexDiff += 1 i = len(listInd) - 1 for value in enumerate(listInd): lines.append(" "*i + " </li>") lines.append(" "*i + "</ul>") i -= 1; lines = list(map(lambda x: "* " + x[1:].strip() if x.startswith("*") and x != "*" else x, lines)) lines = list(map(lambda x: x if x.startswith("*") else "* " + x if x and x != "*" else "*", lines)) lines = list(map(lambda x: x .replace("@note", "<b>Note:</b>") , lines)) lines = list(map(lambda x: re.sub('@b ([\\w:]+?)\\b', '<b>' + r'\1' + '</b>', x), lines)) lines = list(map(lambda x: re.sub('@c ([\\w:]+?)\\b', '<tt>' + r'\1' + '</tt>', x), lines)) lines = list(map(lambda x: re.sub('`(.*?)`', "{@code " + r'\1' + '}', x), lines)) lines = list(map(lambda x: re.sub('@p ([\\w:]+?)\\b', '{@code ' + r'\1' + '}', x), lines)) hasValues = False for line in lines: if line != "*": hasValues = True break return "/**\n " + "\n ".join(lines) + "\n */" if hasValues else "" if __name__ == "__main__": # initialize logger logging.basicConfig(filename='gen_java.log', format=None, filemode='w', level=logging.INFO) handler = logging.StreamHandler() handler.setLevel(logging.WARNING) logging.getLogger().addHandler(handler) # parse command line parameters import argparse arg_parser = argparse.ArgumentParser(description='OpenCV Java Wrapper Generator') arg_parser.add_argument('-p', '--parser', required=True, help='OpenCV header parser') arg_parser.add_argument('-c', '--config', required=True, help='OpenCV modules config') args=arg_parser.parse_args() # import header parser hdr_parser_path = os.path.abspath(args.parser) if hdr_parser_path.endswith(".py"): hdr_parser_path = os.path.dirname(hdr_parser_path) sys.path.append(hdr_parser_path) import hdr_parser with open(args.config) as f: config = json.load(f) ROOT_DIR = config['rootdir']; assert os.path.exists(ROOT_DIR) FILES_REMAP = { os.path.realpath(os.path.join(ROOT_DIR, f['src'])): f['target'] for f in config['files_remap'] } logging.info("\nRemapped configured files (%d):\n%s", len(FILES_REMAP), pformat(FILES_REMAP)) dstdir = "./gen" jni_path = os.path.join(dstdir, 'cpp'); mkdir_p(jni_path) java_base_path = os.path.join(dstdir, 'java'); mkdir_p(java_base_path) java_test_base_path = os.path.join(dstdir, 'test'); mkdir_p(java_test_base_path) for (subdir, target_subdir) in [('src/java', 'java'), ('android/java', None), ('android-21/java', None)]: if target_subdir is None: target_subdir = subdir java_files_dir = os.path.join(SCRIPT_DIR, subdir) if os.path.exists(java_files_dir): target_path = os.path.join(dstdir, target_subdir); mkdir_p(target_path) copy_java_files(java_files_dir, target_path) # launch Java Wrapper generator generator = JavaWrapperGenerator() gen_dict_files = [] print("JAVA: Processing OpenCV modules: %d" % len(config['modules'])) for e in config['modules']: (module, module_location) = (e['name'], os.path.join(ROOT_DIR, e['location'])) logging.info("\n=== MODULE: %s (%s) ===\n" % (module, module_location)) java_path = os.path.join(java_base_path, 'org/opencv') mkdir_p(java_path) module_imports = [] module_j_code = None module_jn_code = None srcfiles = [] common_headers = [] misc_location = os.path.join(module_location, 'misc/java') srcfiles_fname = os.path.join(misc_location, 'filelist') if os.path.exists(srcfiles_fname): with open(srcfiles_fname) as f: srcfiles = [os.path.join(module_location, str(l).strip()) for l in f.readlines() if str(l).strip()] else: re_bad = re.compile(r'(private|.inl.hpp$|_inl.hpp$|.details.hpp$|_winrt.hpp$|/cuda/|/legacy/)') # .h files before .hpp h_files = [] hpp_files = [] for root, dirnames, filenames in os.walk(os.path.join(module_location, 'include')): h_files += [os.path.join(root, filename) for filename in fnmatch.filter(filenames, '*.h')] hpp_files += [os.path.join(root, filename) for filename in fnmatch.filter(filenames, '*.hpp')] srcfiles = h_files + hpp_files srcfiles = [f for f in srcfiles if not re_bad.search(f.replace('\\', '/'))] logging.info("\nFiles (%d):\n%s", len(srcfiles), pformat(srcfiles)) common_headers_fname = os.path.join(misc_location, 'filelist_common') if os.path.exists(common_headers_fname): with open(common_headers_fname) as f: common_headers = [os.path.join(module_location, str(l).strip()) for l in f.readlines() if str(l).strip()] logging.info("\nCommon headers (%d):\n%s", len(common_headers), pformat(common_headers)) gendict_fname = os.path.join(misc_location, 'gen_dict.json') if os.path.exists(gendict_fname): with open(gendict_fname) as f: gen_type_dict = json.load(f) class_ignore_list += gen_type_dict.get("class_ignore_list", []) const_ignore_list += gen_type_dict.get("const_ignore_list", []) const_private_list += gen_type_dict.get("const_private_list", []) missing_consts.update(gen_type_dict.get("missing_consts", {})) type_dict.update(gen_type_dict.get("type_dict", {})) ManualFuncs.update(gen_type_dict.get("ManualFuncs", {})) func_arg_fix.update(gen_type_dict.get("func_arg_fix", {})) namespaces_dict.update(gen_type_dict.get("namespaces_dict", {})) if 'module_j_code' in gen_type_dict: module_j_code = read_contents(checkFileRemap(os.path.join(misc_location, gen_type_dict['module_j_code']))) if 'module_jn_code' in gen_type_dict: module_jn_code = read_contents(checkFileRemap(os.path.join(misc_location, gen_type_dict['module_jn_code']))) module_imports += gen_type_dict.get("module_imports", []) java_files_dir = os.path.join(misc_location, 'src/java') if os.path.exists(java_files_dir): copy_java_files(java_files_dir, java_base_path, 'org/opencv/' + module) java_test_files_dir = os.path.join(misc_location, 'test') if os.path.exists(java_test_files_dir): copy_java_files(java_test_files_dir, java_test_base_path, 'org/opencv/test/' + module) if len(srcfiles) > 0: generator.gen(srcfiles, module, dstdir, jni_path, java_path, common_headers) else: logging.info("No generated code for module: %s", module) generator.finalize(jni_path) print('Generated files: %d (updated %d)' % (total_files, updated_files))
#!/usr/bin/env python import cv2 as cv from tests_common import NewOpenCVTests class knearest_test(NewOpenCVTests): def test_load(self): k_nearest = cv.ml.KNearest_load(self.find_file("ml/opencv_ml_knn.xml")) self.assertFalse(k_nearest.empty()) self.assertTrue(k_nearest.isTrained()) if __name__ == '__main__': NewOpenCVTests.bootstrap()
#!/usr/bin/env python ''' SVM and KNearest digit recognition. Sample loads a dataset of handwritten digits from '../data/digits.png'. Then it trains a SVM and KNearest classifiers on it and evaluates their accuracy. Following preprocessing is applied to the dataset: - Moment-based image deskew (see deskew()) - Digit images are split into 4 10x10 cells and 16-bin histogram of oriented gradients is computed for each cell - Transform histograms to space with Hellinger metric (see [1] (RootSIFT)) [1] R. Arandjelovic, A. Zisserman "Three things everyone should know to improve object retrieval" http://www.robots.ox.ac.uk/~vgg/publications/2012/Arandjelovic12/arandjelovic12.pdf ''' # Python 2/3 compatibility from __future__ import print_function # built-in modules from multiprocessing.pool import ThreadPool import cv2 as cv import numpy as np from numpy.linalg import norm SZ = 20 # size of each digit is SZ x SZ CLASS_N = 10 DIGITS_FN = 'samples/data/digits.png' def split2d(img, cell_size, flatten=True): h, w = img.shape[:2] sx, sy = cell_size cells = [np.hsplit(row, w//sx) for row in np.vsplit(img, h//sy)] cells = np.array(cells) if flatten: cells = cells.reshape(-1, sy, sx) return cells def deskew(img): m = cv.moments(img) if abs(m['mu02']) < 1e-2: return img.copy() skew = m['mu11']/m['mu02'] M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]]) img = cv.warpAffine(img, M, (SZ, SZ), flags=cv.WARP_INVERSE_MAP | cv.INTER_LINEAR) return img class StatModel(object): def load(self, fn): self.model.load(fn) # Known bug: https://github.com/opencv/opencv/issues/4969 def save(self, fn): self.model.save(fn) class KNearest(StatModel): def __init__(self, k = 3): self.k = k self.model = cv.ml.KNearest_create() def train(self, samples, responses): self.model.train(samples, cv.ml.ROW_SAMPLE, responses) def predict(self, samples): _retval, results, _neigh_resp, _dists = self.model.findNearest(samples, self.k) return results.ravel() class SVM(StatModel): def __init__(self, C = 1, gamma = 0.5): self.model = cv.ml.SVM_create() self.model.setGamma(gamma) self.model.setC(C) self.model.setKernel(cv.ml.SVM_RBF) self.model.setType(cv.ml.SVM_C_SVC) def train(self, samples, responses): self.model.train(samples, cv.ml.ROW_SAMPLE, responses) def predict(self, samples): return self.model.predict(samples)[1].ravel() def evaluate_model(model, digits, samples, labels): resp = model.predict(samples) err = (labels != resp).mean() confusion = np.zeros((10, 10), np.int32) for i, j in zip(labels, resp): confusion[int(i), int(j)] += 1 return err, confusion def preprocess_simple(digits): return np.float32(digits).reshape(-1, SZ*SZ) / 255.0 def preprocess_hog(digits): samples = [] for img in digits: gx = cv.Sobel(img, cv.CV_32F, 1, 0) gy = cv.Sobel(img, cv.CV_32F, 0, 1) mag, ang = cv.cartToPolar(gx, gy) bin_n = 16 bin = np.int32(bin_n*ang/(2*np.pi)) bin_cells = bin[:10,:10], bin[10:,:10], bin[:10,10:], bin[10:,10:] mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:] hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)] hist = np.hstack(hists) # transform to Hellinger kernel eps = 1e-7 hist /= hist.sum() + eps hist = np.sqrt(hist) hist /= norm(hist) + eps samples.append(hist) return np.float32(samples) from tests_common import NewOpenCVTests class digits_test(NewOpenCVTests): def load_digits(self, fn): digits_img = self.get_sample(fn, 0) digits = split2d(digits_img, (SZ, SZ)) labels = np.repeat(np.arange(CLASS_N), len(digits)/CLASS_N) return digits, labels def test_digits(self): digits, labels = self.load_digits(DIGITS_FN) # shuffle digits rand = np.random.RandomState(321) shuffle = rand.permutation(len(digits)) digits, labels = digits[shuffle], labels[shuffle] digits2 = list(map(deskew, digits)) samples = preprocess_hog(digits2) train_n = int(0.9*len(samples)) _digits_train, digits_test = np.split(digits2, [train_n]) samples_train, samples_test = np.split(samples, [train_n]) labels_train, labels_test = np.split(labels, [train_n]) errors = list() confusionMatrixes = list() model = KNearest(k=4) model.train(samples_train, labels_train) error, confusion = evaluate_model(model, digits_test, samples_test, labels_test) errors.append(error) confusionMatrixes.append(confusion) model = SVM(C=2.67, gamma=5.383) model.train(samples_train, labels_train) error, confusion = evaluate_model(model, digits_test, samples_test, labels_test) errors.append(error) confusionMatrixes.append(confusion) eps = 0.001 normEps = len(samples_test) * 0.02 confusionKNN = [[45, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 57, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 59, 1, 0, 0, 0, 0, 1, 0], [ 0, 0, 0, 43, 0, 0, 0, 1, 0, 0], [ 0, 0, 0, 0, 38, 0, 2, 0, 0, 0], [ 0, 0, 0, 2, 0, 48, 0, 0, 1, 0], [ 0, 1, 0, 0, 0, 0, 51, 0, 0, 0], [ 0, 0, 1, 0, 0, 0, 0, 54, 0, 0], [ 0, 0, 0, 0, 0, 1, 0, 0, 46, 0], [ 1, 1, 0, 1, 1, 0, 0, 0, 2, 42]] confusionSVM = [[45, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 57, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 59, 2, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 43, 0, 0, 0, 1, 0, 0], [ 0, 0, 0, 0, 40, 0, 0, 0, 0, 0], [ 0, 0, 0, 1, 0, 50, 0, 0, 0, 0], [ 0, 0, 0, 0, 1, 0, 51, 0, 0, 0], [ 0, 0, 1, 0, 0, 0, 0, 54, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 47, 0], [ 0, 1, 0, 1, 0, 0, 0, 0, 1, 45]] self.assertLess(cv.norm(confusionMatrixes[0] - confusionKNN, cv.NORM_L1), normEps) self.assertLess(cv.norm(confusionMatrixes[1] - confusionSVM, cv.NORM_L1), normEps) self.assertLess(errors[0] - 0.034, eps) self.assertLess(errors[1] - 0.018, eps) if __name__ == '__main__': NewOpenCVTests.bootstrap()
#!/usr/bin/env python # Python 2/3 compatibility from __future__ import print_function import cv2 as cv import numpy as np from tests_common import NewOpenCVTests class TestGoodFeaturesToTrack_test(NewOpenCVTests): def test_goodFeaturesToTrack(self): arr = self.get_sample('samples/data/lena.jpg', 0) original = arr.copy(True) threshes = [ x / 100. for x in range(1,10) ] numPoints = 20000 results = dict([(t, cv.goodFeaturesToTrack(arr, numPoints, t, 2, useHarrisDetector=True)) for t in threshes]) # Check that GoodFeaturesToTrack has not modified input image self.assertTrue(arr.tostring() == original.tostring()) # Check for repeatability for i in range(1): results2 = dict([(t, cv.goodFeaturesToTrack(arr, numPoints, t, 2, useHarrisDetector=True)) for t in threshes]) for t in threshes: self.assertTrue(len(results2[t]) == len(results[t])) for i in range(len(results[t])): self.assertTrue(cv.norm(results[t][i][0] - results2[t][i][0]) == 0) for t0,t1 in zip(threshes, threshes[1:]): r0 = results[t0] r1 = results[t1] # Increasing thresh should make result list shorter self.assertTrue(len(r0) > len(r1)) # Increasing thresh should monly truncate result list for i in range(len(r1)): self.assertTrue(cv.norm(r1[i][0] - r0[i][0])==0) if __name__ == '__main__': NewOpenCVTests.bootstrap()
#!/usr/bin/env python ''' The sample demonstrates how to train Random Trees classifier (or Boosting classifier, or MLP, or Knearest, or Support Vector Machines) using the provided dataset. We use the sample database letter-recognition.data from UCI Repository, here is the link: Newman, D.J. & Hettich, S. & Blake, C.L. & Merz, C.J. (1998). UCI Repository of machine learning databases [http://www.ics.uci.edu/~mlearn/MLRepository.html]. Irvine, CA: University of California, Department of Information and Computer Science. The dataset consists of 20000 feature vectors along with the responses - capital latin letters A..Z. The first 10000 samples are used for training and the remaining 10000 - to test the classifier. ====================================================== Models: RTrees, KNearest, Boost, SVM, MLP ''' # Python 2/3 compatibility from __future__ import print_function import numpy as np import cv2 as cv def load_base(fn): a = np.loadtxt(fn, np.float32, delimiter=',', converters={ 0 : lambda ch : ord(ch)-ord('A') }) samples, responses = a[:,1:], a[:,0] return samples, responses class LetterStatModel(object): class_n = 26 train_ratio = 0.5 def load(self, fn): self.model.load(fn) def save(self, fn): self.model.save(fn) def unroll_samples(self, samples): sample_n, var_n = samples.shape new_samples = np.zeros((sample_n * self.class_n, var_n+1), np.float32) new_samples[:,:-1] = np.repeat(samples, self.class_n, axis=0) new_samples[:,-1] = np.tile(np.arange(self.class_n), sample_n) return new_samples def unroll_responses(self, responses): sample_n = len(responses) new_responses = np.zeros(sample_n*self.class_n, np.int32) resp_idx = np.int32( responses + np.arange(sample_n)*self.class_n ) new_responses[resp_idx] = 1 return new_responses class RTrees(LetterStatModel): def __init__(self): self.model = cv.ml.RTrees_create() def train(self, samples, responses): #sample_n, var_n = samples.shape self.model.setMaxDepth(20) self.model.train(samples, cv.ml.ROW_SAMPLE, responses.astype(int)) def predict(self, samples): _ret, resp = self.model.predict(samples) return resp.ravel() class KNearest(LetterStatModel): def __init__(self): self.model = cv.ml.KNearest_create() def train(self, samples, responses): self.model.train(samples, cv.ml.ROW_SAMPLE, responses) def predict(self, samples): _retval, results, _neigh_resp, _dists = self.model.findNearest(samples, k = 10) return results.ravel() class Boost(LetterStatModel): def __init__(self): self.model = cv.ml.Boost_create() def train(self, samples, responses): _sample_n, var_n = samples.shape new_samples = self.unroll_samples(samples) new_responses = self.unroll_responses(responses) var_types = np.array([cv.ml.VAR_NUMERICAL] * var_n + [cv.ml.VAR_CATEGORICAL, cv.ml.VAR_CATEGORICAL], np.uint8) self.model.setWeakCount(15) self.model.setMaxDepth(10) self.model.train(cv.ml.TrainData_create(new_samples, cv.ml.ROW_SAMPLE, new_responses.astype(int), varType = var_types)) def predict(self, samples): new_samples = self.unroll_samples(samples) _ret, resp = self.model.predict(new_samples) return resp.ravel().reshape(-1, self.class_n).argmax(1) class SVM(LetterStatModel): def __init__(self): self.model = cv.ml.SVM_create() def train(self, samples, responses): self.model.setType(cv.ml.SVM_C_SVC) self.model.setC(1) self.model.setKernel(cv.ml.SVM_RBF) self.model.setGamma(.1) self.model.train(samples, cv.ml.ROW_SAMPLE, responses.astype(int)) def predict(self, samples): _ret, resp = self.model.predict(samples) return resp.ravel() class MLP(LetterStatModel): def __init__(self): self.model = cv.ml.ANN_MLP_create() def train(self, samples, responses): _sample_n, var_n = samples.shape new_responses = self.unroll_responses(responses).reshape(-1, self.class_n) layer_sizes = np.int32([var_n, 100, 100, self.class_n]) self.model.setLayerSizes(layer_sizes) self.model.setTrainMethod(cv.ml.ANN_MLP_BACKPROP) self.model.setBackpropMomentumScale(0) self.model.setBackpropWeightScale(0.001) self.model.setTermCriteria((cv.TERM_CRITERIA_COUNT, 20, 0.01)) self.model.setActivationFunction(cv.ml.ANN_MLP_SIGMOID_SYM, 2, 1) self.model.train(samples, cv.ml.ROW_SAMPLE, np.float32(new_responses)) def predict(self, samples): _ret, resp = self.model.predict(samples) return resp.argmax(-1) from tests_common import NewOpenCVTests class letter_recog_test(NewOpenCVTests): def test_letter_recog(self): eps = 0.01 models = [RTrees, KNearest, Boost, SVM, MLP] models = dict( [(cls.__name__.lower(), cls) for cls in models] ) testErrors = {RTrees: (98.930000, 92.390000), KNearest: (94.960000, 92.010000), Boost: (85.970000, 74.920000), SVM: (99.780000, 95.680000), MLP: (90.060000, 87.410000)} for model in models: Model = models[model] classifier = Model() samples, responses = load_base(self.repoPath + '/samples/data/letter-recognition.data') train_n = int(len(samples)*classifier.train_ratio) classifier.train(samples[:train_n], responses[:train_n]) train_rate = np.mean(classifier.predict(samples[:train_n]) == responses[:train_n].astype(int)) test_rate = np.mean(classifier.predict(samples[train_n:]) == responses[train_n:].astype(int)) self.assertLess(train_rate - testErrors[Model][0], eps) self.assertLess(test_rate - testErrors[Model][1], eps) if __name__ == '__main__': NewOpenCVTests.bootstrap()
# This script is used to estimate an accuracy of different face detection models. # COCO evaluation tool is used to compute an accuracy metrics (Average Precision). # Script works with different face detection datasets. import os import json from fnmatch import fnmatch from math import pi import cv2 as cv import argparse import os import sys from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval parser = argparse.ArgumentParser( description='Evaluate OpenCV face detection algorithms ' 'using COCO evaluation tool, http://cocodataset.org/#detections-eval') parser.add_argument('--proto', help='Path to .prototxt of Caffe model or .pbtxt of TensorFlow graph') parser.add_argument('--model', help='Path to .caffemodel trained in Caffe or .pb from TensorFlow') parser.add_argument('--cascade', help='Optional path to trained Haar cascade as ' 'an additional model for evaluation') parser.add_argument('--ann', help='Path to text file with ground truth annotations') parser.add_argument('--pics', help='Path to images root directory') parser.add_argument('--fddb', help='Evaluate FDDB dataset, http://vis-www.cs.umass.edu/fddb/', action='store_true') parser.add_argument('--wider', help='Evaluate WIDER FACE dataset, http://mmlab.ie.cuhk.edu.hk/projects/WIDERFace/', action='store_true') args = parser.parse_args() dataset = {} dataset['images'] = [] dataset['categories'] = [{ 'id': 0, 'name': 'face' }] dataset['annotations'] = [] def ellipse2Rect(params): rad_x = params[0] rad_y = params[1] angle = params[2] * 180.0 / pi center_x = params[3] center_y = params[4] pts = cv.ellipse2Poly((int(center_x), int(center_y)), (int(rad_x), int(rad_y)), int(angle), 0, 360, 10) rect = cv.boundingRect(pts) left = rect[0] top = rect[1] right = rect[0] + rect[2] bottom = rect[1] + rect[3] return left, top, right, bottom def addImage(imagePath): assert('images' in dataset) imageId = len(dataset['images']) dataset['images'].append({ 'id': int(imageId), 'file_name': imagePath }) return imageId def addBBox(imageId, left, top, width, height): assert('annotations' in dataset) dataset['annotations'].append({ 'id': len(dataset['annotations']), 'image_id': int(imageId), 'category_id': 0, # Face 'bbox': [int(left), int(top), int(width), int(height)], 'iscrowd': 0, 'area': float(width * height) }) def addDetection(detections, imageId, left, top, width, height, score): detections.append({ 'image_id': int(imageId), 'category_id': 0, # Face 'bbox': [int(left), int(top), int(width), int(height)], 'score': float(score) }) def fddb_dataset(annotations, images): for d in os.listdir(annotations): if fnmatch(d, 'FDDB-fold-*-ellipseList.txt'): with open(os.path.join(annotations, d), 'rt') as f: lines = [line.rstrip('\n') for line in f] lineId = 0 while lineId < len(lines): # Image imgPath = lines[lineId] lineId += 1 imageId = addImage(os.path.join(images, imgPath) + '.jpg') img = cv.imread(os.path.join(images, imgPath) + '.jpg') # Faces numFaces = int(lines[lineId]) lineId += 1 for i in range(numFaces): params = [float(v) for v in lines[lineId].split()] lineId += 1 left, top, right, bottom = ellipse2Rect(params) addBBox(imageId, left, top, width=right - left + 1, height=bottom - top + 1) def wider_dataset(annotations, images): with open(annotations, 'rt') as f: lines = [line.rstrip('\n') for line in f] lineId = 0 while lineId < len(lines): # Image imgPath = lines[lineId] lineId += 1 imageId = addImage(os.path.join(images, imgPath)) # Faces numFaces = int(lines[lineId]) lineId += 1 for i in range(numFaces): params = [int(v) for v in lines[lineId].split()] lineId += 1 left, top, width, height = params[0], params[1], params[2], params[3] addBBox(imageId, left, top, width, height) def evaluate(): cocoGt = COCO('annotations.json') cocoDt = cocoGt.loadRes('detections.json') cocoEval = COCOeval(cocoGt, cocoDt, 'bbox') cocoEval.evaluate() cocoEval.accumulate() cocoEval.summarize() ### Convert to COCO annotations format ######################################### assert(args.fddb or args.wider) if args.fddb: fddb_dataset(args.ann, args.pics) elif args.wider: wider_dataset(args.ann, args.pics) with open('annotations.json', 'wt') as f: json.dump(dataset, f) ### Obtain detections ########################################################## detections = [] if args.proto and args.model: net = cv.dnn.readNet(args.proto, args.model) def detect(img, imageId): imgWidth = img.shape[1] imgHeight = img.shape[0] net.setInput(cv.dnn.blobFromImage(img, 1.0, (300, 300), (104., 177., 123.), False, False)) out = net.forward() for i in range(out.shape[2]): confidence = out[0, 0, i, 2] left = int(out[0, 0, i, 3] * img.shape[1]) top = int(out[0, 0, i, 4] * img.shape[0]) right = int(out[0, 0, i, 5] * img.shape[1]) bottom = int(out[0, 0, i, 6] * img.shape[0]) x = max(0, min(left, img.shape[1] - 1)) y = max(0, min(top, img.shape[0] - 1)) w = max(0, min(right - x + 1, img.shape[1] - x)) h = max(0, min(bottom - y + 1, img.shape[0] - y)) addDetection(detections, imageId, x, y, w, h, score=confidence) elif args.cascade: cascade = cv.CascadeClassifier(args.cascade) def detect(img, imageId): srcImgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) faces = cascade.detectMultiScale(srcImgGray) for rect in faces: left, top, width, height = rect[0], rect[1], rect[2], rect[3] addDetection(detections, imageId, left, top, width, height, score=1.0) for i in range(len(dataset['images'])): sys.stdout.write('\r%d / %d' % (i + 1, len(dataset['images']))) sys.stdout.flush() img = cv.imread(dataset['images'][i]['file_name']) imageId = int(dataset['images'][i]['id']) detect(img, imageId) with open('detections.json', 'wt') as f: json.dump(detections, f) evaluate() def rm(f): if os.path.exists(f): os.remove(f) rm('annotations.json') rm('detections.json')
from __future__ import print_function import sys import argparse import cv2 as cv import tensorflow as tf import numpy as np import struct if sys.version_info > (3,): long = int from tensorflow.python.tools import optimize_for_inference_lib from tensorflow.tools.graph_transforms import TransformGraph from tensorflow.core.framework.node_def_pb2 import NodeDef from google.protobuf import text_format parser = argparse.ArgumentParser(description="Use this script to create TensorFlow graph " "with weights from OpenCV's face detection network. " "Only backbone part of SSD model is converted this way. " "Look for .pbtxt configuration file at " "https://github.com/opencv/opencv_extra/tree/master/testdata/dnn/opencv_face_detector.pbtxt") parser.add_argument('--model', help='Path to .caffemodel weights', required=True) parser.add_argument('--proto', help='Path to .prototxt Caffe model definition', required=True) parser.add_argument('--pb', help='Path to output .pb TensorFlow model', required=True) parser.add_argument('--pbtxt', help='Path to output .pbxt TensorFlow graph', required=True) parser.add_argument('--quantize', help='Quantize weights to uint8', action='store_true') parser.add_argument('--fp16', help='Convert weights to half precision floats', action='store_true') args = parser.parse_args() assert(not args.quantize or not args.fp16) dtype = tf.float16 if args.fp16 else tf.float32 ################################################################################ cvNet = cv.dnn.readNetFromCaffe(args.proto, args.model) def dnnLayer(name): return cvNet.getLayer(long(cvNet.getLayerId(name))) def scale(x, name): with tf.variable_scope(name): layer = dnnLayer(name) w = tf.Variable(layer.blobs[0].flatten(), dtype=dtype, name='mul') if len(layer.blobs) > 1: b = tf.Variable(layer.blobs[1].flatten(), dtype=dtype, name='add') return tf.nn.bias_add(tf.multiply(x, w), b) else: return tf.multiply(x, w, name) def conv(x, name, stride=1, pad='SAME', dilation=1, activ=None): with tf.variable_scope(name): layer = dnnLayer(name) w = tf.Variable(layer.blobs[0].transpose(2, 3, 1, 0), dtype=dtype, name='weights') if dilation == 1: conv = tf.nn.conv2d(x, filter=w, strides=(1, stride, stride, 1), padding=pad) else: assert(stride == 1) conv = tf.nn.atrous_conv2d(x, w, rate=dilation, padding=pad) if len(layer.blobs) > 1: b = tf.Variable(layer.blobs[1].flatten(), dtype=dtype, name='bias') conv = tf.nn.bias_add(conv, b) return activ(conv) if activ else conv def batch_norm(x, name): with tf.variable_scope(name): # Unfortunately, TensorFlow's batch normalization layer doesn't work with fp16 input. # Here we do a cast to fp32 but remove it in the frozen graph. if x.dtype != tf.float32: x = tf.cast(x, tf.float32) layer = dnnLayer(name) assert(len(layer.blobs) >= 3) mean = layer.blobs[0].flatten() std = layer.blobs[1].flatten() scale = layer.blobs[2].flatten() eps = 1e-5 hasBias = len(layer.blobs) > 3 hasWeights = scale.shape != (1,) if not hasWeights and not hasBias: mean /= scale[0] std /= scale[0] mean = tf.Variable(mean, dtype=tf.float32, name='mean') std = tf.Variable(std, dtype=tf.float32, name='std') gamma = tf.Variable(scale if hasWeights else np.ones(mean.shape), dtype=tf.float32, name='gamma') beta = tf.Variable(layer.blobs[3].flatten() if hasBias else np.zeros(mean.shape), dtype=tf.float32, name='beta') bn = tf.nn.fused_batch_norm(x, gamma, beta, mean, std, eps, is_training=False)[0] if bn.dtype != dtype: bn = tf.cast(bn, dtype) return bn def l2norm(x, name): with tf.variable_scope(name): layer = dnnLayer(name) w = tf.Variable(layer.blobs[0].flatten(), dtype=dtype, name='mul') return tf.nn.l2_normalize(x, 3, epsilon=1e-10) * w ### Graph definition ########################################################### inp = tf.placeholder(dtype, [1, 300, 300, 3], 'data') data_bn = batch_norm(inp, 'data_bn') data_scale = scale(data_bn, 'data_scale') # Instead of tf.pad we use tf.space_to_batch_nd layers which override convolution's padding strategy to explicit numbers # data_scale = tf.pad(data_scale, [[0, 0], [3, 3], [3, 3], [0, 0]]) data_scale = tf.space_to_batch_nd(data_scale, [1, 1], [[3, 3], [3, 3]], name='Pad') conv1_h = conv(data_scale, stride=2, pad='VALID', name='conv1_h') conv1_bn_h = batch_norm(conv1_h, 'conv1_bn_h') conv1_scale_h = scale(conv1_bn_h, 'conv1_scale_h') conv1_relu = tf.nn.relu(conv1_scale_h) conv1_pool = tf.layers.max_pooling2d(conv1_relu, pool_size=(3, 3), strides=(2, 2), padding='SAME', name='conv1_pool') layer_64_1_conv1_h = conv(conv1_pool, 'layer_64_1_conv1_h') layer_64_1_bn2_h = batch_norm(layer_64_1_conv1_h, 'layer_64_1_bn2_h') layer_64_1_scale2_h = scale(layer_64_1_bn2_h, 'layer_64_1_scale2_h') layer_64_1_relu2 = tf.nn.relu(layer_64_1_scale2_h) layer_64_1_conv2_h = conv(layer_64_1_relu2, 'layer_64_1_conv2_h') layer_64_1_sum = layer_64_1_conv2_h + conv1_pool layer_128_1_bn1_h = batch_norm(layer_64_1_sum, 'layer_128_1_bn1_h') layer_128_1_scale1_h = scale(layer_128_1_bn1_h, 'layer_128_1_scale1_h') layer_128_1_relu1 = tf.nn.relu(layer_128_1_scale1_h) layer_128_1_conv1_h = conv(layer_128_1_relu1, stride=2, name='layer_128_1_conv1_h') layer_128_1_bn2 = batch_norm(layer_128_1_conv1_h, 'layer_128_1_bn2') layer_128_1_scale2 = scale(layer_128_1_bn2, 'layer_128_1_scale2') layer_128_1_relu2 = tf.nn.relu(layer_128_1_scale2) layer_128_1_conv2 = conv(layer_128_1_relu2, 'layer_128_1_conv2') layer_128_1_conv_expand_h = conv(layer_128_1_relu1, stride=2, name='layer_128_1_conv_expand_h') layer_128_1_sum = layer_128_1_conv2 + layer_128_1_conv_expand_h layer_256_1_bn1 = batch_norm(layer_128_1_sum, 'layer_256_1_bn1') layer_256_1_scale1 = scale(layer_256_1_bn1, 'layer_256_1_scale1') layer_256_1_relu1 = tf.nn.relu(layer_256_1_scale1) # layer_256_1_conv1 = tf.pad(layer_256_1_relu1, [[0, 0], [1, 1], [1, 1], [0, 0]]) layer_256_1_conv1 = tf.space_to_batch_nd(layer_256_1_relu1, [1, 1], [[1, 1], [1, 1]], name='Pad_1') layer_256_1_conv1 = conv(layer_256_1_conv1, stride=2, pad='VALID', name='layer_256_1_conv1') layer_256_1_bn2 = batch_norm(layer_256_1_conv1, 'layer_256_1_bn2') layer_256_1_scale2 = scale(layer_256_1_bn2, 'layer_256_1_scale2') layer_256_1_relu2 = tf.nn.relu(layer_256_1_scale2) layer_256_1_conv2 = conv(layer_256_1_relu2, 'layer_256_1_conv2') layer_256_1_conv_expand = conv(layer_256_1_relu1, stride=2, name='layer_256_1_conv_expand') layer_256_1_sum = layer_256_1_conv2 + layer_256_1_conv_expand layer_512_1_bn1 = batch_norm(layer_256_1_sum, 'layer_512_1_bn1') layer_512_1_scale1 = scale(layer_512_1_bn1, 'layer_512_1_scale1') layer_512_1_relu1 = tf.nn.relu(layer_512_1_scale1) layer_512_1_conv1_h = conv(layer_512_1_relu1, 'layer_512_1_conv1_h') layer_512_1_bn2_h = batch_norm(layer_512_1_conv1_h, 'layer_512_1_bn2_h') layer_512_1_scale2_h = scale(layer_512_1_bn2_h, 'layer_512_1_scale2_h') layer_512_1_relu2 = tf.nn.relu(layer_512_1_scale2_h) layer_512_1_conv2_h = conv(layer_512_1_relu2, dilation=2, name='layer_512_1_conv2_h') layer_512_1_conv_expand_h = conv(layer_512_1_relu1, 'layer_512_1_conv_expand_h') layer_512_1_sum = layer_512_1_conv2_h + layer_512_1_conv_expand_h last_bn_h = batch_norm(layer_512_1_sum, 'last_bn_h') last_scale_h = scale(last_bn_h, 'last_scale_h') fc7 = tf.nn.relu(last_scale_h, name='last_relu') conv6_1_h = conv(fc7, 'conv6_1_h', activ=tf.nn.relu) conv6_2_h = conv(conv6_1_h, stride=2, name='conv6_2_h', activ=tf.nn.relu) conv7_1_h = conv(conv6_2_h, 'conv7_1_h', activ=tf.nn.relu) # conv7_2_h = tf.pad(conv7_1_h, [[0, 0], [1, 1], [1, 1], [0, 0]]) conv7_2_h = tf.space_to_batch_nd(conv7_1_h, [1, 1], [[1, 1], [1, 1]], name='Pad_2') conv7_2_h = conv(conv7_2_h, stride=2, pad='VALID', name='conv7_2_h', activ=tf.nn.relu) conv8_1_h = conv(conv7_2_h, pad='SAME', name='conv8_1_h', activ=tf.nn.relu) conv8_2_h = conv(conv8_1_h, pad='VALID', name='conv8_2_h', activ=tf.nn.relu) conv9_1_h = conv(conv8_2_h, 'conv9_1_h', activ=tf.nn.relu) conv9_2_h = conv(conv9_1_h, pad='VALID', name='conv9_2_h', activ=tf.nn.relu) conv4_3_norm = l2norm(layer_256_1_relu1, 'conv4_3_norm') ### Locations and confidences ################################################## locations = [] confidences = [] flattenLayersNames = [] # Collect all reshape layers names that should be replaced to flattens. for top, suffix in zip([locations, confidences], ['_mbox_loc', '_mbox_conf']): for bottom, name in zip([conv4_3_norm, fc7, conv6_2_h, conv7_2_h, conv8_2_h, conv9_2_h], ['conv4_3_norm', 'fc7', 'conv6_2', 'conv7_2', 'conv8_2', 'conv9_2']): name += suffix flat = tf.layers.flatten(conv(bottom, name)) flattenLayersNames.append(flat.name[:flat.name.find(':')]) top.append(flat) mbox_loc = tf.concat(locations, axis=-1, name='mbox_loc') mbox_conf = tf.concat(confidences, axis=-1, name='mbox_conf') total = int(np.prod(mbox_conf.shape[1:])) mbox_conf_reshape = tf.reshape(mbox_conf, [-1, 2], name='mbox_conf_reshape') mbox_conf_softmax = tf.nn.softmax(mbox_conf_reshape, name='mbox_conf_softmax') mbox_conf_flatten = tf.reshape(mbox_conf_softmax, [-1, total], name='mbox_conf_flatten') flattenLayersNames.append('mbox_conf_flatten') with tf.Session() as sess: sess.run(tf.global_variables_initializer()) ### Check correctness ###################################################### out_nodes = ['mbox_loc', 'mbox_conf_flatten'] inp_nodes = [inp.name[:inp.name.find(':')]] np.random.seed(2701) inputData = np.random.standard_normal([1, 3, 300, 300]).astype(np.float32) cvNet.setInput(inputData) cvNet.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV) outDNN = cvNet.forward(out_nodes) outTF = sess.run([mbox_loc, mbox_conf_flatten], feed_dict={inp: inputData.transpose(0, 2, 3, 1)}) print('Max diff @ locations: %e' % np.max(np.abs(outDNN[0] - outTF[0]))) print('Max diff @ confidence: %e' % np.max(np.abs(outDNN[1] - outTF[1]))) # Save a graph graph_def = sess.graph.as_graph_def() # Freeze graph. Replaces variables to constants. graph_def = tf.graph_util.convert_variables_to_constants(sess, graph_def, out_nodes) # Optimize graph. Removes training-only ops, unused nodes. graph_def = optimize_for_inference_lib.optimize_for_inference(graph_def, inp_nodes, out_nodes, dtype.as_datatype_enum) # Fuse constant operations. transforms = ["fold_constants(ignore_errors=True)"] if args.quantize: transforms += ["quantize_weights(minimum_size=0)"] transforms += ["sort_by_execution_order"] graph_def = TransformGraph(graph_def, inp_nodes, out_nodes, transforms) # By default, float16 weights are stored in repeated tensor's field called # `half_val`. It has type int32 with leading zeros for unused bytes. # This type is encoded by Variant that means only 7 bits are used for value # representation but the last one is indicated the end of encoding. This way # float16 might takes 1 or 2 or 3 bytes depends on value. To improve compression, # we replace all `half_val` values to `tensor_content` using only 2 bytes for everyone. for node in graph_def.node: if 'value' in node.attr: halfs = node.attr["value"].tensor.half_val if not node.attr["value"].tensor.tensor_content and halfs: node.attr["value"].tensor.tensor_content = struct.pack('H' * len(halfs), *halfs) node.attr["value"].tensor.ClearField('half_val') # Serialize with tf.gfile.FastGFile(args.pb, 'wb') as f: f.write(graph_def.SerializeToString()) ################################################################################ # Write a text graph representation ################################################################################ def tensorMsg(values): msg = 'tensor { dtype: DT_FLOAT tensor_shape { dim { size: %d } }' % len(values) for value in values: msg += 'float_val: %f ' % value return msg + '}' # Remove Const nodes and unused attributes. for i in reversed(range(len(graph_def.node))): if graph_def.node[i].op in ['Const', 'Dequantize']: del graph_def.node[i] for attr in ['T', 'data_format', 'Tshape', 'N', 'Tidx', 'Tdim', 'use_cudnn_on_gpu', 'Index', 'Tperm', 'is_training', 'Tpaddings', 'Tblock_shape', 'Tcrops']: if attr in graph_def.node[i].attr: del graph_def.node[i].attr[attr] # Append prior box generators min_sizes = [30, 60, 111, 162, 213, 264] max_sizes = [60, 111, 162, 213, 264, 315] steps = [8, 16, 32, 64, 100, 300] aspect_ratios = [[2], [2, 3], [2, 3], [2, 3], [2], [2]] layers = [conv4_3_norm, fc7, conv6_2_h, conv7_2_h, conv8_2_h, conv9_2_h] for i in range(6): priorBox = NodeDef() priorBox.name = 'PriorBox_%d' % i priorBox.op = 'PriorBox' priorBox.input.append(layers[i].name[:layers[i].name.find(':')]) priorBox.input.append(inp_nodes[0]) # data text_format.Merge('i: %d' % min_sizes[i], priorBox.attr["min_size"]) text_format.Merge('i: %d' % max_sizes[i], priorBox.attr["max_size"]) text_format.Merge('b: true', priorBox.attr["flip"]) text_format.Merge('b: false', priorBox.attr["clip"]) text_format.Merge(tensorMsg(aspect_ratios[i]), priorBox.attr["aspect_ratio"]) text_format.Merge(tensorMsg([0.1, 0.1, 0.2, 0.2]), priorBox.attr["variance"]) text_format.Merge('f: %f' % steps[i], priorBox.attr["step"]) text_format.Merge('f: 0.5', priorBox.attr["offset"]) graph_def.node.extend([priorBox]) # Concatenate prior boxes concat = NodeDef() concat.name = 'mbox_priorbox' concat.op = 'ConcatV2' for i in range(6): concat.input.append('PriorBox_%d' % i) concat.input.append('mbox_loc/axis') graph_def.node.extend([concat]) # DetectionOutput layer detectionOut = NodeDef() detectionOut.name = 'detection_out' detectionOut.op = 'DetectionOutput' detectionOut.input.append('mbox_loc') detectionOut.input.append('mbox_conf_flatten') detectionOut.input.append('mbox_priorbox') text_format.Merge('i: 2', detectionOut.attr['num_classes']) text_format.Merge('b: true', detectionOut.attr['share_location']) text_format.Merge('i: 0', detectionOut.attr['background_label_id']) text_format.Merge('f: 0.45', detectionOut.attr['nms_threshold']) text_format.Merge('i: 400', detectionOut.attr['top_k']) text_format.Merge('s: "CENTER_SIZE"', detectionOut.attr['code_type']) text_format.Merge('i: 200', detectionOut.attr['keep_top_k']) text_format.Merge('f: 0.01', detectionOut.attr['confidence_threshold']) graph_def.node.extend([detectionOut]) # Replace L2Normalization subgraph onto a single node. for i in reversed(range(len(graph_def.node))): if graph_def.node[i].name in ['conv4_3_norm/l2_normalize/Square', 'conv4_3_norm/l2_normalize/Sum', 'conv4_3_norm/l2_normalize/Maximum', 'conv4_3_norm/l2_normalize/Rsqrt']: del graph_def.node[i] for node in graph_def.node: if node.name == 'conv4_3_norm/l2_normalize': node.op = 'L2Normalize' node.input.pop() node.input.pop() node.input.append(layer_256_1_relu1.name) node.input.append('conv4_3_norm/l2_normalize/Sum/reduction_indices') break softmaxShape = NodeDef() softmaxShape.name = 'reshape_before_softmax' softmaxShape.op = 'Const' text_format.Merge( 'tensor {' ' dtype: DT_INT32' ' tensor_shape { dim { size: 3 } }' ' int_val: 0' ' int_val: -1' ' int_val: 2' '}', softmaxShape.attr["value"]) graph_def.node.extend([softmaxShape]) for node in graph_def.node: if node.name == 'mbox_conf_reshape': node.input[1] = softmaxShape.name elif node.name == 'mbox_conf_softmax': text_format.Merge('i: 2', node.attr['axis']) elif node.name in flattenLayersNames: node.op = 'Flatten' inpName = node.input[0] node.input.pop() node.input.pop() node.input.append(inpName) tf.train.write_graph(graph_def, "", args.pbtxt, as_text=True)
#!/usr/bin/env python import os import cv2 as cv import numpy as np from tests_common import NewOpenCVTests, unittest def normAssert(test, a, b, msg=None, lInf=1e-5): test.assertLess(np.max(np.abs(a - b)), lInf, msg) def inter_area(box1, box2): x_min, x_max = max(box1[0], box2[0]), min(box1[2], box2[2]) y_min, y_max = max(box1[1], box2[1]), min(box1[3], box2[3]) return (x_max - x_min) * (y_max - y_min) def area(box): return (box[2] - box[0]) * (box[3] - box[1]) def box2str(box): left, top = box[0], box[1] width, height = box[2] - left, box[3] - top return '[%f x %f from (%f, %f)]' % (width, height, left, top) def normAssertDetections(test, refClassIds, refScores, refBoxes, testClassIds, testScores, testBoxes, confThreshold=0.0, scores_diff=1e-5, boxes_iou_diff=1e-4): matchedRefBoxes = [False] * len(refBoxes) errMsg = '' for i in range(len(testBoxes)): testScore = testScores[i] if testScore < confThreshold: continue testClassId, testBox = testClassIds[i], testBoxes[i] matched = False for j in range(len(refBoxes)): if (not matchedRefBoxes[j]) and testClassId == refClassIds[j] and \ abs(testScore - refScores[j]) < scores_diff: interArea = inter_area(testBox, refBoxes[j]) iou = interArea / (area(testBox) + area(refBoxes[j]) - interArea) if abs(iou - 1.0) < boxes_iou_diff: matched = True matchedRefBoxes[j] = True if not matched: errMsg += '\nUnmatched prediction: class %d score %f box %s' % (testClassId, testScore, box2str(testBox)) for i in range(len(refBoxes)): if (not matchedRefBoxes[i]) and refScores[i] > confThreshold: errMsg += '\nUnmatched reference: class %d score %f box %s' % (refClassIds[i], refScores[i], box2str(refBoxes[i])) if errMsg: test.fail(errMsg) def printParams(backend, target): backendNames = { cv.dnn.DNN_BACKEND_OPENCV: 'OCV', cv.dnn.DNN_BACKEND_INFERENCE_ENGINE: 'DLIE' } targetNames = { cv.dnn.DNN_TARGET_CPU: 'CPU', cv.dnn.DNN_TARGET_OPENCL: 'OCL', cv.dnn.DNN_TARGET_OPENCL_FP16: 'OCL_FP16', cv.dnn.DNN_TARGET_MYRIAD: 'MYRIAD' } print('%s/%s' % (backendNames[backend], targetNames[target])) testdata_required = bool(os.environ.get('OPENCV_DNN_TEST_REQUIRE_TESTDATA', False)) g_dnnBackendsAndTargets = None class dnn_test(NewOpenCVTests): def setUp(self): super(dnn_test, self).setUp() global g_dnnBackendsAndTargets if g_dnnBackendsAndTargets is None: g_dnnBackendsAndTargets = self.initBackendsAndTargets() self.dnnBackendsAndTargets = g_dnnBackendsAndTargets def initBackendsAndTargets(self): self.dnnBackendsAndTargets = [ [cv.dnn.DNN_BACKEND_OPENCV, cv.dnn.DNN_TARGET_CPU], ] if self.checkIETarget(cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_TARGET_CPU): self.dnnBackendsAndTargets.append([cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_TARGET_CPU]) if self.checkIETarget(cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_TARGET_MYRIAD): self.dnnBackendsAndTargets.append([cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_TARGET_MYRIAD]) if cv.ocl.haveOpenCL() and cv.ocl.useOpenCL(): self.dnnBackendsAndTargets.append([cv.dnn.DNN_BACKEND_OPENCV, cv.dnn.DNN_TARGET_OPENCL]) self.dnnBackendsAndTargets.append([cv.dnn.DNN_BACKEND_OPENCV, cv.dnn.DNN_TARGET_OPENCL_FP16]) if cv.ocl_Device.getDefault().isIntel(): if self.checkIETarget(cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_TARGET_OPENCL): self.dnnBackendsAndTargets.append([cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_TARGET_OPENCL]) if self.checkIETarget(cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_TARGET_OPENCL_FP16): self.dnnBackendsAndTargets.append([cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_TARGET_OPENCL_FP16]) return self.dnnBackendsAndTargets def find_dnn_file(self, filename, required=True): if not required: required = testdata_required return self.find_file(filename, [os.environ.get('OPENCV_DNN_TEST_DATA_PATH', os.getcwd()), os.environ['OPENCV_TEST_DATA_PATH']], required=required) def checkIETarget(self, backend, target): proto = self.find_dnn_file('dnn/layers/layer_convolution.prototxt') model = self.find_dnn_file('dnn/layers/layer_convolution.caffemodel') net = cv.dnn.readNet(proto, model) net.setPreferableBackend(backend) net.setPreferableTarget(target) inp = np.random.standard_normal([1, 2, 10, 11]).astype(np.float32) try: net.setInput(inp) net.forward() except BaseException as e: return False return True def test_getAvailableTargets(self): targets = cv.dnn.getAvailableTargets(cv.dnn.DNN_BACKEND_OPENCV) self.assertTrue(cv.dnn.DNN_TARGET_CPU in targets) def test_blobFromImage(self): np.random.seed(324) width = 6 height = 7 scale = 1.0/127.5 mean = (10, 20, 30) # Test arguments names. img = np.random.randint(0, 255, [4, 5, 3]).astype(np.uint8) blob = cv.dnn.blobFromImage(img, scale, (width, height), mean, True, False) blob_args = cv.dnn.blobFromImage(img, scalefactor=scale, size=(width, height), mean=mean, swapRB=True, crop=False) normAssert(self, blob, blob_args) # Test values. target = cv.resize(img, (width, height), interpolation=cv.INTER_LINEAR) target = target.astype(np.float32) target = target[:,:,[2, 1, 0]] # BGR2RGB target[:,:,0] -= mean[0] target[:,:,1] -= mean[1] target[:,:,2] -= mean[2] target *= scale target = target.transpose(2, 0, 1).reshape(1, 3, height, width) # to NCHW normAssert(self, blob, target) def test_model(self): img_path = self.find_dnn_file("dnn/street.png") weights = self.find_dnn_file("dnn/MobileNetSSD_deploy.caffemodel", required=False) config = self.find_dnn_file("dnn/MobileNetSSD_deploy.prototxt", required=False) if weights is None or config is None: raise unittest.SkipTest("Missing DNN test files (dnn/MobileNetSSD_deploy.{prototxt/caffemodel}). Verify OPENCV_DNN_TEST_DATA_PATH configuration parameter.") frame = cv.imread(img_path) model = cv.dnn_DetectionModel(weights, config) model.setInputParams(size=(300, 300), mean=(127.5, 127.5, 127.5), scale=1.0/127.5) iouDiff = 0.05 confThreshold = 0.0001 nmsThreshold = 0 scoreDiff = 1e-3 classIds, confidences, boxes = model.detect(frame, confThreshold, nmsThreshold) refClassIds = (7, 15) refConfidences = (0.9998, 0.8793) refBoxes = ((328, 238, 85, 102), (101, 188, 34, 138)) normAssertDetections(self, refClassIds, refConfidences, refBoxes, classIds, confidences, boxes,confThreshold, scoreDiff, iouDiff) for box in boxes: cv.rectangle(frame, box, (0, 255, 0)) cv.rectangle(frame, np.array(box), (0, 255, 0)) cv.rectangle(frame, tuple(box), (0, 255, 0)) cv.rectangle(frame, list(box), (0, 255, 0)) def test_classification_model(self): img_path = self.find_dnn_file("dnn/googlenet_0.png") weights = self.find_dnn_file("dnn/squeezenet_v1.1.caffemodel", required=False) config = self.find_dnn_file("dnn/squeezenet_v1.1.prototxt") ref = np.load(self.find_dnn_file("dnn/squeezenet_v1.1_prob.npy")) if weights is None or config is None: raise unittest.SkipTest("Missing DNN test files (dnn/squeezenet_v1.1.{prototxt/caffemodel}). Verify OPENCV_DNN_TEST_DATA_PATH configuration parameter.") frame = cv.imread(img_path) model = cv.dnn_ClassificationModel(config, weights) model.setInputSize(227, 227) model.setInputCrop(True) out = model.predict(frame) normAssert(self, out, ref) def test_face_detection(self): proto = self.find_dnn_file('dnn/opencv_face_detector.prototxt') model = self.find_dnn_file('dnn/opencv_face_detector.caffemodel', required=False) if proto is None or model is None: raise unittest.SkipTest("Missing DNN test files (dnn/opencv_face_detector.{prototxt/caffemodel}). Verify OPENCV_DNN_TEST_DATA_PATH configuration parameter.") img = self.get_sample('gpu/lbpcascade/er.png') blob = cv.dnn.blobFromImage(img, mean=(104, 177, 123), swapRB=False, crop=False) ref = [[0, 1, 0.99520785, 0.80997437, 0.16379407, 0.87996572, 0.26685631], [0, 1, 0.9934696, 0.2831718, 0.50738752, 0.345781, 0.5985168], [0, 1, 0.99096733, 0.13629119, 0.24892329, 0.19756334, 0.3310290], [0, 1, 0.98977017, 0.23901358, 0.09084064, 0.29902688, 0.1769477], [0, 1, 0.97203469, 0.67965847, 0.06876482, 0.73999709, 0.1513494], [0, 1, 0.95097077, 0.51901293, 0.45863652, 0.5777427, 0.5347801]] print('\n') for backend, target in self.dnnBackendsAndTargets: printParams(backend, target) net = cv.dnn.readNet(proto, model) net.setPreferableBackend(backend) net.setPreferableTarget(target) net.setInput(blob) out = net.forward().reshape(-1, 7) scoresDiff = 4e-3 if target in [cv.dnn.DNN_TARGET_OPENCL_FP16, cv.dnn.DNN_TARGET_MYRIAD] else 1e-5 iouDiff = 2e-2 if target in [cv.dnn.DNN_TARGET_OPENCL_FP16, cv.dnn.DNN_TARGET_MYRIAD] else 1e-4 ref = np.array(ref, np.float32) refClassIds, testClassIds = ref[:, 1], out[:, 1] refScores, testScores = ref[:, 2], out[:, 2] refBoxes, testBoxes = ref[:, 3:], out[:, 3:] normAssertDetections(self, refClassIds, refScores, refBoxes, testClassIds, testScores, testBoxes, 0.5, scoresDiff, iouDiff) def test_async(self): timeout = 10*1000*10**6 # in nanoseconds (10 sec) proto = self.find_dnn_file('dnn/layers/layer_convolution.prototxt') model = self.find_dnn_file('dnn/layers/layer_convolution.caffemodel') if proto is None or model is None: raise unittest.SkipTest("Missing DNN test files (dnn/layers/layer_convolution.{prototxt/caffemodel}). Verify OPENCV_DNN_TEST_DATA_PATH configuration parameter.") print('\n') for backend, target in self.dnnBackendsAndTargets: if backend != cv.dnn.DNN_BACKEND_INFERENCE_ENGINE: continue printParams(backend, target) netSync = cv.dnn.readNet(proto, model) netSync.setPreferableBackend(backend) netSync.setPreferableTarget(target) netAsync = cv.dnn.readNet(proto, model) netAsync.setPreferableBackend(backend) netAsync.setPreferableTarget(target) # Generate inputs numInputs = 10 inputs = [] for _ in range(numInputs): inputs.append(np.random.standard_normal([2, 6, 75, 113]).astype(np.float32)) # Run synchronously refs = [] for i in range(numInputs): netSync.setInput(inputs[i]) refs.append(netSync.forward()) # Run asynchronously. To make test more robust, process inputs in the reversed order. outs = [] for i in reversed(range(numInputs)): netAsync.setInput(inputs[i]) outs.insert(0, netAsync.forwardAsync()) for i in reversed(range(numInputs)): ret, result = outs[i].get(timeoutNs=float(timeout)) self.assertTrue(ret) normAssert(self, refs[i], result, 'Index: %d' % i, 1e-10) def test_custom_layer(self): class CropLayer(object): def __init__(self, params, blobs): self.xstart = 0 self.xend = 0 self.ystart = 0 self.yend = 0 # Our layer receives two inputs. We need to crop the first input blob # to match a shape of the second one (keeping batch size and number of channels) def getMemoryShapes(self, inputs): inputShape, targetShape = inputs[0], inputs[1] batchSize, numChannels = inputShape[0], inputShape[1] height, width = targetShape[2], targetShape[3] self.ystart = (inputShape[2] - targetShape[2]) // 2 self.xstart = (inputShape[3] - targetShape[3]) // 2 self.yend = self.ystart + height self.xend = self.xstart + width return [[batchSize, numChannels, height, width]] def forward(self, inputs): return [inputs[0][:,:,self.ystart:self.yend,self.xstart:self.xend]] cv.dnn_registerLayer('CropCaffe', CropLayer) proto = ''' name: "TestCrop" input: "input" input_shape { dim: 1 dim: 2 dim: 5 dim: 5 } input: "roi" input_shape { dim: 1 dim: 2 dim: 3 dim: 3 } layer { name: "Crop" type: "CropCaffe" bottom: "input" bottom: "roi" top: "Crop" }''' net = cv.dnn.readNetFromCaffe(bytearray(proto.encode())) for backend, target in self.dnnBackendsAndTargets: if backend != cv.dnn.DNN_BACKEND_OPENCV: continue printParams(backend, target) net.setPreferableBackend(backend) net.setPreferableTarget(target) src_shape = [1, 2, 5, 5] dst_shape = [1, 2, 3, 3] inp = np.arange(0, np.prod(src_shape), dtype=np.float32).reshape(src_shape) roi = np.empty(dst_shape, dtype=np.float32) net.setInput(inp, "input") net.setInput(roi, "roi") out = net.forward() ref = inp[:, :, 1:4, 1:4] normAssert(self, out, ref) cv.dnn_unregisterLayer('CropCaffe') if __name__ == '__main__': NewOpenCVTests.bootstrap()
import numpy as np import sys import os import argparse import tensorflow as tf from tensorflow.python.platform import gfile from imagenet_cls_test_alexnet import MeanValueFetch, DnnCaffeModel, Framework, ClsAccEvaluation try: import cv2 as cv except ImportError: raise ImportError('Can\'t find OpenCV Python module. If you\'ve built it from sources without installation, ' 'configure environment variable PYTHONPATH to "opencv_build_dir/lib" directory (with "python3" subdirectory if required)') # If you've got an exception "Cannot load libmkl_avx.so or libmkl_def.so" or similar, try to export next variable # before running the script: # LD_PRELOAD=/opt/intel/mkl/lib/intel64/libmkl_core.so:/opt/intel/mkl/lib/intel64/libmkl_sequential.so class TensorflowModel(Framework): sess = tf.Session output = tf.Graph def __init__(self, model_file, in_blob_name, out_blob_name): self.in_blob_name = in_blob_name self.sess = tf.Session() with gfile.FastGFile(model_file, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) self.sess.graph.as_default() tf.import_graph_def(graph_def, name='') self.output = self.sess.graph.get_tensor_by_name(out_blob_name + ":0") def get_name(self): return 'Tensorflow' def get_output(self, input_blob): assert len(input_blob.shape) == 4 batch_tf = input_blob.transpose(0, 2, 3, 1) out = self.sess.run(self.output, {self.in_blob_name+':0': batch_tf}) out = out[..., 1:1001] return out class DnnTfInceptionModel(DnnCaffeModel): net = cv.dnn.Net() def __init__(self, model_file, in_blob_name, out_blob_name): self.net = cv.dnn.readNetFromTensorflow(model_file) self.in_blob_name = in_blob_name self.out_blob_name = out_blob_name def get_output(self, input_blob): return super(DnnTfInceptionModel, self).get_output(input_blob)[..., 1:1001] if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--imgs_dir", help="path to ImageNet validation subset images dir, ILSVRC2012_img_val dir") parser.add_argument("--img_cls_file", help="path to file with classes ids for images, download it here:" "https://github.com/opencv/opencv_extra/tree/master/testdata/dnn/img_classes_inception.txt") parser.add_argument("--model", help="path to tensorflow model, download it here:" "https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip") parser.add_argument("--log", help="path to logging file") parser.add_argument("--batch_size", help="size of images in batch", default=1) parser.add_argument("--frame_size", help="size of input image", default=224) parser.add_argument("--in_blob", help="name for input blob", default='input') parser.add_argument("--out_blob", help="name for output blob", default='softmax2') args = parser.parse_args() data_fetcher = MeanValueFetch(args.frame_size, args.imgs_dir, True) frameworks = [TensorflowModel(args.model, args.in_blob, args.out_blob), DnnTfInceptionModel(args.model, '', args.out_blob)] acc_eval = ClsAccEvaluation(args.log, args.img_cls_file, args.batch_size) acc_eval.process(frameworks, data_fetcher)
import numpy as np import sys import os import fnmatch import argparse try: import cv2 as cv except ImportError: raise ImportError('Can\'t find OpenCV Python module. If you\'ve built it from sources without installation, ' 'configure environment variable PYTHONPATH to "opencv_build_dir/lib" directory (with "python3" subdirectory if required)') try: import torch except ImportError: raise ImportError('Can\'t find pytorch. Please install it by following instructions on the official site') from torch.utils.serialization import load_lua from pascal_semsegm_test_fcn import eval_segm_result, get_conf_mat, get_metrics, DatasetImageFetch, SemSegmEvaluation from imagenet_cls_test_alexnet import Framework, DnnCaffeModel class NormalizePreproc: def __init__(self): pass @staticmethod def process(img): image_data = np.array(img).transpose(2, 0, 1).astype(np.float32) image_data = np.expand_dims(image_data, 0) image_data /= 255.0 return image_data class CityscapesDataFetch(DatasetImageFetch): img_dir = '' segm_dir = '' segm_files = [] colors = [] i = 0 def __init__(self, img_dir, segm_dir, preproc): self.img_dir = img_dir self.segm_dir = segm_dir self.segm_files = sorted([img for img in self.locate('*_color.png', segm_dir)]) self.colors = self.get_colors() self.data_prepoc = preproc self.i = 0 @staticmethod def get_colors(): result = [] colors_list = ( (0, 0, 0), (128, 64, 128), (244, 35, 232), (70, 70, 70), (102, 102, 156), (190, 153, 153), (153, 153, 153), (250, 170, 30), (220, 220, 0), (107, 142, 35), (152, 251, 152), (70, 130, 180), (220, 20, 60), (255, 0, 0), (0, 0, 142), (0, 0, 70), (0, 60, 100), (0, 80, 100), (0, 0, 230), (119, 11, 32)) for c in colors_list: result.append(DatasetImageFetch.pix_to_c(c)) return result def __iter__(self): return self def next(self): if self.i < len(self.segm_files): segm_file = self.segm_files[self.i] segm = cv.imread(segm_file, cv.IMREAD_COLOR)[:, :, ::-1] segm = cv.resize(segm, (1024, 512), interpolation=cv.INTER_NEAREST) img_file = self.rreplace(self.img_dir + segm_file[len(self.segm_dir):], 'gtFine_color', 'leftImg8bit') assert os.path.exists(img_file) img = cv.imread(img_file, cv.IMREAD_COLOR)[:, :, ::-1] img = cv.resize(img, (1024, 512)) self.i += 1 gt = self.color_to_gt(segm, self.colors) img = self.data_prepoc.process(img) return img, gt else: self.i = 0 raise StopIteration def get_num_classes(self): return len(self.colors) @staticmethod def locate(pattern, root_path): for path, dirs, files in os.walk(os.path.abspath(root_path)): for filename in fnmatch.filter(files, pattern): yield os.path.join(path, filename) @staticmethod def rreplace(s, old, new, occurrence=1): li = s.rsplit(old, occurrence) return new.join(li) class TorchModel(Framework): net = object def __init__(self, model_file): self.net = load_lua(model_file) def get_name(self): return 'Torch' def get_output(self, input_blob): tensor = torch.FloatTensor(input_blob) out = self.net.forward(tensor).numpy() return out class DnnTorchModel(DnnCaffeModel): net = cv.dnn.Net() def __init__(self, model_file): self.net = cv.dnn.readNetFromTorch(model_file) def get_output(self, input_blob): self.net.setBlob("", input_blob) self.net.forward() return self.net.getBlob(self.net.getLayerNames()[-1]) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--imgs_dir", help="path to Cityscapes validation images dir, imgsfine/leftImg8bit/val") parser.add_argument("--segm_dir", help="path to Cityscapes dir with segmentation, gtfine/gtFine/val") parser.add_argument("--model", help="path to torch model, download it here: " "https://www.dropbox.com/sh/dywzk3gyb12hpe5/AAD5YkUa8XgMpHs2gCRgmCVCa") parser.add_argument("--log", help="path to logging file") args = parser.parse_args() prep = NormalizePreproc() df = CityscapesDataFetch(args.imgs_dir, args.segm_dir, prep) fw = [TorchModel(args.model), DnnTorchModel(args.model)] segm_eval = SemSegmEvaluation(args.log) segm_eval.process(fw, df)
import numpy as np import sys import os import argparse from imagenet_cls_test_alexnet import MeanChannelsFetch, CaffeModel, DnnCaffeModel, ClsAccEvaluation try: import caffe except ImportError: raise ImportError('Can\'t find Caffe Python module. If you\'ve built it from sources without installation, ' 'configure environment variable PYTHONPATH to "git/caffe/python" directory') try: import cv2 as cv except ImportError: raise ImportError('Can\'t find OpenCV Python module. If you\'ve built it from sources without installation, ' 'configure environment variable PYTHONPATH to "opencv_build_dir/lib" directory (with "python3" subdirectory if required)') if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--imgs_dir", help="path to ImageNet validation subset images dir, ILSVRC2012_img_val dir") parser.add_argument("--img_cls_file", help="path to file with classes ids for images, val.txt file from this " "archive: http://dl.caffe.berkeleyvision.org/caffe_ilsvrc12.tar.gz") parser.add_argument("--prototxt", help="path to caffe prototxt, download it here: " "https://github.com/BVLC/caffe/blob/master/models/bvlc_alexnet/deploy.prototxt") parser.add_argument("--caffemodel", help="path to caffemodel file, download it here: " "http://dl.caffe.berkeleyvision.org/bvlc_alexnet.caffemodel") parser.add_argument("--log", help="path to logging file") parser.add_argument("--batch_size", help="size of images in batch", default=500, type=int) parser.add_argument("--frame_size", help="size of input image", default=224, type=int) parser.add_argument("--in_blob", help="name for input blob", default='data') parser.add_argument("--out_blob", help="name for output blob", default='prob') args = parser.parse_args() data_fetcher = MeanChannelsFetch(args.frame_size, args.imgs_dir) frameworks = [CaffeModel(args.prototxt, args.caffemodel, args.in_blob, args.out_blob), DnnCaffeModel(args.prototxt, args.caffemodel, '', args.out_blob)] acc_eval = ClsAccEvaluation(args.log, args.img_cls_file, args.batch_size) acc_eval.process(frameworks, data_fetcher)
from __future__ import print_function from abc import ABCMeta, abstractmethod import numpy as np import sys import os import argparse import time try: import caffe except ImportError: raise ImportError('Can\'t find Caffe Python module. If you\'ve built it from sources without installation, ' 'configure environment variable PYTHONPATH to "git/caffe/python" directory') try: import cv2 as cv except ImportError: raise ImportError('Can\'t find OpenCV Python module. If you\'ve built it from sources without installation, ' 'configure environment variable PYTHONPATH to "opencv_build_dir/lib" directory (with "python3" subdirectory if required)') try: xrange # Python 2 except NameError: xrange = range # Python 3 class DataFetch(object): imgs_dir = '' frame_size = 0 bgr_to_rgb = False __metaclass__ = ABCMeta @abstractmethod def preprocess(self, img): pass def get_batch(self, imgs_names): assert type(imgs_names) is list batch = np.zeros((len(imgs_names), 3, self.frame_size, self.frame_size)).astype(np.float32) for i in range(len(imgs_names)): img_name = imgs_names[i] img_file = self.imgs_dir + img_name assert os.path.exists(img_file) img = cv.imread(img_file, cv.IMREAD_COLOR) min_dim = min(img.shape[-3], img.shape[-2]) resize_ratio = self.frame_size / float(min_dim) img = cv.resize(img, (0, 0), fx=resize_ratio, fy=resize_ratio) cols = img.shape[1] rows = img.shape[0] y1 = (rows - self.frame_size) / 2 y2 = y1 + self.frame_size x1 = (cols - self.frame_size) / 2 x2 = x1 + self.frame_size img = img[y1:y2, x1:x2] if self.bgr_to_rgb: img = img[..., ::-1] image_data = img[:, :, 0:3].transpose(2, 0, 1) batch[i] = self.preprocess(image_data) return batch class MeanBlobFetch(DataFetch): mean_blob = np.ndarray(()) def __init__(self, frame_size, mean_blob_path, imgs_dir): self.imgs_dir = imgs_dir self.frame_size = frame_size blob = caffe.proto.caffe_pb2.BlobProto() data = open(mean_blob_path, 'rb').read() blob.ParseFromString(data) self.mean_blob = np.array(caffe.io.blobproto_to_array(blob)) start = (self.mean_blob.shape[2] - self.frame_size) / 2 stop = start + self.frame_size self.mean_blob = self.mean_blob[:, :, start:stop, start:stop][0] def preprocess(self, img): return img - self.mean_blob class MeanChannelsFetch(MeanBlobFetch): def __init__(self, frame_size, imgs_dir): self.imgs_dir = imgs_dir self.frame_size = frame_size self.mean_blob = np.ones((3, self.frame_size, self.frame_size)).astype(np.float32) self.mean_blob[0] *= 104 self.mean_blob[1] *= 117 self.mean_blob[2] *= 123 class MeanValueFetch(MeanBlobFetch): def __init__(self, frame_size, imgs_dir, bgr_to_rgb): self.imgs_dir = imgs_dir self.frame_size = frame_size self.mean_blob = np.ones((3, self.frame_size, self.frame_size)).astype(np.float32) self.mean_blob *= 117 self.bgr_to_rgb = bgr_to_rgb def get_correct_answers(img_list, img_classes, net_output_blob): correct_answers = 0 for i in range(len(img_list)): indexes = np.argsort(net_output_blob[i])[-5:] correct_index = img_classes[img_list[i]] if correct_index in indexes: correct_answers += 1 return correct_answers class Framework(object): in_blob_name = '' out_blob_name = '' __metaclass__ = ABCMeta @abstractmethod def get_name(self): pass @abstractmethod def get_output(self, input_blob): pass class CaffeModel(Framework): net = caffe.Net need_reshape = False def __init__(self, prototxt, caffemodel, in_blob_name, out_blob_name, need_reshape=False): caffe.set_mode_cpu() self.net = caffe.Net(prototxt, caffemodel, caffe.TEST) self.in_blob_name = in_blob_name self.out_blob_name = out_blob_name self.need_reshape = need_reshape def get_name(self): return 'Caffe' def get_output(self, input_blob): if self.need_reshape: self.net.blobs[self.in_blob_name].reshape(*input_blob.shape) return self.net.forward_all(**{self.in_blob_name: input_blob})[self.out_blob_name] class DnnCaffeModel(Framework): net = object def __init__(self, prototxt, caffemodel, in_blob_name, out_blob_name): self.net = cv.dnn.readNetFromCaffe(prototxt, caffemodel) self.in_blob_name = in_blob_name self.out_blob_name = out_blob_name def get_name(self): return 'DNN' def get_output(self, input_blob): self.net.setInput(input_blob, self.in_blob_name) return self.net.forward(self.out_blob_name) class ClsAccEvaluation: log = sys.stdout img_classes = {} batch_size = 0 def __init__(self, log_path, img_classes_file, batch_size): self.log = open(log_path, 'w') self.img_classes = self.read_classes(img_classes_file) self.batch_size = batch_size @staticmethod def read_classes(img_classes_file): result = {} with open(img_classes_file) as file: for l in file.readlines(): result[l.split()[0]] = int(l.split()[1]) return result def process(self, frameworks, data_fetcher): sorted_imgs_names = sorted(self.img_classes.keys()) correct_answers = [0] * len(frameworks) samples_handled = 0 blobs_l1_diff = [0] * len(frameworks) blobs_l1_diff_count = [0] * len(frameworks) blobs_l_inf_diff = [sys.float_info.min] * len(frameworks) inference_time = [0.0] * len(frameworks) for x in xrange(0, len(sorted_imgs_names), self.batch_size): sublist = sorted_imgs_names[x:x + self.batch_size] batch = data_fetcher.get_batch(sublist) samples_handled += len(sublist) frameworks_out = [] fw_accuracy = [] for i in range(len(frameworks)): start = time.time() out = frameworks[i].get_output(batch) end = time.time() correct_answers[i] += get_correct_answers(sublist, self.img_classes, out) fw_accuracy.append(100 * correct_answers[i] / float(samples_handled)) frameworks_out.append(out) inference_time[i] += end - start print(samples_handled, 'Accuracy for', frameworks[i].get_name() + ':', fw_accuracy[i], file=self.log) print("Inference time, ms ", \ frameworks[i].get_name(), inference_time[i] / samples_handled * 1000, file=self.log) for i in range(1, len(frameworks)): log_str = frameworks[0].get_name() + " vs " + frameworks[i].get_name() + ':' diff = np.abs(frameworks_out[0] - frameworks_out[i]) l1_diff = np.sum(diff) / diff.size print(samples_handled, "L1 difference", log_str, l1_diff, file=self.log) blobs_l1_diff[i] += l1_diff blobs_l1_diff_count[i] += 1 if np.max(diff) > blobs_l_inf_diff[i]: blobs_l_inf_diff[i] = np.max(diff) print(samples_handled, "L_INF difference", log_str, blobs_l_inf_diff[i], file=self.log) self.log.flush() for i in range(1, len(blobs_l1_diff)): log_str = frameworks[0].get_name() + " vs " + frameworks[i].get_name() + ':' print('Final l1 diff', log_str, blobs_l1_diff[i] / blobs_l1_diff_count[i], file=self.log) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--imgs_dir", help="path to ImageNet validation subset images dir, ILSVRC2012_img_val dir") parser.add_argument("--img_cls_file", help="path to file with classes ids for images, val.txt file from this " "archive: http://dl.caffe.berkeleyvision.org/caffe_ilsvrc12.tar.gz") parser.add_argument("--prototxt", help="path to caffe prototxt, download it here: " "https://github.com/BVLC/caffe/blob/master/models/bvlc_alexnet/deploy.prototxt") parser.add_argument("--caffemodel", help="path to caffemodel file, download it here: " "http://dl.caffe.berkeleyvision.org/bvlc_alexnet.caffemodel") parser.add_argument("--log", help="path to logging file") parser.add_argument("--mean", help="path to ImageNet mean blob caffe file, imagenet_mean.binaryproto file from" "this archive: http://dl.caffe.berkeleyvision.org/caffe_ilsvrc12.tar.gz") parser.add_argument("--batch_size", help="size of images in batch", default=1000) parser.add_argument("--frame_size", help="size of input image", default=227) parser.add_argument("--in_blob", help="name for input blob", default='data') parser.add_argument("--out_blob", help="name for output blob", default='prob') args = parser.parse_args() data_fetcher = MeanBlobFetch(args.frame_size, args.mean, args.imgs_dir) frameworks = [CaffeModel(args.prototxt, args.caffemodel, args.in_blob, args.out_blob), DnnCaffeModel(args.prototxt, args.caffemodel, '', args.out_blob)] acc_eval = ClsAccEvaluation(args.log, args.img_cls_file, args.batch_size) acc_eval.process(frameworks, data_fetcher)
from __future__ import print_function from abc import ABCMeta, abstractmethod import numpy as np import sys import argparse import time from imagenet_cls_test_alexnet import CaffeModel, DnnCaffeModel try: import cv2 as cv except ImportError: raise ImportError('Can\'t find OpenCV Python module. If you\'ve built it from sources without installation, ' 'configure environment variable PYTHONPATH to "opencv_build_dir/lib" directory (with "python3" subdirectory if required)') def get_metrics(conf_mat): pix_accuracy = np.trace(conf_mat) / np.sum(conf_mat) t = np.sum(conf_mat, 1) num_cl = np.count_nonzero(t) assert num_cl mean_accuracy = np.sum(np.nan_to_num(np.divide(np.diagonal(conf_mat), t))) / num_cl col_sum = np.sum(conf_mat, 0) mean_iou = np.sum( np.nan_to_num(np.divide(np.diagonal(conf_mat), (t + col_sum - np.diagonal(conf_mat))))) / num_cl return pix_accuracy, mean_accuracy, mean_iou def eval_segm_result(net_out): assert type(net_out) is np.ndarray assert len(net_out.shape) == 4 channels_dim = 1 y_dim = channels_dim + 1 x_dim = y_dim + 1 res = np.zeros(net_out.shape).astype(np.int) for i in range(net_out.shape[y_dim]): for j in range(net_out.shape[x_dim]): max_ch = np.argmax(net_out[..., i, j]) res[0, max_ch, i, j] = 1 return res def get_conf_mat(gt, prob): assert type(gt) is np.ndarray assert type(prob) is np.ndarray conf_mat = np.zeros((gt.shape[0], gt.shape[0])) for ch_gt in range(conf_mat.shape[0]): gt_channel = gt[ch_gt, ...] for ch_pr in range(conf_mat.shape[1]): prob_channel = prob[ch_pr, ...] conf_mat[ch_gt][ch_pr] = np.count_nonzero(np.multiply(gt_channel, prob_channel)) return conf_mat class MeanChannelsPreproc: def __init__(self): pass @staticmethod def process(img): image_data = np.array(img).transpose(2, 0, 1).astype(np.float32) mean = np.ones(image_data.shape) mean[0] *= 104 mean[1] *= 117 mean[2] *= 123 image_data -= mean image_data = np.expand_dims(image_data, 0) return image_data class DatasetImageFetch(object): __metaclass__ = ABCMeta data_prepoc = object @abstractmethod def __iter__(self): pass @abstractmethod def next(self): pass @staticmethod def pix_to_c(pix): return pix[0] * 256 * 256 + pix[1] * 256 + pix[2] @staticmethod def color_to_gt(color_img, colors): num_classes = len(colors) gt = np.zeros((num_classes, color_img.shape[0], color_img.shape[1])).astype(np.int) for img_y in range(color_img.shape[0]): for img_x in range(color_img.shape[1]): c = DatasetImageFetch.pix_to_c(color_img[img_y][img_x]) if c in colors: cls = colors.index(c) gt[cls][img_y][img_x] = 1 return gt class PASCALDataFetch(DatasetImageFetch): img_dir = '' segm_dir = '' names = [] colors = [] i = 0 def __init__(self, img_dir, segm_dir, names_file, segm_cls_colors_file, preproc): self.img_dir = img_dir self.segm_dir = segm_dir self.colors = self.read_colors(segm_cls_colors_file) self.data_prepoc = preproc self.i = 0 with open(names_file) as f: for l in f.readlines(): self.names.append(l.rstrip()) @staticmethod def read_colors(img_classes_file): result = [] with open(img_classes_file) as f: for l in f.readlines(): color = np.array(map(int, l.split()[1:])) result.append(DatasetImageFetch.pix_to_c(color)) return result def __iter__(self): return self def next(self): if self.i < len(self.names): name = self.names[self.i] self.i += 1 segm_file = self.segm_dir + name + ".png" img_file = self.img_dir + name + ".jpg" gt = self.color_to_gt(cv.imread(segm_file, cv.IMREAD_COLOR)[:, :, ::-1], self.colors) img = self.data_prepoc.process(cv.imread(img_file, cv.IMREAD_COLOR)[:, :, ::-1]) return img, gt else: self.i = 0 raise StopIteration def get_num_classes(self): return len(self.colors) class SemSegmEvaluation: log = sys.stdout def __init__(self, log_path,): self.log = open(log_path, 'w') def process(self, frameworks, data_fetcher): samples_handled = 0 conf_mats = [np.zeros((data_fetcher.get_num_classes(), data_fetcher.get_num_classes())) for i in range(len(frameworks))] blobs_l1_diff = [0] * len(frameworks) blobs_l1_diff_count = [0] * len(frameworks) blobs_l_inf_diff = [sys.float_info.min] * len(frameworks) inference_time = [0.0] * len(frameworks) for in_blob, gt in data_fetcher: frameworks_out = [] samples_handled += 1 for i in range(len(frameworks)): start = time.time() out = frameworks[i].get_output(in_blob) end = time.time() segm = eval_segm_result(out) conf_mats[i] += get_conf_mat(gt, segm[0]) frameworks_out.append(out) inference_time[i] += end - start pix_acc, mean_acc, miou = get_metrics(conf_mats[i]) name = frameworks[i].get_name() print(samples_handled, 'Pixel accuracy, %s:' % name, 100 * pix_acc, file=self.log) print(samples_handled, 'Mean accuracy, %s:' % name, 100 * mean_acc, file=self.log) print(samples_handled, 'Mean IOU, %s:' % name, 100 * miou, file=self.log) print("Inference time, ms ", \ frameworks[i].get_name(), inference_time[i] / samples_handled * 1000, file=self.log) for i in range(1, len(frameworks)): log_str = frameworks[0].get_name() + " vs " + frameworks[i].get_name() + ':' diff = np.abs(frameworks_out[0] - frameworks_out[i]) l1_diff = np.sum(diff) / diff.size print(samples_handled, "L1 difference", log_str, l1_diff, file=self.log) blobs_l1_diff[i] += l1_diff blobs_l1_diff_count[i] += 1 if np.max(diff) > blobs_l_inf_diff[i]: blobs_l_inf_diff[i] = np.max(diff) print(samples_handled, "L_INF difference", log_str, blobs_l_inf_diff[i], file=self.log) self.log.flush() for i in range(1, len(blobs_l1_diff)): log_str = frameworks[0].get_name() + " vs " + frameworks[i].get_name() + ':' print('Final l1 diff', log_str, blobs_l1_diff[i] / blobs_l1_diff_count[i], file=self.log) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--imgs_dir", help="path to PASCAL VOC 2012 images dir, data/VOC2012/JPEGImages") parser.add_argument("--segm_dir", help="path to PASCAL VOC 2012 segmentation dir, data/VOC2012/SegmentationClass/") parser.add_argument("--val_names", help="path to file with validation set image names, download it here: " "https://github.com/shelhamer/fcn.berkeleyvision.org/blob/master/data/pascal/seg11valid.txt") parser.add_argument("--cls_file", help="path to file with colors for classes, download it here: " "https://github.com/opencv/opencv/blob/master/samples/data/dnn/pascal-classes.txt") parser.add_argument("--prototxt", help="path to caffe prototxt, download it here: " "https://github.com/opencv/opencv/blob/master/samples/data/dnn/fcn8s-heavy-pascal.prototxt") parser.add_argument("--caffemodel", help="path to caffemodel file, download it here: " "http://dl.caffe.berkeleyvision.org/fcn8s-heavy-pascal.caffemodel") parser.add_argument("--log", help="path to logging file") parser.add_argument("--in_blob", help="name for input blob", default='data') parser.add_argument("--out_blob", help="name for output blob", default='score') args = parser.parse_args() prep = MeanChannelsPreproc() df = PASCALDataFetch(args.imgs_dir, args.segm_dir, args.val_names, args.cls_file, prep) fw = [CaffeModel(args.prototxt, args.caffemodel, args.in_blob, args.out_blob, True), DnnCaffeModel(args.prototxt, args.caffemodel, '', args.out_blob)] segm_eval = SemSegmEvaluation(args.log) segm_eval.process(fw, df)
# Iterate all GLSL shaders (with suffix '.comp') in current directory. # # Use glslangValidator to compile them to SPIR-V shaders and write them # into .cpp files as unsigned int array. # # Also generate a header file 'spv_shader.hpp' to extern declare these shaders. import re import os import sys dir = "./" license_decl = \ '// This file is part of OpenCV project.\n'\ '// It is subject to the license terms in the LICENSE file found in the top-level directory\n'\ '// of this distribution and at http://opencv.org/license.html.\n'\ '//\n'\ '// Copyright (C) 2018, Intel Corporation, all rights reserved.\n'\ '// Third party copyrights are property of their respective owners.\n\n' precomp = '#include \"../../precomp.hpp\"\n' ns_head = '\nnamespace cv { namespace dnn { namespace vkcom {\n\n' ns_tail = '\n}}} // namespace cv::dnn::vkcom\n' headfile = open('spv_shader.hpp', 'w') headfile.write(license_decl) headfile.write('#ifndef OPENCV_DNN_SPV_SHADER_HPP\n') headfile.write('#define OPENCV_DNN_SPV_SHADER_HPP\n\n') headfile.write(ns_head) cmd_remove = '' null_out = '' if sys.platform.find('win32') != -1: cmd_remove = 'del' null_out = ' >>nul 2>nul' elif sys.platform.find('linux') != -1: cmd_remove = 'rm' null_out = ' > /dev/null 2>&1' list = os.listdir(dir) for i in range(0, len(list)): if (os.path.splitext(list[i])[-1] != '.comp'): continue prefix = os.path.splitext(list[i])[0]; path = os.path.join(dir, list[i]) bin_file = prefix + '.tmp' cmd = ' glslangValidator -V ' + path + ' -S comp -o ' + bin_file print('compiling') if os.system(cmd) != 0: continue; size = os.path.getsize(bin_file) spv_txt_file = prefix + '.spv' cmd = 'glslangValidator -V ' + path + ' -S comp -o ' + spv_txt_file + ' -x' + null_out os.system(cmd) infile_name = spv_txt_file outfile_name = prefix + '_spv.cpp' array_name = prefix + '_spv' infile = open(infile_name, 'r') outfile = open(outfile_name, 'w') outfile.write(license_decl) outfile.write(precomp) outfile.write(ns_head) # xxx.spv ==> xxx_spv.cpp fmt = 'extern const unsigned int %s[%d] = {\n' % (array_name, size/4) outfile.write(fmt) for eachLine in infile: if(re.match(r'^.*\/\/', eachLine)): continue newline = ' ' + eachLine.replace('\t','') outfile.write(newline) infile.close() outfile.write("};\n") outfile.write(ns_tail) # write a line into header file fmt = 'extern const unsigned int %s[%d];\n' % (array_name, size/4) headfile.write(fmt) os.system(cmd_remove + ' ' + bin_file) os.system(cmd_remove + ' ' + spv_txt_file) headfile.write(ns_tail) headfile.write('\n#endif /* OPENCV_DNN_SPV_SHADER_HPP */\n') headfile.close();
#!/usr/bin/env python from __future__ import print_function import numpy as np import cv2 as cv from tests_common import NewOpenCVTests class Bindings(NewOpenCVTests): def check_name(self, name): #print(name) self.assertFalse(name == None) self.assertFalse(name == "") def test_registry(self): self.check_name(cv.videoio_registry.getBackendName(cv.CAP_ANY)); self.check_name(cv.videoio_registry.getBackendName(cv.CAP_FFMPEG)) self.check_name(cv.videoio_registry.getBackendName(cv.CAP_OPENCV_MJPEG)) backends = cv.videoio_registry.getBackends() for backend in backends: self.check_name(cv.videoio_registry.getBackendName(backend)) if __name__ == '__main__': NewOpenCVTests.bootstrap()
#!/usr/bin/env python ''' Feature homography ================== Example of using features2d framework for interactive video homography matching. ORB features and FLANN matcher are used. The actual tracking is implemented by PlaneTracker class in plane_tracker.py ''' # Python 2/3 compatibility from __future__ import print_function import numpy as np import cv2 as cv import sys PY3 = sys.version_info[0] == 3 if PY3: xrange = range # local modules from tst_scene_render import TestSceneRender def intersectionRate(s1, s2): x1, y1, x2, y2 = s1 s1 = np.array([[x1, y1], [x2,y1], [x2, y2], [x1, y2]]) area, _intersection = cv.intersectConvexConvex(s1, np.array(s2)) return 2 * area / (cv.contourArea(s1) + cv.contourArea(np.array(s2))) from tests_common import NewOpenCVTests class feature_homography_test(NewOpenCVTests): render = None tracker = None framesCounter = 0 frame = None def test_feature_homography(self): self.render = TestSceneRender(self.get_sample('samples/data/graf1.png'), self.get_sample('samples/data/box.png'), noise = 0.5, speed = 0.5) self.frame = self.render.getNextFrame() self.tracker = PlaneTracker() self.tracker.clear() self.tracker.add_target(self.frame, self.render.getCurrentRect()) while self.framesCounter < 100: self.framesCounter += 1 tracked = self.tracker.track(self.frame) if len(tracked) > 0: tracked = tracked[0] self.assertGreater(intersectionRate(self.render.getCurrentRect(), np.int32(tracked.quad)), 0.6) else: self.assertEqual(0, 1, 'Tracking error') self.frame = self.render.getNextFrame() # built-in modules from collections import namedtuple FLANN_INDEX_KDTREE = 1 FLANN_INDEX_LSH = 6 flann_params= dict(algorithm = FLANN_INDEX_LSH, table_number = 6, # 12 key_size = 12, # 20 multi_probe_level = 1) #2 MIN_MATCH_COUNT = 10 ''' image - image to track rect - tracked rectangle (x1, y1, x2, y2) keypoints - keypoints detected inside rect descrs - their descriptors data - some user-provided data ''' PlanarTarget = namedtuple('PlaneTarget', 'image, rect, keypoints, descrs, data') ''' target - reference to PlanarTarget p0 - matched points coords in target image p1 - matched points coords in input frame H - homography matrix from p0 to p1 quad - target boundary quad in input frame ''' TrackedTarget = namedtuple('TrackedTarget', 'target, p0, p1, H, quad') class PlaneTracker: def __init__(self): self.detector = cv.AKAZE_create(threshold = 0.003) self.matcher = cv.FlannBasedMatcher(flann_params, {}) # bug : need to pass empty dict (#1329) self.targets = [] self.frame_points = [] def add_target(self, image, rect, data=None): '''Add a new tracking target.''' x0, y0, x1, y1 = rect raw_points, raw_descrs = self.detect_features(image) points, descs = [], [] for kp, desc in zip(raw_points, raw_descrs): x, y = kp.pt if x0 <= x <= x1 and y0 <= y <= y1: points.append(kp) descs.append(desc) descs = np.uint8(descs) self.matcher.add([descs]) target = PlanarTarget(image = image, rect=rect, keypoints = points, descrs=descs, data=data) self.targets.append(target) def clear(self): '''Remove all targets''' self.targets = [] self.matcher.clear() def track(self, frame): '''Returns a list of detected TrackedTarget objects''' self.frame_points, frame_descrs = self.detect_features(frame) if len(self.frame_points) < MIN_MATCH_COUNT: return [] matches = self.matcher.knnMatch(frame_descrs, k = 2) matches = [m[0] for m in matches if len(m) == 2 and m[0].distance < m[1].distance * 0.75] if len(matches) < MIN_MATCH_COUNT: return [] matches_by_id = [[] for _ in xrange(len(self.targets))] for m in matches: matches_by_id[m.imgIdx].append(m) tracked = [] for imgIdx, matches in enumerate(matches_by_id): if len(matches) < MIN_MATCH_COUNT: continue target = self.targets[imgIdx] p0 = [target.keypoints[m.trainIdx].pt for m in matches] p1 = [self.frame_points[m.queryIdx].pt for m in matches] p0, p1 = np.float32((p0, p1)) H, status = cv.findHomography(p0, p1, cv.RANSAC, 3.0) status = status.ravel() != 0 if status.sum() < MIN_MATCH_COUNT: continue p0, p1 = p0[status], p1[status] x0, y0, x1, y1 = target.rect quad = np.float32([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]) quad = cv.perspectiveTransform(quad.reshape(1, -1, 2), H).reshape(-1, 2) track = TrackedTarget(target=target, p0=p0, p1=p1, H=H, quad=quad) tracked.append(track) tracked.sort(key = lambda t: len(t.p0), reverse=True) return tracked def detect_features(self, frame): '''detect_features(self, frame) -> keypoints, descrs''' keypoints, descrs = self.detector.detectAndCompute(frame, None) if descrs is None: # detectAndCompute returns descs=None if no keypoints found descrs = [] return keypoints, descrs if __name__ == '__main__': NewOpenCVTests.bootstrap()
#!/usr/bin/env python from __future__ import print_function import collections import re import os.path import sys from xml.dom.minidom import parse if sys.version_info > (3,): long = int def cmp(a, b): return (a>b)-(a<b) class TestInfo(object): def __init__(self, xmlnode): self.fixture = xmlnode.getAttribute("classname") self.name = xmlnode.getAttribute("name") self.value_param = xmlnode.getAttribute("value_param") self.type_param = xmlnode.getAttribute("type_param") custom_status = xmlnode.getAttribute("custom_status") failures = xmlnode.getElementsByTagName("failure") if len(custom_status) > 0: self.status = custom_status elif len(failures) > 0: self.status = "failed" else: self.status = xmlnode.getAttribute("status") if self.name.startswith("DISABLED_"): if self.status == 'notrun': self.status = "disabled" self.fixture = self.fixture.replace("DISABLED_", "") self.name = self.name.replace("DISABLED_", "") self.properties = { prop.getAttribute("name") : prop.getAttribute("value") for prop in xmlnode.getElementsByTagName("property") if prop.hasAttribute("name") and prop.hasAttribute("value") } self.metrix = {} self.parseLongMetric(xmlnode, "bytesIn"); self.parseLongMetric(xmlnode, "bytesOut"); self.parseIntMetric(xmlnode, "samples"); self.parseIntMetric(xmlnode, "outliers"); self.parseFloatMetric(xmlnode, "frequency", 1); self.parseLongMetric(xmlnode, "min"); self.parseLongMetric(xmlnode, "median"); self.parseLongMetric(xmlnode, "gmean"); self.parseLongMetric(xmlnode, "mean"); self.parseLongMetric(xmlnode, "stddev"); self.parseFloatMetric(xmlnode, "gstddev"); self.parseFloatMetric(xmlnode, "time"); self.parseLongMetric(xmlnode, "total_memory_usage"); def parseLongMetric(self, xmlnode, name, default = 0): if name in self.properties: self.metrix[name] = long(self.properties[name]) elif xmlnode.hasAttribute(name): self.metrix[name] = long(xmlnode.getAttribute(name)) else: self.metrix[name] = default def parseIntMetric(self, xmlnode, name, default = 0): if name in self.properties: self.metrix[name] = int(self.properties[name]) elif xmlnode.hasAttribute(name): self.metrix[name] = int(xmlnode.getAttribute(name)) else: self.metrix[name] = default def parseFloatMetric(self, xmlnode, name, default = 0): if name in self.properties: self.metrix[name] = float(self.properties[name]) elif xmlnode.hasAttribute(name): self.metrix[name] = float(xmlnode.getAttribute(name)) else: self.metrix[name] = default def parseStringMetric(self, xmlnode, name, default = None): if name in self.properties: self.metrix[name] = self.properties[name].strip() elif xmlnode.hasAttribute(name): self.metrix[name] = xmlnode.getAttribute(name).strip() else: self.metrix[name] = default def get(self, name, units="ms"): if name == "classname": return self.fixture if name == "name": return self.name if name == "fullname": return self.__str__() if name == "value_param": return self.value_param if name == "type_param": return self.type_param if name == "status": return self.status val = self.metrix.get(name, None) if not val: return val if name == "time": return self.metrix.get("time") if name in ["gmean", "min", "mean", "median", "stddev"]: scale = 1.0 frequency = self.metrix.get("frequency", 1.0) or 1.0 if units == "ms": scale = 1000.0 if units == "us" or units == "mks": # mks is typo error for microsecond (<= OpenCV 3.4) scale = 1000000.0 if units == "ns": scale = 1000000000.0 if units == "ticks": frequency = long(1) scale = long(1) return val * scale / frequency return val def dump(self, units="ms"): print("%s ->\t\033[1;31m%s\033[0m = \t%.2f%s" % (str(self), self.status, self.get("gmean", units), units)) def getName(self): pos = self.name.find("/") if pos > 0: return self.name[:pos] return self.name def getFixture(self): if self.fixture.endswith(self.getName()): fixture = self.fixture[:-len(self.getName())] else: fixture = self.fixture if fixture.endswith("_"): fixture = fixture[:-1] return fixture def param(self): return '::'.join(filter(None, [self.type_param, self.value_param])) def shortName(self): name = self.getName() fixture = self.getFixture() return '::'.join(filter(None, [name, fixture])) def __str__(self): name = self.getName() fixture = self.getFixture() return '::'.join(filter(None, [name, fixture, self.type_param, self.value_param])) def __cmp__(self, other): r = cmp(self.fixture, other.fixture); if r != 0: return r if self.type_param: if other.type_param: r = cmp(self.type_param, other.type_param); if r != 0: return r else: return -1 else: if other.type_param: return 1 if self.value_param: if other.value_param: r = cmp(self.value_param, other.value_param); if r != 0: return r else: return -1 else: if other.value_param: return 1 return 0 # This is a Sequence for compatibility with old scripts, # which treat parseLogFile's return value as a list. class TestRunInfo(collections.Sequence): def __init__(self, properties, tests): self.properties = properties self.tests = tests def __len__(self): return len(self.tests) def __getitem__(self, key): return self.tests[key] def parseLogFile(filename): log = parse(filename) properties = { attr_name[3:]: attr_value for (attr_name, attr_value) in log.documentElement.attributes.items() if attr_name.startswith('cv_') } tests = list(map(TestInfo, log.getElementsByTagName("testcase"))) return TestRunInfo(properties, tests) if __name__ == "__main__": if len(sys.argv) < 2: print("Usage:\n", os.path.basename(sys.argv[0]), "<log_name>.xml") exit(0) for arg in sys.argv[1:]: print("Processing {}...".format(arg)) run = parseLogFile(arg) print("Properties:") for (prop_name, prop_value) in run.properties.items(): print("\t{} = {}".format(prop_name, prop_value)) print("Tests:") for t in sorted(run.tests): t.dump() print()
#!/usr/bin/env python from __future__ import print_function import xml.etree.ElementTree as ET from glob import glob from pprint import PrettyPrinter as PP LONG_TESTS_DEBUG_VALGRIND = [ ('calib3d', 'Calib3d_InitUndistortRectifyMap.accuracy', 2017.22), ('dnn', 'Reproducibility*', 1000), # large DNN models ('dnn', '*RCNN*', 1000), # very large DNN models ('dnn', '*RFCN*', 1000), # very large DNN models ('dnn', '*EAST*', 1000), # very large DNN models ('dnn', '*VGG16*', 1000), # very large DNN models ('dnn', '*ZFNet*', 1000), # very large DNN models ('dnn', '*ResNet101_DUC_HDC*', 1000), # very large DNN models ('dnn', '*LResNet100E_IR*', 1000), # very large DNN models ('dnn', '*read_yolo_voc_stream*', 1000), # very large DNN models ('dnn', '*eccv16*', 1000), # very large DNN models ('dnn', '*OpenPose*', 1000), # very large DNN models ('dnn', '*SSD/*', 1000), # very large DNN models ('gapi', 'Fluid.MemoryConsumptionDoesNotGrowOnReshape', 1000000), # test doesn't work properly under valgrind ('face', 'CV_Face_FacemarkLBF.test_workflow', 10000.0), # >40min on i7 ('features2d', 'Features2d/DescriptorImage.no_crash/3', 1000), ('features2d', 'Features2d/DescriptorImage.no_crash/4', 1000), ('features2d', 'Features2d/DescriptorImage.no_crash/5', 1000), ('features2d', 'Features2d/DescriptorImage.no_crash/6', 1000), ('features2d', 'Features2d/DescriptorImage.no_crash/7', 1000), ('imgcodecs', 'Imgcodecs_Png.write_big', 1000), # memory limit ('imgcodecs', 'Imgcodecs_Tiff.decode_tile16384x16384', 1000), # memory limit ('ml', 'ML_RTrees.regression', 1423.47), ('optflow', 'DenseOpticalFlow_DeepFlow.ReferenceAccuracy', 1360.95), ('optflow', 'DenseOpticalFlow_DeepFlow_perf.perf/0', 1881.59), ('optflow', 'DenseOpticalFlow_DeepFlow_perf.perf/1', 5608.75), ('optflow', 'DenseOpticalFlow_GlobalPatchColliderDCT.ReferenceAccuracy', 5433.84), ('optflow', 'DenseOpticalFlow_GlobalPatchColliderWHT.ReferenceAccuracy', 5232.73), ('optflow', 'DenseOpticalFlow_SimpleFlow.ReferenceAccuracy', 1542.1), ('photo', 'Photo_Denoising.speed', 1484.87), ('photo', 'Photo_DenoisingColoredMulti.regression', 2447.11), ('rgbd', 'Rgbd_Normals.compute', 1156.32), ('shape', 'Hauss.regression', 2625.72), ('shape', 'ShapeEMD_SCD.regression', 61913.7), ('shape', 'Shape_SCD.regression', 3311.46), ('tracking', 'AUKF.br_mean_squared_error', 10764.6), ('tracking', 'UKF.br_mean_squared_error', 5228.27), ('tracking', '*DistanceAndOverlap*/1', 1000.0), # dudek ('tracking', '*DistanceAndOverlap*/2', 1000.0), # faceocc2 ('videoio', 'videoio/videoio_ffmpeg.write_big*', 1000), ('videoio', 'videoio_ffmpeg.parallel', 1000), ('xfeatures2d', 'Features2d_RotationInvariance_Descriptor_BoostDesc_LBGM.regression', 1124.51), ('xfeatures2d', 'Features2d_RotationInvariance_Descriptor_VGG120.regression', 2198.1), ('xfeatures2d', 'Features2d_RotationInvariance_Descriptor_VGG48.regression', 1958.52), ('xfeatures2d', 'Features2d_RotationInvariance_Descriptor_VGG64.regression', 2113.12), ('xfeatures2d', 'Features2d_RotationInvariance_Descriptor_VGG80.regression', 2167.16), ('xfeatures2d', 'Features2d_ScaleInvariance_Descriptor_BoostDesc_LBGM.regression', 1511.39), ('xfeatures2d', 'Features2d_ScaleInvariance_Descriptor_VGG120.regression', 1222.07), ('xfeatures2d', 'Features2d_ScaleInvariance_Descriptor_VGG48.regression', 1059.14), ('xfeatures2d', 'Features2d_ScaleInvariance_Descriptor_VGG64.regression', 1163.41), ('xfeatures2d', 'Features2d_ScaleInvariance_Descriptor_VGG80.regression', 1179.06), ('ximgproc', 'L0SmoothTest.SplatSurfaceAccuracy', 6382.26), ('ximgproc', 'perf*/1*:perf*/2*:perf*/3*:perf*/4*:perf*/5*:perf*/6*:perf*/7*:perf*/8*:perf*/9*', 1000.0), # only first 10 parameters ('ximgproc', 'TypicalSet1/RollingGuidanceFilterTest.MultiThreadReproducibility/5', 1086.33), ('ximgproc', 'TypicalSet1/RollingGuidanceFilterTest.MultiThreadReproducibility/7', 1405.05), ('ximgproc', 'TypicalSet1/RollingGuidanceFilterTest.SplatSurfaceAccuracy/5', 1253.07), ('ximgproc', 'TypicalSet1/RollingGuidanceFilterTest.SplatSurfaceAccuracy/7', 1599.98), ('ximgproc', '*MultiThreadReproducibility*/1:*MultiThreadReproducibility*/2:*MultiThreadReproducibility*/3:*MultiThreadReproducibility*/4:*MultiThreadReproducibility*/5:*MultiThreadReproducibility*/6:*MultiThreadReproducibility*/7:*MultiThreadReproducibility*/8:*MultiThreadReproducibility*/9:*MultiThreadReproducibility*/1*', 1000.0), ('ximgproc', '*AdaptiveManifoldRefImplTest*/1:*AdaptiveManifoldRefImplTest*/2:*AdaptiveManifoldRefImplTest*/3', 1000.0), ('ximgproc', '*JointBilateralFilterTest_NaiveRef*', 1000.0), ('ximgproc', '*RollingGuidanceFilterTest_BilateralRef*/1*:*RollingGuidanceFilterTest_BilateralRef*/2*:*RollingGuidanceFilterTest_BilateralRef*/3*', 1000.0), ('ximgproc', '*JointBilateralFilterTest_NaiveRef*', 1000.0), ] def longTestFilter(data, module=None): res = ['*', '-'] + [v for m, v, _time in data if module is None or m == module] return '--gtest_filter={}'.format(':'.join(res)) # Parse one xml file, filter out tests which took less than 'timeLimit' seconds # Returns tuple: ( <module_name>, [ (<module_name>, <test_name>, <test_time>), ... ] ) def parseOneFile(filename, timeLimit): tree = ET.parse(filename) root = tree.getroot() def guess(s, delims): for delim in delims: tmp = s.partition(delim) if len(tmp[1]) != 0: return tmp[0] return None module = guess(filename, ['_posix_', '_nt_', '__']) or root.get('cv_module_name') if not module: return (None, None) res = [] for elem in root.findall('.//testcase'): key = '{}.{}'.format(elem.get('classname'), elem.get('name')) val = elem.get('time') if float(val) >= timeLimit: res.append((module, key, float(val))) return (module, res) # Parse all xml files in current folder and combine results into one list # Print result to the stdout if __name__ == '__main__': LIMIT = 1000 res = [] xmls = glob('*.xml') for xml in xmls: print('Parsing file', xml, '...') module, testinfo = parseOneFile(xml, LIMIT) if not module: print('SKIP') continue res.extend(testinfo) print('========= RESULTS =========') PP(indent=4, width=100).pprint(sorted(res))
#!/usr/bin/env python import os import argparse import logging import datetime from run_utils import Err, CMakeCache, log, execute from run_suite import TestSuite from run_android import AndroidTestSuite epilog = ''' NOTE: Additional options starting with "--gtest_" and "--perf_" will be passed directly to the test executables. ''' if __name__ == "__main__": # log.basicConfig(format='[%(levelname)s] %(message)s', level = log.DEBUG) # log.basicConfig(format='[%(levelname)s] %(message)s', level = log.INFO) parser = argparse.ArgumentParser( description='OpenCV test runner script', epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("build_path", nargs='?', default=".", help="Path to build directory (should contain CMakeCache.txt, default is current) or to directory with tests (all platform checks will be disabled in this case)") parser.add_argument("-t", "--tests", metavar="MODULES", default="", help="Comma-separated list of modules to test (example: -t core,imgproc,java)") parser.add_argument("-b", "--blacklist", metavar="MODULES", default="", help="Comma-separated list of modules to exclude from test (example: -b java)") parser.add_argument("-a", "--accuracy", action="store_true", default=False, help="Look for accuracy tests instead of performance tests") parser.add_argument("--check", action="store_true", default=False, help="Shortcut for '--perf_min_samples=1 --perf_force_samples=1'") parser.add_argument("-w", "--cwd", metavar="PATH", default=".", help="Working directory for tests (default is current)") parser.add_argument("--list", action="store_true", default=False, help="List available tests (executables)") parser.add_argument("--list_short", action="store_true", default=False, help="List available tests (aliases)") parser.add_argument("--list_short_main", action="store_true", default=False, help="List available tests (main repository, aliases)") parser.add_argument("--configuration", metavar="CFG", default=None, help="Force Debug or Release configuration (for Visual Studio and Java tests build)") parser.add_argument("-n", "--dry_run", action="store_true", help="Do not run the tests") parser.add_argument("-v", "--verbose", action="store_true", default=False, help="Print more debug information") # Valgrind parser.add_argument("--valgrind", action="store_true", default=False, help="Run C++ tests in valgrind") parser.add_argument("--valgrind_supp", metavar="FILE", action='append', help="Path to valgrind suppression file (example: --valgrind_supp opencv/platforms/scripts/valgrind.supp)") parser.add_argument("--valgrind_opt", metavar="OPT", action="append", default=[], help="Add command line option to valgrind (example: --valgrind_opt=--leak-check=full)") # QEMU parser.add_argument("--qemu", default="", help="Specify qemu binary and base parameters") # Android parser.add_argument("--android", action="store_true", default=False, help="Android: force all tests to run on device") parser.add_argument("--android_sdk", metavar="PATH", help="Android: path to SDK to use adb and aapt tools") parser.add_argument("--android_test_data_path", metavar="PATH", default="/sdcard/opencv_testdata/", help="Android: path to testdata on device") parser.add_argument("--android_env", action='append', help="Android: add environment variable (NAME=VALUE)") parser.add_argument("--android_propagate_opencv_env", action="store_true", default=False, help="Android: propagate OPENCV* environment variables") parser.add_argument("--serial", metavar="serial number", default="", help="Android: directs command to the USB device or emulator with the given serial number") parser.add_argument("--package", metavar="package", default="", help="Java: run JUnit tests for specified module or Android package") parser.add_argument("--trace", action="store_true", default=False, help="Trace: enable OpenCV tracing") parser.add_argument("--trace_dump", metavar="trace_dump", default=-1, help="Trace: dump highlight calls (specify max entries count, 0 - dump all)") args, other_args = parser.parse_known_args() log.setLevel(logging.DEBUG if args.verbose else logging.INFO) test_args = [a for a in other_args if a.startswith("--perf_") or a.startswith("--test_") or a.startswith("--gtest_")] bad_args = [a for a in other_args if a not in test_args] if len(bad_args) > 0: log.error("Error: Bad arguments: %s", bad_args) exit(1) args.mode = "test" if args.accuracy else "perf" android_env = [] if args.android_env: android_env.extend([entry.split("=", 1) for entry in args.android_env]) if args.android_propagate_opencv_env: android_env.extend([entry for entry in os.environ.items() if entry[0].startswith('OPENCV')]) android_env = dict(android_env) if args.android_test_data_path: android_env['OPENCV_TEST_DATA_PATH'] = args.android_test_data_path if args.valgrind: try: ver = execute(["valgrind", "--version"], silent=True) log.debug("Using %s", ver) except OSError as e: log.error("Failed to run valgrind: %s", e) exit(1) if len(args.build_path) != 1: test_args = [a for a in test_args if not a.startswith("--gtest_output=")] if args.check: if not [a for a in test_args if a.startswith("--perf_min_samples=")]: test_args.extend(["--perf_min_samples=1"]) if not [a for a in test_args if a.startswith("--perf_force_samples=")]: test_args.extend(["--perf_force_samples=1"]) if not [a for a in test_args if a.startswith("--perf_verify_sanity")]: test_args.extend(["--perf_verify_sanity"]) if bool(os.environ.get('BUILD_PRECOMMIT', None)): test_args.extend(["--skip_unstable=1"]) ret = 0 logs = [] stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") path = args.build_path try: if not os.path.isdir(path): raise Err("Not a directory (should contain CMakeCache.txt ot test executables)") cache = CMakeCache(args.configuration) fname = os.path.join(path, "CMakeCache.txt") if os.path.isfile(fname): log.debug("Reading cmake cache file: %s", fname) cache.read(path, fname) else: log.debug("Assuming folder contains tests: %s", path) cache.setDummy(path) if args.android or cache.getOS() == "android": log.debug("Creating Android test runner") suite = AndroidTestSuite(args, cache, stamp, android_env) else: log.debug("Creating native test runner") suite = TestSuite(args, cache, stamp) if args.list or args.list_short or args.list_short_main: suite.listTests(args.list_short or args.list_short_main, args.list_short_main) else: log.debug("Running tests in '%s', working dir: '%s'", path, args.cwd) def parseTests(s): return [o.strip() for o in s.split(",") if o] logs, ret = suite.runTests(parseTests(args.tests), parseTests(args.blacklist), args.cwd, test_args) except Err as e: log.error("ERROR: test path '%s' ==> %s", path, e.msg) ret = -1 if logs: log.warning("Collected: %s", logs) if ret != 0: log.error("ERROR: some tests have failed") exit(ret)
#!/usr/bin/env python import math, os, sys webcolors = { "indianred": "#cd5c5c", "lightcoral": "#f08080", "salmon": "#fa8072", "darksalmon": "#e9967a", "lightsalmon": "#ffa07a", "red": "#ff0000", "crimson": "#dc143c", "firebrick": "#b22222", "darkred": "#8b0000", "pink": "#ffc0cb", "lightpink": "#ffb6c1", "hotpink": "#ff69b4", "deeppink": "#ff1493", "mediumvioletred": "#c71585", "palevioletred": "#db7093", "lightsalmon": "#ffa07a", "coral": "#ff7f50", "tomato": "#ff6347", "orangered": "#ff4500", "darkorange": "#ff8c00", "orange": "#ffa500", "gold": "#ffd700", "yellow": "#ffff00", "lightyellow": "#ffffe0", "lemonchiffon": "#fffacd", "lightgoldenrodyellow": "#fafad2", "papayawhip": "#ffefd5", "moccasin": "#ffe4b5", "peachpuff": "#ffdab9", "palegoldenrod": "#eee8aa", "khaki": "#f0e68c", "darkkhaki": "#bdb76b", "lavender": "#e6e6fa", "thistle": "#d8bfd8", "plum": "#dda0dd", "violet": "#ee82ee", "orchid": "#da70d6", "fuchsia": "#ff00ff", "magenta": "#ff00ff", "mediumorchid": "#ba55d3", "mediumpurple": "#9370db", "blueviolet": "#8a2be2", "darkviolet": "#9400d3", "darkorchid": "#9932cc", "darkmagenta": "#8b008b", "purple": "#800080", "indigo": "#4b0082", "darkslateblue": "#483d8b", "slateblue": "#6a5acd", "mediumslateblue": "#7b68ee", "greenyellow": "#adff2f", "chartreuse": "#7fff00", "lawngreen": "#7cfc00", "lime": "#00ff00", "limegreen": "#32cd32", "palegreen": "#98fb98", "lightgreen": "#90ee90", "mediumspringgreen": "#00fa9a", "springgreen": "#00ff7f", "mediumseagreen": "#3cb371", "seagreen": "#2e8b57", "forestgreen": "#228b22", "green": "#008000", "darkgreen": "#006400", "yellowgreen": "#9acd32", "olivedrab": "#6b8e23", "olive": "#808000", "darkolivegreen": "#556b2f", "mediumaquamarine": "#66cdaa", "darkseagreen": "#8fbc8f", "lightseagreen": "#20b2aa", "darkcyan": "#008b8b", "teal": "#008080", "aqua": "#00ffff", "cyan": "#00ffff", "lightcyan": "#e0ffff", "paleturquoise": "#afeeee", "aquamarine": "#7fffd4", "turquoise": "#40e0d0", "mediumturquoise": "#48d1cc", "darkturquoise": "#00ced1", "cadetblue": "#5f9ea0", "steelblue": "#4682b4", "lightsteelblue": "#b0c4de", "powderblue": "#b0e0e6", "lightblue": "#add8e6", "skyblue": "#87ceeb", "lightskyblue": "#87cefa", "deepskyblue": "#00bfff", "dodgerblue": "#1e90ff", "cornflowerblue": "#6495ed", "royalblue": "#4169e1", "blue": "#0000ff", "mediumblue": "#0000cd", "darkblue": "#00008b", "navy": "#000080", "midnightblue": "#191970", "cornsilk": "#fff8dc", "blanchedalmond": "#ffebcd", "bisque": "#ffe4c4", "navajowhite": "#ffdead", "wheat": "#f5deb3", "burlywood": "#deb887", "tan": "#d2b48c", "rosybrown": "#bc8f8f", "sandybrown": "#f4a460", "goldenrod": "#daa520", "darkgoldenrod": "#b8860b", "peru": "#cd853f", "chocolate": "#d2691e", "saddlebrown": "#8b4513", "sienna": "#a0522d", "brown": "#a52a2a", "maroon": "#800000", "white": "#ffffff", "snow": "#fffafa", "honeydew": "#f0fff0", "mintcream": "#f5fffa", "azure": "#f0ffff", "aliceblue": "#f0f8ff", "ghostwhite": "#f8f8ff", "whitesmoke": "#f5f5f5", "seashell": "#fff5ee", "beige": "#f5f5dc", "oldlace": "#fdf5e6", "floralwhite": "#fffaf0", "ivory": "#fffff0", "antiquewhite": "#faebd7", "linen": "#faf0e6", "lavenderblush": "#fff0f5", "mistyrose": "#ffe4e1", "gainsboro": "#dcdcdc", "lightgrey": "#d3d3d3", "silver": "#c0c0c0", "darkgray": "#a9a9a9", "gray": "#808080", "dimgray": "#696969", "lightslategray": "#778899", "slategray": "#708090", "darkslategray": "#2f4f4f", "black": "#000000", } if os.name == "nt": consoleColors = [ "#000000", #{ 0, 0, 0 },//0 - black "#000080", #{ 0, 0, 128 },//1 - navy "#008000", #{ 0, 128, 0 },//2 - green "#008080", #{ 0, 128, 128 },//3 - teal "#800000", #{ 128, 0, 0 },//4 - maroon "#800080", #{ 128, 0, 128 },//5 - purple "#808000", #{ 128, 128, 0 },//6 - olive "#C0C0C0", #{ 192, 192, 192 },//7 - silver "#808080", #{ 128, 128, 128 },//8 - gray "#0000FF", #{ 0, 0, 255 },//9 - blue "#00FF00", #{ 0, 255, 0 },//a - lime "#00FFFF", #{ 0, 255, 255 },//b - cyan "#FF0000", #{ 255, 0, 0 },//c - red "#FF00FF", #{ 255, 0, 255 },//d - magenta "#FFFF00", #{ 255, 255, 0 },//e - yellow "#FFFFFF", #{ 255, 255, 255 } //f - white ] else: consoleColors = [ "#2e3436", "#cc0000", "#4e9a06", "#c4a000", "#3465a4", "#75507b", "#06989a", "#d3d7cf", "#ffffff", "#555753", "#ef2929", "#8ae234", "#fce94f", "#729fcf", "#ad7fa8", "#34e2e2", "#eeeeec", ] def RGB2LAB(r,g,b): if max(r,g,b): r /= 255. g /= 255. b /= 255. X = (0.412453 * r + 0.357580 * g + 0.180423 * b) / 0.950456 Y = (0.212671 * r + 0.715160 * g + 0.072169 * b) Z = (0.019334 * r + 0.119193 * g + 0.950227 * b) / 1.088754 #[X * 0.950456] [0.412453 0.357580 0.180423] [R] #[Y ] = [0.212671 0.715160 0.072169] * [G] #[Z * 1.088754] [0.019334 0.119193 0.950227] [B] T = 0.008856 #threshold if X > T: fX = math.pow(X, 1./3.) else: fX = 7.787 * X + 16./116. # Compute L if Y > T: Y3 = math.pow(Y, 1./3.) fY = Y3 L = 116. * Y3 - 16.0 else: fY = 7.787 * Y + 16./116. L = 903.3 * Y if Z > T: fZ = math.pow(Z, 1./3.) else: fZ = 7.787 * Z + 16./116. # Compute a and b a = 500. * (fX - fY) b = 200. * (fY - fZ) return (L,a,b) def colorDistance(r1,g1,b1 = None, r2 = None, g2 = None,b2 = None): if type(r1) == tuple and type(g1) == tuple and b1 is None and r2 is None and g2 is None and b2 is None: (l1,a1,b1) = RGB2LAB(*r1) (l2,a2,b2) = RGB2LAB(*g1) else: (l1,a1,b1) = RGB2LAB(r1,g1,b1) (l2,a2,b2) = RGB2LAB(r2,g2,b2) #CIE94 dl = l1-l2 C1 = math.sqrt(a1*a1 + b1*b1) C2 = math.sqrt(a2*a2 + b2*b2) dC = C1 - C2 da = a1-a2 db = b1-b2 dH = math.sqrt(max(0, da*da + db*db - dC*dC)) Kl = 1 K1 = 0.045 K2 = 0.015 s1 = dl/Kl s2 = dC/(1. + K1 * C1) s3 = dH/(1. + K2 * C1) return math.sqrt(s1*s1 + s2*s2 + s3*s3) def parseHexColor(col): if len(col) != 4 and len(col) != 7 and not col.startswith("#"): return (0,0,0) if len(col) == 4: r = col[1]*2 g = col[2]*2 b = col[3]*2 else: r = col[1:3] g = col[3:5] b = col[5:7] return (int(r,16), int(g,16), int(b,16)) def getColor(col): if isinstance(col, str): if col.lower() in webcolors: return parseHexColor(webcolors[col.lower()]) else: return parseHexColor(col) else: return col def getNearestConsoleColor(col): color = getColor(col) minidx = 0 mindist = colorDistance(color, getColor(consoleColors[0])) for i in range(len(consoleColors)): dist = colorDistance(color, getColor(consoleColors[i])) if dist < mindist: mindist = dist minidx = i return minidx if os.name == 'nt': import msvcrt from ctypes import windll, Structure, c_short, c_ushort, byref SHORT = c_short WORD = c_ushort class COORD(Structure): _fields_ = [ ("X", SHORT), ("Y", SHORT)] class SMALL_RECT(Structure): _fields_ = [ ("Left", SHORT), ("Top", SHORT), ("Right", SHORT), ("Bottom", SHORT)] class CONSOLE_SCREEN_BUFFER_INFO(Structure): _fields_ = [ ("dwSize", COORD), ("dwCursorPosition", COORD), ("wAttributes", WORD), ("srWindow", SMALL_RECT), ("dwMaximumWindowSize", COORD)] class winConsoleColorizer(object): def __init__(self, stream): self.handle = msvcrt.get_osfhandle(stream.fileno()) self.default_attrs = 7#self.get_text_attr() self.stream = stream def get_text_attr(self): csbi = CONSOLE_SCREEN_BUFFER_INFO() windll.kernel32.GetConsoleScreenBufferInfo(self.handle, byref(csbi)) return csbi.wAttributes def set_text_attr(self, color): windll.kernel32.SetConsoleTextAttribute(self.handle, color) def write(self, *text, **attrs): if not text: return color = attrs.get("color", None) if color: col = getNearestConsoleColor(color) self.stream.flush() self.set_text_attr(col) self.stream.write(" ".join([str(t) for t in text])) if color: self.stream.flush() self.set_text_attr(self.default_attrs) class dummyColorizer(object): def __init__(self, stream): self.stream = stream def write(self, *text, **attrs): if text: self.stream.write(" ".join([str(t) for t in text])) class asciiSeqColorizer(object): RESET_SEQ = "\033[0m" #BOLD_SEQ = "\033[1m" ITALIC_SEQ = "\033[3m" UNDERLINE_SEQ = "\033[4m" STRIKEOUT_SEQ = "\033[9m" COLOR_SEQ0 = "\033[00;%dm" #dark COLOR_SEQ1 = "\033[01;%dm" #bold and light def __init__(self, stream): self.stream = stream def get_seq(self, code): if code > 8: return self.__class__.COLOR_SEQ1 % (30 + code - 9) else: return self.__class__.COLOR_SEQ0 % (30 + code) def write(self, *text, **attrs): if not text: return color = attrs.get("color", None) if color: col = getNearestConsoleColor(color) self.stream.write(self.get_seq(col)) self.stream.write(" ".join([str(t) for t in text])) if color: self.stream.write(self.__class__.RESET_SEQ) def getColorizer(stream): if stream.isatty(): if os.name == "nt": return winConsoleColorizer(stream) else: return asciiSeqColorizer(stream) else: return dummyColorizer(stream)
#!/usr/bin/env python from optparse import OptionParser import glob, sys, os, re if __name__ == "__main__": parser = OptionParser() parser.add_option("-o", "--output", dest="output", help="output file name", metavar="FILENAME", default=None) (options, args) = parser.parse_args() if not options.output: sys.stderr.write("Error: output file name is not provided") exit(-1) files = [] for arg in args: if ("*" in arg) or ("?" in arg): files.extend([os.path.abspath(f) for f in glob.glob(arg)]) else: files.append(os.path.abspath(arg)) html = None for f in sorted(files): try: fobj = open(f) if not fobj: continue text = fobj.read() if not html: html = text continue idx1 = text.find("<tbody>") + len("<tbody>") idx2 = html.rfind("</tbody>") html = html[:idx2] + re.sub(r"[ \t\n\r]+", " ", text[idx1:]) except: pass if html: idx1 = text.find("<title>") + len("<title>") idx2 = html.find("</title>") html = html[:idx1] + "OpenCV performance testing report" + html[idx2:] open(options.output, "w").write(html) else: sys.stderr.write("Error: no input data") exit(-1)
#!/usr/bin/env python import testlog_parser, sys, os, xml, re from table_formatter import * from optparse import OptionParser cvsize_re = re.compile("^\d+x\d+$") cvtype_re = re.compile("^(CV_)(8U|8S|16U|16S|32S|32F|64F)(C\d{1,3})?$") def keyselector(a): if cvsize_re.match(a): size = [int(d) for d in a.split('x')] return size[0] * size[1] elif cvtype_re.match(a): if a.startswith("CV_"): a = a[3:] depth = 7 if a[0] == '8': depth = (0, 1) [a[1] == 'S'] elif a[0] == '1': depth = (2, 3) [a[2] == 'S'] elif a[2] == 'S': depth = 4 elif a[0] == '3': depth = 5 elif a[0] == '6': depth = 6 cidx = a.find('C') if cidx < 0: channels = 1 else: channels = int(a[a.index('C') + 1:]) #return (depth & 7) + ((channels - 1) << 3) return ((channels-1) & 511) + (depth << 9) return a convert = lambda text: int(text) if text.isdigit() else text alphanum_keyselector = lambda key: [ convert(c) for c in re.split('([0-9]+)', str(keyselector(key))) ] def getValueParams(test): param = test.get("value_param") if not param: return [] if param.startswith("("): param = param[1:] if param.endswith(")"): param = param[:-1] args = [] prev_pos = 0 start = 0 balance = 0 while True: idx = param.find(",", prev_pos) if idx < 0: break idxlb = param.find("(", prev_pos, idx) while idxlb >= 0: balance += 1 idxlb = param.find("(", idxlb+1, idx) idxrb = param.find(")", prev_pos, idx) while idxrb >= 0: balance -= 1 idxrb = param.find(")", idxrb+1, idx) assert(balance >= 0) if balance == 0: args.append(param[start:idx].strip()) start = idx + 1 prev_pos = idx + 1 args.append(param[start:].strip()) return args #return [p.strip() for p in param.split(",")] def nextPermutation(indexes, lists, x, y): idx = len(indexes)-1 while idx >= 0: while idx == x or idx == y: idx -= 1 if idx < 0: return False v = indexes[idx] + 1 if v < len(lists[idx]): indexes[idx] = v; return True; else: indexes[idx] = 0; idx -= 1 return False def getTestWideName(sname, indexes, lists, x, y): name = sname + "::(" for i in range(len(indexes)): if i > 0: name += ", " if i == x: name += "X" elif i == y: name += "Y" else: name += lists[i][indexes[i]] return str(name + ")") def getTest(stests, x, y, row, col): for pair in stests: if pair[1][x] == row and pair[1][y] == col: return pair[0] return None if __name__ == "__main__": parser = OptionParser() parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar="FMT", default="auto") parser.add_option("-u", "--units", dest="units", help="units for output values (s, ms (default), us, ns or ticks)", metavar="UNITS", default="ms") parser.add_option("-m", "--metric", dest="metric", help="output metric", metavar="NAME", default="gmean") parser.add_option("-x", "", dest="x", help="argument number for rows", metavar="ROW", default=1) parser.add_option("-y", "", dest="y", help="argument number for columns", metavar="COL", default=0) parser.add_option("-f", "--filter", dest="filter", help="regex to filter tests", metavar="REGEX", default=None) (options, args) = parser.parse_args() if len(args) != 1: print >> sys.stderr, "Usage:\n", os.path.basename(sys.argv[0]), "<log_name1>.xml" exit(1) options.generateHtml = detectHtmlOutputType(options.format) if options.metric not in metrix_table: options.metric = "gmean" if options.metric.endswith("%"): options.metric = options.metric[:-1] getter = metrix_table[options.metric][1] tests = testlog_parser.parseLogFile(args[0]) if options.filter: expr = re.compile(options.filter) tests = [(t,getValueParams(t)) for t in tests if expr.search(str(t))] else: tests = [(t,getValueParams(t)) for t in tests] args[0] = os.path.basename(args[0]) if not tests: print >> sys.stderr, "Error - no tests matched" exit(1) argsnum = len(tests[0][1]) sname = tests[0][0].shortName() arglists = [] for i in range(argsnum): arglists.append({}) names = set() names1 = set() for pair in tests: sn = pair[0].shortName() if len(pair[1]) > 1: names.add(sn) else: names1.add(sn) if sn == sname: if len(pair[1]) != argsnum: print >> sys.stderr, "Error - unable to create chart tables for functions having different argument numbers" sys.exit(1) for i in range(argsnum): arglists[i][pair[1][i]] = 1 if names1 or len(names) != 1: print >> sys.stderr, "Error - unable to create tables for functions from different test suits:" i = 1 for name in sorted(names): print >> sys.stderr, "%4s: %s" % (i, name) i += 1 if names1: print >> sys.stderr, "Other suits in this log (can not be chosen):" for name in sorted(names1): print >> sys.stderr, "%4s: %s" % (i, name) i += 1 sys.exit(1) if argsnum < 2: print >> sys.stderr, "Error - tests from %s have less than 2 parameters" % sname exit(1) for i in range(argsnum): arglists[i] = sorted([str(key) for key in arglists[i].iterkeys()], key=alphanum_keyselector) if options.generateHtml and options.format != "moinwiki": htmlPrintHeader(sys.stdout, "Report %s for %s" % (args[0], sname)) indexes = [0] * argsnum x = int(options.x) y = int(options.y) if x == y or x < 0 or y < 0 or x >= argsnum or y >= argsnum: x = 1 y = 0 while True: stests = [] for pair in tests: t = pair[0] v = pair[1] for i in range(argsnum): if i != x and i != y: if v[i] != arglists[i][indexes[i]]: t = None break if t: stests.append(pair) tbl = table(metrix_table[options.metric][0] + " for\n" + getTestWideName(sname, indexes, arglists, x, y)) tbl.newColumn("x", "X\Y") for col in arglists[y]: tbl.newColumn(col, col, align="center") for row in arglists[x]: tbl.newRow() tbl.newCell("x", row) for col in arglists[y]: case = getTest(stests, x, y, row, col) if case: status = case.get("status") if status != "run": tbl.newCell(col, status, color = "red") else: val = getter(case, None, options.units) if isinstance(val, float): tbl.newCell(col, "%.2f %s" % (val, options.units), val) else: tbl.newCell(col, val, val) else: tbl.newCell(col, "-") if options.generateHtml: tbl.htmlPrintTable(sys.stdout, options.format == "moinwiki") else: tbl.consolePrintTable(sys.stdout) if not nextPermutation(indexes, arglists, x, y): break if options.generateHtml and options.format != "moinwiki": htmlPrintFooter(sys.stdout)
#!/usr/bin/env python import sys import os import platform import re import tempfile import glob import logging import shutil from subprocess import check_call, check_output, CalledProcessError, STDOUT def initLogger(): logger = logging.getLogger("run.py") logger.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stderr) ch.setFormatter(logging.Formatter("%(message)s")) logger.addHandler(ch) return logger log = initLogger() hostos = os.name # 'nt', 'posix' class Err(Exception): def __init__(self, msg, *args): self.msg = msg % args def execute(cmd, silent=False, cwd=".", env=None): try: log.debug("Run: %s", cmd) if env is not None: for k in env: log.debug(" Environ: %s=%s", k, env[k]) new_env = os.environ.copy() new_env.update(env) env = new_env if sys.platform == 'darwin': # https://github.com/opencv/opencv/issues/14351 if env is None: env = os.environ.copy() if 'DYLD_LIBRARY_PATH' in env: env['OPENCV_SAVED_DYLD_LIBRARY_PATH'] = env['DYLD_LIBRARY_PATH'] if silent: return check_output(cmd, stderr=STDOUT, cwd=cwd, env=env).decode("latin-1") else: return check_call(cmd, cwd=cwd, env=env) except CalledProcessError as e: if silent: log.debug("Process returned: %d", e.returncode) return e.output.decode("latin-1") else: log.error("Process returned: %d", e.returncode) return e.returncode def isColorEnabled(args): usercolor = [a for a in args if a.startswith("--gtest_color=")] return len(usercolor) == 0 and sys.stdout.isatty() and hostos != "nt" def getPlatformVersion(): mv = platform.mac_ver() if mv[0]: return "Darwin" + mv[0] else: wv = platform.win32_ver() if wv[0]: return "Windows" + wv[0] else: lv = platform.linux_distribution() if lv[0]: return lv[0] + lv[1] return None parse_patterns = ( {'name': "cmake_home", 'default': None, 'pattern': re.compile(r"^CMAKE_HOME_DIRECTORY:\w+=(.+)$")}, {'name': "opencv_home", 'default': None, 'pattern': re.compile(r"^OpenCV_SOURCE_DIR:\w+=(.+)$")}, {'name': "opencv_build", 'default': None, 'pattern': re.compile(r"^OpenCV_BINARY_DIR:\w+=(.+)$")}, {'name': "tests_dir", 'default': None, 'pattern': re.compile(r"^EXECUTABLE_OUTPUT_PATH:\w+=(.+)$")}, {'name': "build_type", 'default': "Release", 'pattern': re.compile(r"^CMAKE_BUILD_TYPE:\w+=(.*)$")}, {'name': "android_abi", 'default': None, 'pattern': re.compile(r"^ANDROID_ABI:\w+=(.*)$")}, {'name': "android_executable", 'default': None, 'pattern': re.compile(r"^ANDROID_EXECUTABLE:\w+=(.*android.*)$")}, {'name': "ant_executable", 'default': None, 'pattern': re.compile(r"^ANT_EXECUTABLE:\w+=(.*ant.*)$")}, {'name': "java_test_dir", 'default': None, 'pattern': re.compile(r"^OPENCV_JAVA_TEST_DIR:\w+=(.*)$")}, {'name': "is_x64", 'default': "OFF", 'pattern': re.compile(r"^CUDA_64_BIT_DEVICE_CODE:\w+=(ON)$")}, {'name': "cmake_generator", 'default': None, 'pattern': re.compile(r"^CMAKE_GENERATOR:\w+=(.+)$")}, {'name': "python2", 'default': None, 'pattern': re.compile(r"^BUILD_opencv_python2:\w+=(.*)$")}, {'name': "python3", 'default': None, 'pattern': re.compile(r"^BUILD_opencv_python3:\w+=(.*)$")}, ) class CMakeCache: def __init__(self, cfg=None): self.setDefaultAttrs() self.main_modules = [] if cfg: self.build_type = cfg def setDummy(self, path): self.tests_dir = os.path.normpath(path) def read(self, path, fname): rx = re.compile(r'^OPENCV_MODULE_opencv_(\w+)_LOCATION:INTERNAL=(.*)$') module_paths = {} # name -> path with open(fname, "rt") as cachefile: for l in cachefile.readlines(): ll = l.strip() if not ll or ll.startswith("#"): continue for p in parse_patterns: match = p["pattern"].match(ll) if match: value = match.groups()[0] if value and not value.endswith("-NOTFOUND"): setattr(self, p["name"], value) # log.debug("cache value: %s = %s", p["name"], value) match = rx.search(ll) if match: module_paths[match.group(1)] = match.group(2) if not self.tests_dir: self.tests_dir = path else: rel = os.path.relpath(self.tests_dir, self.opencv_build) self.tests_dir = os.path.join(path, rel) self.tests_dir = os.path.normpath(self.tests_dir) # fix VS test binary path (add Debug or Release) if "Visual Studio" in self.cmake_generator: self.tests_dir = os.path.join(self.tests_dir, self.build_type) for module, path in module_paths.items(): rel = os.path.relpath(path, self.opencv_home) if ".." not in rel: self.main_modules.append(module) def setDefaultAttrs(self): for p in parse_patterns: setattr(self, p["name"], p["default"]) def gatherTests(self, mask, isGood=None): if self.tests_dir and os.path.isdir(self.tests_dir): d = os.path.abspath(self.tests_dir) files = glob.glob(os.path.join(d, mask)) if not self.getOS() == "android" and self.withJava(): files.append("java") if self.withPython2(): files.append("python2") if self.withPython3(): files.append("python3") return [f for f in files if isGood(f)] return [] def isMainModule(self, name): return name in self.main_modules + ['python2', 'python3'] def withJava(self): return self.ant_executable and self.java_test_dir and os.path.exists(self.java_test_dir) def withPython2(self): return self.python2 == 'ON' def withPython3(self): return self.python3 == 'ON' def getOS(self): if self.android_executable: return "android" else: return hostos class TempEnvDir: def __init__(self, envname, prefix): self.envname = envname self.prefix = prefix self.saved_name = None self.new_name = None def init(self): self.saved_name = os.environ.get(self.envname) self.new_name = tempfile.mkdtemp(prefix=self.prefix, dir=self.saved_name or None) os.environ[self.envname] = self.new_name def clean(self): if self.saved_name: os.environ[self.envname] = self.saved_name else: del os.environ[self.envname] try: shutil.rmtree(self.new_name) except: pass if __name__ == "__main__": log.error("This is utility file, please execute run.py script")
#!/usr/bin/env python import testlog_parser, sys, os, xml, glob, re from table_formatter import * from optparse import OptionParser numeric_re = re.compile("(\d+)") cvtype_re = re.compile("(8U|8S|16U|16S|32S|32F|64F)C(\d{1,3})") cvtypes = { '8U': 0, '8S': 1, '16U': 2, '16S': 3, '32S': 4, '32F': 5, '64F': 6 } convert = lambda text: int(text) if text.isdigit() else text keyselector = lambda a: cvtype_re.sub(lambda match: " " + str(cvtypes.get(match.group(1), 7) + (int(match.group(2))-1) * 8) + " ", a) alphanum_keyselector = lambda key: [ convert(c) for c in numeric_re.split(keyselector(key)) ] def getSetName(tset, idx, columns, short = True): if columns and len(columns) > idx: prefix = columns[idx] else: prefix = None if short and prefix: return prefix name = tset[0].replace(".xml","").replace("_", "\n") if prefix: return prefix + "\n" + ("-"*int(len(max(prefix.split("\n"), key=len))*1.5)) + "\n" + name return name if __name__ == "__main__": if len(sys.argv) < 2: print >> sys.stderr, "Usage:\n", os.path.basename(sys.argv[0]), "<log_name1>.xml [<log_name2>.xml ...]" exit(0) parser = OptionParser() parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html', 'markdown' or 'auto' - default)", metavar="FMT", default="auto") parser.add_option("-m", "--metric", dest="metric", help="output metric", metavar="NAME", default="gmean") parser.add_option("-u", "--units", dest="units", help="units for output values (s, ms (default), us, ns or ticks)", metavar="UNITS", default="ms") parser.add_option("-f", "--filter", dest="filter", help="regex to filter tests", metavar="REGEX", default=None) parser.add_option("", "--module", dest="module", default=None, metavar="NAME", help="module prefix for test names") parser.add_option("", "--columns", dest="columns", default=None, metavar="NAMES", help="comma-separated list of column aliases") parser.add_option("", "--no-relatives", action="store_false", dest="calc_relatives", default=True, help="do not output relative values") parser.add_option("", "--with-cycles-reduction", action="store_true", dest="calc_cr", default=False, help="output cycle reduction percentages") parser.add_option("", "--with-score", action="store_true", dest="calc_score", default=False, help="output automatic classification of speedups") parser.add_option("", "--progress", action="store_true", dest="progress_mode", default=False, help="enable progress mode") parser.add_option("", "--regressions", dest="regressions", default=None, metavar="LIST", help="comma-separated custom regressions map: \"[r][c]#current-#reference\" (indexes of columns are 0-based, \"r\" - reverse flag, \"c\" - color flag for base data)") parser.add_option("", "--show-all", action="store_true", dest="showall", default=False, help="also include empty and \"notrun\" lines") parser.add_option("", "--match", dest="match", default=None) parser.add_option("", "--match-replace", dest="match_replace", default="") parser.add_option("", "--regressions-only", dest="regressionsOnly", default=None, metavar="X-FACTOR", help="show only tests with performance regressions not") parser.add_option("", "--intersect-logs", dest="intersect_logs", default=False, help="show only tests present in all log files") parser.add_option("", "--show_units", action="store_true", dest="show_units", help="append units into table cells") (options, args) = parser.parse_args() options.generateHtml = detectHtmlOutputType(options.format) if options.metric not in metrix_table: options.metric = "gmean" if options.metric.endswith("%") or options.metric.endswith("$"): options.calc_relatives = False options.calc_cr = False if options.columns: options.columns = [s.strip().replace("\\n", "\n") for s in options.columns.split(",")] if options.regressions: assert not options.progress_mode, 'unsupported mode' def parseRegressionColumn(s): """ Format: '[r][c]<uint>-<uint>' """ reverse = s.startswith('r') if reverse: s = s[1:] addColor = s.startswith('c') if addColor: s = s[1:] parts = s.split('-', 1) link = (int(parts[0]), int(parts[1]), reverse, addColor) assert link[0] != link[1] return link options.regressions = [parseRegressionColumn(s) for s in options.regressions.split(',')] show_units = options.units if options.show_units else None # expand wildcards and filter duplicates files = [] seen = set() for arg in args: if ("*" in arg) or ("?" in arg): flist = [os.path.abspath(f) for f in glob.glob(arg)] flist = sorted(flist, key= lambda text: str(text).replace("M", "_")) files.extend([ x for x in flist if x not in seen and not seen.add(x)]) else: fname = os.path.abspath(arg) if fname not in seen and not seen.add(fname): files.append(fname) # read all passed files test_sets = [] for arg in files: try: tests = testlog_parser.parseLogFile(arg) if options.filter: expr = re.compile(options.filter) tests = [t for t in tests if expr.search(str(t))] if options.match: tests = [t for t in tests if t.get("status") != "notrun"] if tests: test_sets.append((os.path.basename(arg), tests)) except IOError as err: sys.stderr.write("IOError reading \"" + arg + "\" - " + str(err) + os.linesep) except xml.parsers.expat.ExpatError as err: sys.stderr.write("ExpatError reading \"" + arg + "\" - " + str(err) + os.linesep) if not test_sets: sys.stderr.write("Error: no test data found" + os.linesep) quit() setsCount = len(test_sets) if options.regressions is None: reference = -1 if options.progress_mode else 0 options.regressions = [(i, reference, False, True) for i in range(1, len(test_sets))] for link in options.regressions: (i, ref, reverse, addColor) = link assert i >= 0 and i < setsCount assert ref < setsCount # find matches test_cases = {} name_extractor = lambda name: str(name) if options.match: reg = re.compile(options.match) name_extractor = lambda name: reg.sub(options.match_replace, str(name)) for i in range(setsCount): for case in test_sets[i][1]: name = name_extractor(case) if options.module: name = options.module + "::" + name if name not in test_cases: test_cases[name] = [None] * setsCount test_cases[name][i] = case # build table getter = metrix_table[options.metric][1] getter_score = metrix_table["score"][1] if options.calc_score else None getter_p = metrix_table[options.metric + "%"][1] if options.calc_relatives else None getter_cr = metrix_table[options.metric + "$"][1] if options.calc_cr else None tbl = table('%s (%s)' % (metrix_table[options.metric][0], options.units), options.format) # header tbl.newColumn("name", "Name of Test", align = "left", cssclass = "col_name") for i in range(setsCount): tbl.newColumn(str(i), getSetName(test_sets[i], i, options.columns, False), align = "center") def addHeaderColumns(suffix, description, cssclass): for link in options.regressions: (i, ref, reverse, addColor) = link if reverse: i, ref = ref, i current_set = test_sets[i] current = getSetName(current_set, i, options.columns) if ref >= 0: reference_set = test_sets[ref] reference = getSetName(reference_set, ref, options.columns) else: reference = 'previous' tbl.newColumn(str(i) + '-' + str(ref) + suffix, '%s\nvs\n%s\n(%s)' % (current, reference, description), align='center', cssclass=cssclass) if options.calc_cr: addHeaderColumns(suffix='$', description='cycles reduction', cssclass='col_cr') if options.calc_relatives: addHeaderColumns(suffix='%', description='x-factor', cssclass='col_rel') if options.calc_score: addHeaderColumns(suffix='S', description='score', cssclass='col_name') # rows prevGroupName = None needNewRow = True lastRow = None for name in sorted(test_cases.keys(), key=alphanum_keyselector): cases = test_cases[name] if needNewRow: lastRow = tbl.newRow() if not options.showall: needNewRow = False tbl.newCell("name", name) groupName = next(c for c in cases if c).shortName() if groupName != prevGroupName: prop = lastRow.props.get("cssclass", "") if "firstingroup" not in prop: lastRow.props["cssclass"] = prop + " firstingroup" prevGroupName = groupName for i in range(setsCount): case = cases[i] if case is None: if options.intersect_logs: needNewRow = False break tbl.newCell(str(i), "-") else: status = case.get("status") if status != "run": tbl.newCell(str(i), status, color="red") else: val = getter(case, cases[0], options.units) if val: needNewRow = True tbl.newCell(str(i), formatValue(val, options.metric, show_units), val) if needNewRow: for link in options.regressions: (i, reference, reverse, addColor) = link if reverse: i, reference = reference, i tblCellID = str(i) + '-' + str(reference) case = cases[i] if case is None: if options.calc_relatives: tbl.newCell(tblCellID + "%", "-") if options.calc_cr: tbl.newCell(tblCellID + "$", "-") if options.calc_score: tbl.newCell(tblCellID + "$", "-") else: status = case.get("status") if status != "run": tbl.newCell(str(i), status, color="red") if status != "notrun": needNewRow = True if options.calc_relatives: tbl.newCell(tblCellID + "%", "-", color="red") if options.calc_cr: tbl.newCell(tblCellID + "$", "-", color="red") if options.calc_score: tbl.newCell(tblCellID + "S", "-", color="red") else: val = getter(case, cases[0], options.units) def getRegression(fn): if fn and val: for j in reversed(range(i)) if reference < 0 else [reference]: r = cases[j] if r is not None and r.get("status") == 'run': return fn(case, r, options.units) valp = getRegression(getter_p) if options.calc_relatives or options.progress_mode else None valcr = getRegression(getter_cr) if options.calc_cr else None val_score = getRegression(getter_score) if options.calc_score else None if not valp: color = None elif valp > 1.05: color = 'green' elif valp < 0.95: color = 'red' else: color = None if addColor: if not reverse: tbl.newCell(str(i), formatValue(val, options.metric, show_units), val, color=color) else: r = cases[reference] if r is not None and r.get("status") == 'run': val = getter(r, cases[0], options.units) tbl.newCell(str(reference), formatValue(val, options.metric, show_units), val, color=color) if options.calc_relatives: tbl.newCell(tblCellID + "%", formatValue(valp, "%"), valp, color=color, bold=color) if options.calc_cr: tbl.newCell(tblCellID + "$", formatValue(valcr, "$"), valcr, color=color, bold=color) if options.calc_score: tbl.newCell(tblCellID + "S", formatValue(val_score, "S"), val_score, color = color, bold = color) if not needNewRow: tbl.trimLastRow() if options.regressionsOnly: for r in reversed(range(len(tbl.rows))): for i in range(1, len(options.regressions) + 1): val = tbl.rows[r].cells[len(tbl.rows[r].cells) - i].value if val is not None and val < float(options.regressionsOnly): break else: tbl.rows.pop(r) # output table if options.generateHtml: if options.format == "moinwiki": tbl.htmlPrintTable(sys.stdout, True) else: htmlPrintHeader(sys.stdout, "Summary report for %s tests from %s test logs" % (len(test_cases), setsCount)) tbl.htmlPrintTable(sys.stdout) htmlPrintFooter(sys.stdout) else: tbl.consolePrintTable(sys.stdout) if options.regressionsOnly: sys.exit(len(tbl.rows))
#!/usr/bin/env python from __future__ import print_function import sys, re, os.path, cgi, stat, math from optparse import OptionParser from color import getColorizer, dummyColorizer class tblCell(object): def __init__(self, text, value = None, props = None): self.text = text self.value = value self.props = props class tblColumn(object): def __init__(self, caption, title = None, props = None): self.text = caption self.title = title self.props = props class tblRow(object): def __init__(self, colsNum, props = None): self.cells = [None] * colsNum self.props = props def htmlEncode(str): return '<br/>'.join([cgi.escape(s) for s in str]) class table(object): def_align = "left" def_valign = "middle" def_color = None def_colspan = 1 def_rowspan = 1 def_bold = False def_italic = False def_text="-" def __init__(self, caption = None, format=None): self.format = format self.is_markdown = self.format == 'markdown' self.columns = {} self.rows = [] self.ridx = -1; self.caption = caption pass def newRow(self, **properties): if len(self.rows) - 1 == self.ridx: self.rows.append(tblRow(len(self.columns), properties)) else: self.rows[self.ridx + 1].props = properties self.ridx += 1 return self.rows[self.ridx] def trimLastRow(self): if self.rows: self.rows.pop() if self.ridx >= len(self.rows): self.ridx = len(self.rows) - 1 def newColumn(self, name, caption, title = None, **properties): if name in self.columns: index = self.columns[name].index else: index = len(self.columns) if isinstance(caption, tblColumn): caption.index = index self.columns[name] = caption return caption else: col = tblColumn(caption, title, properties) col.index = index self.columns[name] = col return col def getColumn(self, name): if isinstance(name, str): return self.columns.get(name, None) else: vals = [v for v in self.columns.values() if v.index == name] if vals: return vals[0] return None def newCell(self, col_name, text, value = None, **properties): if self.ridx < 0: self.newRow() col = self.getColumn(col_name) row = self.rows[self.ridx] if not col: return None if isinstance(text, tblCell): cl = text else: cl = tblCell(text, value, properties) row.cells[col.index] = cl return cl def layoutTable(self): columns = self.columns.values() columns = sorted(columns, key=lambda c: c.index) colspanned = [] rowspanned = [] self.headerHeight = 1 rowsToAppend = 0 for col in columns: self.measureCell(col) if col.height > self.headerHeight: self.headerHeight = col.height col.minwidth = col.width col.line = None for r in range(len(self.rows)): row = self.rows[r] row.minheight = 1 for i in range(len(row.cells)): cell = row.cells[i] if row.cells[i] is None: continue cell.line = None self.measureCell(cell) colspan = int(self.getValue("colspan", cell)) rowspan = int(self.getValue("rowspan", cell)) if colspan > 1: colspanned.append((r,i)) if i + colspan > len(columns): colspan = len(columns) - i cell.colspan = colspan #clear spanned cells for j in range(i+1, min(len(row.cells), i + colspan)): row.cells[j] = None elif columns[i].minwidth < cell.width: columns[i].minwidth = cell.width if rowspan > 1: rowspanned.append((r,i)) rowsToAppend2 = r + colspan - len(self.rows) if rowsToAppend2 > rowsToAppend: rowsToAppend = rowsToAppend2 cell.rowspan = rowspan #clear spanned cells for j in range(r+1, min(len(self.rows), r + rowspan)): if len(self.rows[j].cells) > i: self.rows[j].cells[i] = None elif row.minheight < cell.height: row.minheight = cell.height self.ridx = len(self.rows) - 1 for r in range(rowsToAppend): self.newRow() self.rows[len(self.rows) - 1].minheight = 1 while colspanned: colspanned_new = [] for r, c in colspanned: cell = self.rows[r].cells[c] sum([col.minwidth for col in columns[c:c + cell.colspan]]) cell.awailable = sum([col.minwidth for col in columns[c:c + cell.colspan]]) + cell.colspan - 1 if cell.awailable < cell.width: colspanned_new.append((r,c)) colspanned = colspanned_new if colspanned: r,c = colspanned[0] cell = self.rows[r].cells[c] cols = columns[c:c + cell.colspan] total = cell.awailable - cell.colspan + 1 budget = cell.width - cell.awailable spent = 0 s = 0 for col in cols: s += col.minwidth addition = s * budget / total - spent spent += addition col.minwidth += addition while rowspanned: rowspanned_new = [] for r, c in rowspanned: cell = self.rows[r].cells[c] cell.awailable = sum([row.minheight for row in self.rows[r:r + cell.rowspan]]) if cell.awailable < cell.height: rowspanned_new.append((r,c)) rowspanned = rowspanned_new if rowspanned: r,c = rowspanned[0] cell = self.rows[r].cells[c] rows = self.rows[r:r + cell.rowspan] total = cell.awailable budget = cell.height - cell.awailable spent = 0 s = 0 for row in rows: s += row.minheight addition = s * budget / total - spent spent += addition row.minheight += addition return columns def measureCell(self, cell): text = self.getValue("text", cell) cell.text = self.reformatTextValue(text) cell.height = len(cell.text) cell.width = len(max(cell.text, key = lambda line: len(line))) def reformatTextValue(self, value): if sys.version_info >= (2,7): unicode = str if isinstance(value, str): vstr = value elif isinstance(value, unicode): vstr = str(value) else: try: vstr = '\n'.join([str(v) for v in value]) except TypeError: vstr = str(value) return vstr.splitlines() def adjustColWidth(self, cols, width): total = sum([c.minWidth for c in cols]) if total + len(cols) - 1 >= width: return budget = width - len(cols) + 1 - total spent = 0 s = 0 for col in cols: s += col.minWidth addition = s * budget / total - spent spent += addition col.minWidth += addition def getValue(self, name, *elements): for el in elements: try: return getattr(el, name) except AttributeError: pass try: val = el.props[name] if val: return val except AttributeError: pass except KeyError: pass try: return getattr(self.__class__, "def_" + name) except AttributeError: return None def consolePrintTable(self, out): columns = self.layoutTable() colrizer = getColorizer(out) if not self.is_markdown else dummyColorizer(out) if self.caption: out.write("%s%s%s" % ( os.linesep, os.linesep.join(self.reformatTextValue(self.caption)), os.linesep * 2)) headerRow = tblRow(len(columns), {"align": "center", "valign": "top", "bold": True, "header": True}) headerRow.cells = columns headerRow.minheight = self.headerHeight self.consolePrintRow2(colrizer, headerRow, columns) for i in range(0, len(self.rows)): self.consolePrintRow2(colrizer, i, columns) def consolePrintRow2(self, out, r, columns): if isinstance(r, tblRow): row = r r = -1 else: row = self.rows[r] #evaluate initial values for line numbers i = 0 while i < len(row.cells): cell = row.cells[i] colspan = self.getValue("colspan", cell) if cell is not None: cell.wspace = sum([col.minwidth for col in columns[i:i + colspan]]) + colspan - 1 if cell.line is None: if r < 0: rows = [row] else: rows = self.rows[r:r + self.getValue("rowspan", cell)] cell.line = self.evalLine(cell, rows, columns[i]) if len(rows) > 1: for rw in rows: rw.cells[i] = cell i += colspan #print content if self.is_markdown: out.write("|") for c in row.cells: text = ' '.join(self.getValue('text', c) or []) out.write(text + "|") out.write(os.linesep) else: for ln in range(row.minheight): i = 0 while i < len(row.cells): if i > 0: out.write(" ") cell = row.cells[i] column = columns[i] if cell is None: out.write(" " * column.minwidth) i += 1 else: self.consolePrintLine(cell, row, column, out) i += self.getValue("colspan", cell) if self.is_markdown: out.write("|") out.write(os.linesep) if self.is_markdown and row.props.get('header', False): out.write("|") for th in row.cells: align = self.getValue("align", th) if align == 'center': out.write(":-:|") elif align == 'right': out.write("--:|") else: out.write("---|") out.write(os.linesep) def consolePrintLine(self, cell, row, column, out): if cell.line < 0 or cell.line >= cell.height: line = "" else: line = cell.text[cell.line] width = cell.wspace align = self.getValue("align", ((None, cell)[isinstance(cell, tblCell)]), row, column) if align == "right": pattern = "%" + str(width) + "s" elif align == "center": pattern = "%" + str((width - len(line)) // 2 + len(line)) + "s" + " " * (width - len(line) - (width - len(line)) // 2) else: pattern = "%-" + str(width) + "s" out.write(pattern % line, color = self.getValue("color", cell, row, column)) cell.line += 1 def evalLine(self, cell, rows, column): height = cell.height valign = self.getValue("valign", cell, rows[0], column) space = sum([row.minheight for row in rows]) if valign == "bottom": return height - space if valign == "middle": return (height - space + 1) // 2 return 0 def htmlPrintTable(self, out, embeedcss = False): columns = self.layoutTable() if embeedcss: out.write("<div style=\"font-family: Lucida Console, Courier New, Courier;font-size: 16px;color:#3e4758;\">\n<table style=\"background:none repeat scroll 0 0 #FFFFFF;border-collapse:collapse;font-family:'Lucida Sans Unicode','Lucida Grande',Sans-Serif;font-size:14px;margin:20px;text-align:left;width:480px;margin-left: auto;margin-right: auto;white-space:nowrap;\">\n") else: out.write("<div class=\"tableFormatter\">\n<table class=\"tbl\">\n") if self.caption: if embeedcss: out.write(" <caption style=\"font:italic 16px 'Trebuchet MS',Verdana,Arial,Helvetica,sans-serif;padding:0 0 5px;text-align:right;white-space:normal;\">%s</caption>\n" % htmlEncode(self.reformatTextValue(self.caption))) else: out.write(" <caption>%s</caption>\n" % htmlEncode(self.reformatTextValue(self.caption))) out.write(" <thead>\n") headerRow = tblRow(len(columns), {"align": "center", "valign": "top", "bold": True, "header": True}) headerRow.cells = columns header_rows = [headerRow] header_rows.extend([row for row in self.rows if self.getValue("header")]) last_row = header_rows[len(header_rows) - 1] for row in header_rows: out.write(" <tr>\n") for th in row.cells: align = self.getValue("align", ((None, th)[isinstance(th, tblCell)]), row, row) valign = self.getValue("valign", th, row) cssclass = self.getValue("cssclass", th) attr = "" if align: attr += " align=\"%s\"" % align if valign: attr += " valign=\"%s\"" % valign if cssclass: attr += " class=\"%s\"" % cssclass css = "" if embeedcss: css = " style=\"border:none;color:#003399;font-size:16px;font-weight:normal;white-space:nowrap;padding:3px 10px;\"" if row == last_row: css = css[:-1] + "padding-bottom:5px;\"" out.write(" <th%s%s>\n" % (attr, css)) if th is not None: out.write(" %s\n" % htmlEncode(th.text)) out.write(" </th>\n") out.write(" </tr>\n") out.write(" </thead>\n <tbody>\n") rows = [row for row in self.rows if not self.getValue("header")] for r in range(len(rows)): row = rows[r] rowattr = "" cssclass = self.getValue("cssclass", row) if cssclass: rowattr += " class=\"%s\"" % cssclass out.write(" <tr%s>\n" % (rowattr)) i = 0 while i < len(row.cells): column = columns[i] td = row.cells[i] if isinstance(td, int): i += td continue colspan = self.getValue("colspan", td) rowspan = self.getValue("rowspan", td) align = self.getValue("align", td, row, column) valign = self.getValue("valign", td, row, column) color = self.getValue("color", td, row, column) bold = self.getValue("bold", td, row, column) italic = self.getValue("italic", td, row, column) style = "" attr = "" if color: style += "color:%s;" % color if bold: style += "font-weight: bold;" if italic: style += "font-style: italic;" if align and align != "left": attr += " align=\"%s\"" % align if valign and valign != "middle": attr += " valign=\"%s\"" % valign if colspan > 1: attr += " colspan=\"%s\"" % colspan if rowspan > 1: attr += " rowspan=\"%s\"" % rowspan for q in range(r+1, min(r+rowspan, len(rows))): rows[q].cells[i] = colspan if style: attr += " style=\"%s\"" % style css = "" if embeedcss: css = " style=\"border:none;border-bottom:1px solid #CCCCCC;color:#666699;padding:6px 8px;white-space:nowrap;\"" if r == 0: css = css[:-1] + "border-top:2px solid #6678B1;\"" out.write(" <td%s%s>\n" % (attr, css)) if td is not None: out.write(" %s\n" % htmlEncode(td.text)) out.write(" </td>\n") i += colspan out.write(" </tr>\n") out.write(" </tbody>\n</table>\n</div>\n") def htmlPrintHeader(out, title = None): if title: titletag = "<title>%s</title>\n" % htmlEncode([str(title)]) else: titletag = "" out.write("""<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=us-ascii"> %s<style type="text/css"> html, body {font-family: Lucida Console, Courier New, Courier;font-size: 16px;color:#3e4758;} .tbl{background:none repeat scroll 0 0 #FFFFFF;border-collapse:collapse;font-family:"Lucida Sans Unicode","Lucida Grande",Sans-Serif;font-size:14px;margin:20px;text-align:left;width:480px;margin-left: auto;margin-right: auto;white-space:nowrap;} .tbl span{display:block;white-space:nowrap;} .tbl thead tr:last-child th {padding-bottom:5px;} .tbl tbody tr:first-child td {border-top:3px solid #6678B1;} .tbl th{border:none;color:#003399;font-size:16px;font-weight:normal;white-space:nowrap;padding:3px 10px;} .tbl td{border:none;border-bottom:1px solid #CCCCCC;color:#666699;padding:6px 8px;white-space:nowrap;} .tbl tbody tr:hover td{color:#000099;} .tbl caption{font:italic 16px "Trebuchet MS",Verdana,Arial,Helvetica,sans-serif;padding:0 0 5px;text-align:right;white-space:normal;} .firstingroup {border-top:2px solid #6678B1;} </style> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript"> function abs(val) { return val < 0 ? -val : val } $(function(){ //generate filter rows $("div.tableFormatter table.tbl").each(function(tblIdx, tbl) { var head = $("thead", tbl) var filters = $("<tr></tr>") var hasAny = false $("tr:first th", head).each(function(colIdx, col) { col = $(col) var cell var id = "t" + tblIdx + "r" + colIdx if (col.hasClass("col_name")){ cell = $("<th><input id='" + id + "' name='" + id + "' type='text' style='width:100%%' class='filter_col_name' title='Regular expression for name filtering (&quot;resize.*640x480&quot; - resize tests on VGA resolution)'></input></th>") hasAny = true } else if (col.hasClass("col_rel")){ cell = $("<th><input id='" + id + "' name='" + id + "' type='text' style='width:100%%' class='filter_col_rel' title='Filter out lines with a x-factor of acceleration less than Nx'></input></th>") hasAny = true } else if (col.hasClass("col_cr")){ cell = $("<th><input id='" + id + "' name='" + id + "' type='text' style='width:100%%' class='filter_col_cr' title='Filter out lines with a percentage of acceleration less than N%%'></input></th>") hasAny = true } else cell = $("<th></th>") cell.appendTo(filters) }) if (hasAny){ $(tbl).wrap("<form id='form_t" + tblIdx + "' method='get' action=''></form>") $("<input it='test' type='submit' value='Apply Filters' style='margin-left:10px;'></input>") .appendTo($("th:last", filters.appendTo(head))) } }) //get filter values var vars = [] var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&') for(var i = 0; i < hashes.length; ++i) { hash = hashes[i].split('=') vars.push(decodeURIComponent(hash[0])) vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]); } //set filter values for(var i = 0; i < vars.length; ++i) $("#" + vars[i]).val(vars[vars[i]]) //apply filters $("div.tableFormatter table.tbl").each(function(tblIdx, tbl) { filters = $("input:text", tbl) var predicate = function(row) {return true;} var empty = true $.each($("input:text", tbl), function(i, flt) { flt = $(flt) var val = flt.val() var pred = predicate; if(val) { empty = false var colIdx = parseInt(flt.attr("id").slice(flt.attr("id").indexOf('r') + 1)) if(flt.hasClass("filter_col_name")) { var re = new RegExp(val); predicate = function(row) { if (re.exec($(row.get(colIdx)).text()) == null) return false return pred(row) } } else if(flt.hasClass("filter_col_rel")) { var percent = parseFloat(val) if (percent < 0) { predicate = function(row) { var val = parseFloat($(row.get(colIdx)).text()) if (!val || val >= 1 || val > 1+percent) return false return pred(row) } } else { predicate = function(row) { var val = parseFloat($(row.get(colIdx)).text()) if (!val || val < percent) return false return pred(row) } } } else if(flt.hasClass("filter_col_cr")) { var percent = parseFloat(val) predicate = function(row) { var val = parseFloat($(row.get(colIdx)).text()) if (!val || val < percent) return false return pred(row) } } } }); if (!empty){ $("tbody tr", tbl).each(function (i, tbl_row) { if(!predicate($("td", tbl_row))) $(tbl_row).remove() }) if($("tbody tr", tbl).length == 0) { $("<tr><td colspan='"+$("thead tr:first th", tbl).length+"'>No results matching your search criteria</td></tr>") .appendTo($("tbody", tbl)) } } }) }) </script> </head> <body> """ % titletag) def htmlPrintFooter(out): out.write("</body>\n</html>") def getStdoutFilename(): try: if os.name == "nt": import msvcrt, ctypes handle = msvcrt.get_osfhandle(sys.stdout.fileno()) size = ctypes.c_ulong(1024) nameBuffer = ctypes.create_string_buffer(size.value) ctypes.windll.kernel32.GetFinalPathNameByHandleA(handle, nameBuffer, size, 4) return nameBuffer.value else: return os.readlink('/proc/self/fd/1') except: return "" def detectHtmlOutputType(requestedType): if requestedType in ['txt', 'markdown']: return False elif requestedType in ["html", "moinwiki"]: return True else: if sys.stdout.isatty(): return False else: outname = getStdoutFilename() if outname: if outname.endswith(".htm") or outname.endswith(".html"): return True else: return False else: return False def getRelativeVal(test, test0, metric): if not test or not test0: return None val0 = test0.get(metric, "s") if not val0: return None val = test.get(metric, "s") if not val or val == 0: return None return float(val0)/val def getCycleReduction(test, test0, metric): if not test or not test0: return None val0 = test0.get(metric, "s") if not val0 or val0 == 0: return None val = test.get(metric, "s") if not val: return None return (1.0-float(val)/val0)*100 def getScore(test, test0, metric): if not test or not test0: return None m0 = float(test.get("gmean", None)) m1 = float(test0.get("gmean", None)) if m0 == 0 or m1 == 0: return None s0 = float(test.get("gstddev", None)) s1 = float(test0.get("gstddev", None)) s = math.sqrt(s0*s0 + s1*s1) m0 = math.log(m0) m1 = math.log(m1) if s == 0: return None return (m0-m1)/s metrix_table = \ { "name": ("Name of Test", lambda test,test0,units: str(test)), "samples": ("Number of\ncollected samples", lambda test,test0,units: test.get("samples", units)), "outliers": ("Number of\noutliers", lambda test,test0,units: test.get("outliers", units)), "gmean": ("Geometric mean", lambda test,test0,units: test.get("gmean", units)), "mean": ("Mean", lambda test,test0,units: test.get("mean", units)), "min": ("Min", lambda test,test0,units: test.get("min", units)), "median": ("Median", lambda test,test0,units: test.get("median", units)), "stddev": ("Standard deviation", lambda test,test0,units: test.get("stddev", units)), "gstddev": ("Standard deviation of Ln(time)", lambda test,test0,units: test.get("gstddev")), "gmean%": ("Geometric mean (relative)", lambda test,test0,units: getRelativeVal(test, test0, "gmean")), "mean%": ("Mean (relative)", lambda test,test0,units: getRelativeVal(test, test0, "mean")), "min%": ("Min (relative)", lambda test,test0,units: getRelativeVal(test, test0, "min")), "median%": ("Median (relative)", lambda test,test0,units: getRelativeVal(test, test0, "median")), "stddev%": ("Standard deviation (relative)", lambda test,test0,units: getRelativeVal(test, test0, "stddev")), "gstddev%": ("Standard deviation of Ln(time) (relative)", lambda test,test0,units: getRelativeVal(test, test0, "gstddev")), "gmean$": ("Geometric mean (cycle reduction)", lambda test,test0,units: getCycleReduction(test, test0, "gmean")), "mean$": ("Mean (cycle reduction)", lambda test,test0,units: getCycleReduction(test, test0, "mean")), "min$": ("Min (cycle reduction)", lambda test,test0,units: getCycleReduction(test, test0, "min")), "median$": ("Median (cycle reduction)", lambda test,test0,units: getCycleReduction(test, test0, "median")), "stddev$": ("Standard deviation (cycle reduction)", lambda test,test0,units: getCycleReduction(test, test0, "stddev")), "gstddev$": ("Standard deviation of Ln(time) (cycle reduction)", lambda test,test0,units: getCycleReduction(test, test0, "gstddev")), "score": ("SCORE", lambda test,test0,units: getScore(test, test0, "gstddev")), } def formatValue(val, metric, units = None): if val is None: return "-" if metric.endswith("%"): return "%.2f" % val if metric.endswith("$"): return "%.2f%%" % val if metric.endswith("S"): if val > 3.5: return "SLOWER" if val < -3.5: return "FASTER" if val > -1.5 and val < 1.5: return " " if val < 0: return "faster" if val > 0: return "slower" #return "%.4f" % val if units: return "%.3f %s" % (val, units) else: return "%.3f" % val if __name__ == "__main__": if len(sys.argv) < 2: print("Usage:\n", os.path.basename(sys.argv[0]), "<log_name>.xml") exit(0) parser = OptionParser() parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html', 'markdown' or 'auto' - default)", metavar="FMT", default="auto") parser.add_option("-m", "--metric", dest="metric", help="output metric", metavar="NAME", default="gmean") parser.add_option("-u", "--units", dest="units", help="units for output values (s, ms (default), us, ns or ticks)", metavar="UNITS", default="ms") (options, args) = parser.parse_args() options.generateHtml = detectHtmlOutputType(options.format) if options.metric not in metrix_table: options.metric = "gmean" #print options #print args # tbl = table() # tbl.newColumn("first", "qqqq", align = "left") # tbl.newColumn("second", "wwww\nz\nx\n") # tbl.newColumn("third", "wwasdas") # # tbl.newCell(0, "ccc111", align = "right") # tbl.newCell(1, "dddd1") # tbl.newCell(2, "8768756754") # tbl.newRow() # tbl.newCell(0, "1\n2\n3\n4\n5\n6\n7", align = "center", colspan = 2, rowspan = 2) # tbl.newCell(2, "xxx\nqqq", align = "center", colspan = 1, valign = "middle") # tbl.newRow() # tbl.newCell(2, "+", align = "center", colspan = 1, valign = "middle") # tbl.newRow() # tbl.newCell(0, "vcvvbasdsadassdasdasv", align = "right", colspan = 2) # tbl.newCell(2, "dddd1") # tbl.newRow() # tbl.newCell(0, "vcvvbv") # tbl.newCell(1, "3445324", align = "right") # tbl.newCell(2, None) # tbl.newCell(1, "0000") # if sys.stdout.isatty(): # tbl.consolePrintTable(sys.stdout) # else: # htmlPrintHeader(sys.stdout) # tbl.htmlPrintTable(sys.stdout) # htmlPrintFooter(sys.stdout) import testlog_parser if options.generateHtml: htmlPrintHeader(sys.stdout, "Tables demo") getter = metrix_table[options.metric][1] for arg in args: tests = testlog_parser.parseLogFile(arg) tbl = table(arg, format=options.format) tbl.newColumn("name", "Name of Test", align = "left") tbl.newColumn("value", metrix_table[options.metric][0], align = "center", bold = "true") for t in sorted(tests): tbl.newRow() tbl.newCell("name", str(t)) status = t.get("status") if status != "run": tbl.newCell("value", status) else: val = getter(t, None, options.units) if val: if options.metric.endswith("%"): tbl.newCell("value", "%.2f" % val, val) else: tbl.newCell("value", "%.3f %s" % (val, options.units), val) else: tbl.newCell("value", "-") if options.generateHtml: tbl.htmlPrintTable(sys.stdout) else: tbl.consolePrintTable(sys.stdout) if options.generateHtml: htmlPrintFooter(sys.stdout)
#!/usr/bin/env python import os import re import getpass from run_utils import Err, log, execute, isColorEnabled, hostos from run_suite import TestSuite def exe(program): return program + ".exe" if hostos == 'nt' else program class ApkInfo: def __init__(self): self.pkg_name = None self.pkg_target = None self.pkg_runner = None def forcePackage(self, package): if package: if package.startswith("."): self.pkg_target += package else: self.pkg_target = package class Tool: def __init__(self): self.cmd = [] def run(self, args=[], silent=False): cmd = self.cmd[:] cmd.extend(args) return execute(self.cmd + args, silent) class Adb(Tool): def __init__(self, sdk_dir): Tool.__init__(self) exe_path = os.path.join(sdk_dir, exe("platform-tools/adb")) if not os.path.isfile(exe_path) or not os.access(exe_path, os.X_OK): exe_path = None # fix adb tool location if not exe_path: exe_path = "adb" self.cmd = [exe_path] def init(self, serial): # remember current device serial. Needed if another device is connected while this script runs if not serial: serial = self.detectSerial() if serial: self.cmd.extend(["-s", serial]) def detectSerial(self): adb_res = self.run(["devices"], silent=True) # assume here that device name may consists of any characters except newline connected_devices = re.findall(r"^[^\n]+[ \t]+device\r?$", adb_res, re.MULTILINE) if not connected_devices: raise Err("Can not find Android device") elif len(connected_devices) != 1: raise Err("Too many (%s) devices are connected. Please specify single device using --serial option:\n\n%s", len(connected_devices), adb_res) else: return connected_devices[0].split("\t")[0] def getOSIdentifier(self): return "Android" + self.run(["shell", "getprop ro.build.version.release"], silent=True).strip() class Aapt(Tool): def __init__(self, sdk_dir): Tool.__init__(self) aapt_fn = exe("aapt") aapt = None for r, ds, fs in os.walk(os.path.join(sdk_dir, 'build-tools')): if aapt_fn in fs: aapt = os.path.join(r, aapt_fn) break if not aapt: raise Err("Can not find aapt tool: %s", aapt_fn) self.cmd = [aapt] def dump(self, exe): res = ApkInfo() output = self.run(["dump", "xmltree", exe, "AndroidManifest.xml"], silent=True) if not output: raise Err("Can not dump manifest from %s", exe) tags = re.split(r"[ ]+E: ", output) # get package name manifest_tag = [t for t in tags if t.startswith("manifest ")] if not manifest_tag: raise Err("Can not read package name from: %s", exe) res.pkg_name = re.search(r"^[ ]+A: package=\"(?P<pkg>.*?)\" \(Raw: \"(?P=pkg)\"\)\r?$", manifest_tag[0], flags=re.MULTILINE).group("pkg") # get test instrumentation info instrumentation_tag = [t for t in tags if t.startswith("instrumentation ")] if not instrumentation_tag: raise Err("Can not find instrumentation details in: %s", exe) res.pkg_runner = re.search(r"^[ ]+A: android:name\(0x[0-9a-f]{8}\)=\"(?P<runner>.*?)\" \(Raw: \"(?P=runner)\"\)\r?$", instrumentation_tag[0], flags=re.MULTILINE).group("runner") res.pkg_target = re.search(r"^[ ]+A: android:targetPackage\(0x[0-9a-f]{8}\)=\"(?P<pkg>.*?)\" \(Raw: \"(?P=pkg)\"\)\r?$", instrumentation_tag[0], flags=re.MULTILINE).group("pkg") if not res.pkg_name or not res.pkg_runner or not res.pkg_target: raise Err("Can not find instrumentation details in: %s", exe) return res class AndroidTestSuite(TestSuite): def __init__(self, options, cache, id, android_env={}): TestSuite.__init__(self, options, cache, id) sdk_dir = options.android_sdk or os.environ.get("ANDROID_SDK", False) or os.path.dirname(os.path.dirname(self.cache.android_executable)) log.debug("Detecting Android tools in directory: %s", sdk_dir) self.adb = Adb(sdk_dir) self.aapt = Aapt(sdk_dir) self.env = android_env def isTest(self, fullpath): if os.path.isfile(fullpath): if fullpath.endswith(".apk") or os.access(fullpath, os.X_OK): return True return False def getOS(self): return self.adb.getOSIdentifier() def checkPrerequisites(self): self.adb.init(self.options.serial) def runTest(self, module, path, logfile, workingDir, args=[]): args = args[:] exe = os.path.abspath(path) if exe.endswith(".apk"): info = self.aapt.dump(exe) if not info: raise Err("Can not read info from test package: %s", exe) info.forcePackage(self.options.package) self.adb.run(["uninstall", info.pkg_name]) output = self.adb.run(["install", exe], silent=True) if not (output and "Success" in output): raise Err("Can not install package: %s", exe) params = ["-e package %s" % info.pkg_target] ret = self.adb.run(["shell", "am instrument -w %s %s/%s" % (" ".join(params), info.pkg_name, info.pkg_runner)]) return None, ret else: device_dir = getpass.getuser().replace(" ", "") + "_" + self.options.mode + "/" if isColorEnabled(args): args.append("--gtest_color=yes") tempdir = "/data/local/tmp/" android_dir = tempdir + device_dir exename = os.path.basename(exe) android_exe = android_dir + exename self.adb.run(["push", exe, android_exe]) self.adb.run(["shell", "chmod 777 " + android_exe]) env_pieces = ["export %s=%s" % (a, b) for a, b in self.env.items()] pieces = ["cd %s" % android_dir, "./%s %s" % (exename, " ".join(args))] log.warning("Run: %s" % " && ".join(pieces)) ret = self.adb.run(["shell", " && ".join(env_pieces + pieces)]) # try get log hostlogpath = os.path.join(workingDir, logfile) self.adb.run(["pull", android_dir + logfile, hostlogpath]) # cleanup self.adb.run(["shell", "rm " + android_dir + logfile]) self.adb.run(["shell", "rm " + tempdir + "__opencv_temp.*"], silent=True) if os.path.isfile(hostlogpath): return hostlogpath, ret return None, ret if __name__ == "__main__": log.error("This is utility file, please execute run.py script")
#!/usr/bin/env python from __future__ import print_function import testlog_parser, sys, os, xml, glob, re from table_formatter import * from optparse import OptionParser from operator import itemgetter, attrgetter from summary import getSetName, alphanum_keyselector import re if __name__ == "__main__": usage = "%prog <log_name>.xml [...]" parser = OptionParser(usage = usage) parser.add_option("-o", "--output", dest = "format", help = "output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar = 'FMT', default = 'auto') parser.add_option("--failed-only", action = "store_true", dest = "failedOnly", help = "print only failed tests", default = False) (options, args) = parser.parse_args() options.generateHtml = detectHtmlOutputType(options.format) files = [] testsuits = [] # testsuit module, name, time, num, flag for failed tests overall_time = 0 seen = set() for arg in args: if ("*" in arg) or ("?" in arg): flist = [os.path.abspath(f) for f in glob.glob(arg)] flist = sorted(flist, key= lambda text: str(text).replace("M", "_")) files.extend([ x for x in flist if x not in seen and not seen.add(x)]) else: fname = os.path.abspath(arg) if fname not in seen and not seen.add(fname): files.append(fname) file = os.path.abspath(fname) if not os.path.isfile(file): sys.stderr.write("IOError reading \"" + file + "\" - " + str(err) + os.linesep) parser.print_help() exit(0) fname = os.path.basename(fname) find_module_name = re.search(r'([^_]*)', fname) module_name = find_module_name.group(0) test_sets = [] try: tests = testlog_parser.parseLogFile(file) if tests: test_sets.append((os.path.basename(file), tests)) except IOError as err: sys.stderr.write("IOError reading \"" + file + "\" - " + str(err) + os.linesep) except xml.parsers.expat.ExpatError as err: sys.stderr.write("ExpatError reading \"" + file + "\" - " + str(err) + os.linesep) if not test_sets: continue # find matches setsCount = len(test_sets) test_cases = {} name_extractor = lambda name: str(name) for i in range(setsCount): for case in test_sets[i][1]: name = name_extractor(case) if name not in test_cases: test_cases[name] = [None] * setsCount test_cases[name][i] = case prevGroupName = None suit_time = 0 suit_num = 0 fails_num = 0 for name in sorted(test_cases.iterkeys(), key=alphanum_keyselector): cases = test_cases[name] groupName = next(c for c in cases if c).shortName() if groupName != prevGroupName: if prevGroupName != None: suit_time = suit_time/60 #from seconds to minutes testsuits.append({'module': module_name, 'name': prevGroupName, \ 'time': suit_time, 'num': suit_num, 'failed': fails_num}) overall_time += suit_time suit_time = 0 suit_num = 0 fails_num = 0 prevGroupName = groupName for i in range(setsCount): case = cases[i] if not case is None: suit_num += 1 if case.get('status') == 'run': suit_time += case.get('time') if case.get('status') == 'failed': fails_num += 1 # last testsuit processing suit_time = suit_time/60 testsuits.append({'module': module_name, 'name': prevGroupName, \ 'time': suit_time, 'num': suit_num, 'failed': fails_num}) overall_time += suit_time if len(testsuits)==0: exit(0) tbl = table() rows = 0 if not options.failedOnly: tbl.newColumn('module', 'Module', align = 'left', cssclass = 'col_name') tbl.newColumn('name', 'Testsuit', align = 'left', cssclass = 'col_name') tbl.newColumn('time', 'Time (min)', align = 'center', cssclass = 'col_name') tbl.newColumn('num', 'Num of tests', align = 'center', cssclass = 'col_name') tbl.newColumn('failed', 'Failed', align = 'center', cssclass = 'col_name') # rows for suit in sorted(testsuits, key = lambda suit: suit['time'], reverse = True): tbl.newRow() tbl.newCell('module', suit['module']) tbl.newCell('name', suit['name']) tbl.newCell('time', formatValue(suit['time'], '', ''), suit['time']) tbl.newCell('num', suit['num']) if (suit['failed'] != 0): tbl.newCell('failed', suit['failed']) else: tbl.newCell('failed', ' ') rows += 1 else: tbl.newColumn('module', 'Module', align = 'left', cssclass = 'col_name') tbl.newColumn('name', 'Testsuit', align = 'left', cssclass = 'col_name') tbl.newColumn('failed', 'Failed', align = 'center', cssclass = 'col_name') # rows for suit in sorted(testsuits, key = lambda suit: suit['time'], reverse = True): if (suit['failed'] != 0): tbl.newRow() tbl.newCell('module', suit['module']) tbl.newCell('name', suit['name']) tbl.newCell('failed', suit['failed']) rows += 1 # output table if rows: if options.generateHtml: tbl.htmlPrintTable(sys.stdout) htmlPrintFooter(sys.stdout) else: if not options.failedOnly: print('\nOverall time: %.2f min\n' % overall_time) tbl.consolePrintTable(sys.stdout) print(2 * '\n')
#!/usr/bin/env python import os import re import sys from run_utils import Err, log, execute, getPlatformVersion, isColorEnabled, TempEnvDir from run_long import LONG_TESTS_DEBUG_VALGRIND, longTestFilter class TestSuite(object): def __init__(self, options, cache, id): self.options = options self.cache = cache self.nameprefix = "opencv_" + self.options.mode + "_" self.tests = self.cache.gatherTests(self.nameprefix + "*", self.isTest) self.id = id def getOS(self): return getPlatformVersion() or self.cache.getOS() def getLogName(self, app): return self.getAlias(app) + '_' + str(self.id) + '.xml' def listTests(self, short=False, main=False): if len(self.tests) == 0: raise Err("No tests found") for t in self.tests: if short: t = self.getAlias(t) if not main or self.cache.isMainModule(t): log.info("%s", t) def getAlias(self, fname): return sorted(self.getAliases(fname), key=len)[0] def getAliases(self, fname): def getCuts(fname, prefix): # filename w/o extension (opencv_test_core) noext = re.sub(r"\.(exe|apk)$", '', fname) # filename w/o prefix (core.exe) nopref = fname if fname.startswith(prefix): nopref = fname[len(prefix):] # filename w/o prefix and extension (core) noprefext = noext if noext.startswith(prefix): noprefext = noext[len(prefix):] return noext, nopref, noprefext # input is full path ('/home/.../bin/opencv_test_core') or 'java' res = [fname] fname = os.path.basename(fname) res.append(fname) # filename (opencv_test_core.exe) for s in getCuts(fname, self.nameprefix): res.append(s) if self.cache.build_type == "Debug" and "Visual Studio" in self.cache.cmake_generator: res.append(re.sub(r"d$", '', s)) # MSVC debug config, remove 'd' suffix log.debug("Aliases: %s", set(res)) return set(res) def getTest(self, name): # return stored test name by provided alias for t in self.tests: if name in self.getAliases(t): return t raise Err("Can not find test: %s", name) def getTestList(self, white, black): res = [t for t in white or self.tests if self.getAlias(t) not in black] if len(res) == 0: raise Err("No tests found") return set(res) def isTest(self, fullpath): if fullpath in ['java', 'python2', 'python3']: return self.options.mode == 'test' if not os.path.isfile(fullpath): return False if self.cache.getOS() == "nt" and not fullpath.endswith(".exe"): return False return os.access(fullpath, os.X_OK) def wrapCommand(self, module, cmd, env): if self.options.valgrind: res = ['valgrind'] supp = self.options.valgrind_supp or [] for f in supp: if os.path.isfile(f): res.append("--suppressions=%s" % f) else: print("WARNING: Valgrind suppression file is missing, SKIP: %s" % f) res.extend(self.options.valgrind_opt) has_gtest_filter = next((True for x in cmd if x.startswith('--gtest_filter=')), False) return res + cmd + ([longTestFilter(LONG_TESTS_DEBUG_VALGRIND, module)] if not has_gtest_filter else []) elif self.options.qemu: import shlex res = shlex.split(self.options.qemu) for (name, value) in [entry for entry in os.environ.items() if entry[0].startswith('OPENCV') and not entry[0] in env]: res += ['-E', '"{}={}"'.format(name, value)] for (name, value) in env.items(): res += ['-E', '"{}={}"'.format(name, value)] return res + ['--'] + cmd return cmd def tryCommand(self, cmd, workingDir): try: if 0 == execute(cmd, cwd=workingDir): return True except: pass return False def runTest(self, module, path, logfile, workingDir, args=[]): args = args[:] exe = os.path.abspath(path) if module == "java": cmd = [self.cache.ant_executable, "-Dopencv.build.type=%s" % self.cache.build_type] if self.options.package: cmd += ["-Dopencv.test.package=%s" % self.options.package] cmd += ["buildAndTest"] ret = execute(cmd, cwd=self.cache.java_test_dir) return None, ret elif module in ['python2', 'python3']: executable = os.getenv('OPENCV_PYTHON_BINARY', None) if executable is None or module == 'python{}'.format(sys.version_info[0]): executable = sys.executable if executable is None: executable = path if not self.tryCommand([executable, '--version'], workingDir): executable = 'python' cmd = [executable, self.cache.opencv_home + '/modules/python/test/test.py', '--repo', self.cache.opencv_home, '-v'] + args module_suffix = '' if 'Visual Studio' not in self.cache.cmake_generator else '/' + self.cache.build_type env = {} env['PYTHONPATH'] = self.cache.opencv_build + '/lib' + module_suffix + os.pathsep + os.getenv('PYTHONPATH', '') if self.cache.getOS() == 'nt': env['PATH'] = self.cache.opencv_build + '/bin' + module_suffix + os.pathsep + os.getenv('PATH', '') else: env['LD_LIBRARY_PATH'] = self.cache.opencv_build + '/bin' + os.pathsep + os.getenv('LD_LIBRARY_PATH', '') ret = execute(cmd, cwd=workingDir, env=env) return None, ret else: if isColorEnabled(args): args.append("--gtest_color=yes") env = {} if not self.options.valgrind and self.options.trace: env['OPENCV_TRACE'] = '1' env['OPENCV_TRACE_LOCATION'] = 'OpenCVTrace-{}'.format(self.getLogBaseName(exe)) env['OPENCV_TRACE_SYNC_OPENCL'] = '1' tempDir = TempEnvDir('OPENCV_TEMP_PATH', "__opencv_temp.") tempDir.init() cmd = self.wrapCommand(module, [exe] + args, env) log.warning("Run: %s" % " ".join(cmd)) ret = execute(cmd, cwd=workingDir, env=env) try: if not self.options.valgrind and self.options.trace and int(self.options.trace_dump) >= 0: import trace_profiler trace = trace_profiler.Trace(env['OPENCV_TRACE_LOCATION']+'.txt') trace.process() trace.dump(max_entries=int(self.options.trace_dump)) except: import traceback traceback.print_exc() pass tempDir.clean() hostlogpath = os.path.join(workingDir, logfile) if os.path.isfile(hostlogpath): return hostlogpath, ret return None, ret def runTests(self, tests, black, workingDir, args=[]): args = args[:] logs = [] test_list = self.getTestList(tests, black) if len(test_list) != 1: args = [a for a in args if not a.startswith("--gtest_output=")] ret = 0 for test in test_list: more_args = [] exe = self.getTest(test) if exe in ["java", "python2", "python3"]: logname = None else: userlog = [a for a in args if a.startswith("--gtest_output=")] if len(userlog) == 0: logname = self.getLogName(exe) more_args.append("--gtest_output=xml:" + logname) else: logname = userlog[0][userlog[0].find(":")+1:] log.debug("Running the test: %s (%s) ==> %s in %s", exe, args + more_args, logname, workingDir) if self.options.dry_run: logfile, r = None, 0 else: logfile, r = self.runTest(test, exe, logname, workingDir, args + more_args) log.debug("Test returned: %s ==> %s", r, logfile) if r != 0: ret = r if logfile: logs.append(os.path.relpath(logfile, workingDir)) return logs, ret if __name__ == "__main__": log.error("This is utility file, please execute run.py script")
#!/usr/bin/env python """ This script can generate XLS reports from OpenCV tests' XML output files. To use it, first, create a directory for each machine you ran tests on. Each such directory will become a sheet in the report. Put each XML file into the corresponding directory. Then, create your configuration file(s). You can have a global configuration file (specified with the -c option), and per-sheet configuration files, which must be called sheet.conf and placed in the directory corresponding to the sheet. The settings in the per-sheet configuration file will override those in the global configuration file, if both are present. A configuration file must consist of a Python dictionary. The following keys will be recognized: * 'comparisons': [{'from': string, 'to': string}] List of configurations to compare performance between. For each item, the sheet will have a column showing speedup from configuration named 'from' to configuration named "to". * 'configuration_matchers': [{'properties': {string: object}, 'name': string}] Instructions for matching test run property sets to configuration names. For each found XML file: 1) All attributes of the root element starting with the prefix 'cv_' are placed in a dictionary, with the cv_ prefix stripped and the cv_module_name element deleted. 2) The first matcher for which the XML's file property set contains the same keys with equal values as its 'properties' dictionary is searched for. A missing property can be matched by using None as the value. Corollary 1: you should place more specific matchers before less specific ones. Corollary 2: an empty 'properties' dictionary matches every property set. 3) If a matching matcher is found, its 'name' string is presumed to be the name of the configuration the XML file corresponds to. A warning is printed if two different property sets match to the same configuration name. 4) If a such a matcher isn't found, if --include-unmatched was specified, the configuration name is assumed to be the relative path from the sheet's directory to the XML file's containing directory. If the XML file isinstance directly inside the sheet's directory, the configuration name is instead a dump of all its properties. If --include-unmatched wasn't specified, the XML file is ignored and a warning is printed. * 'configurations': [string] List of names for compile-time and runtime configurations of OpenCV. Each item will correspond to a column of the sheet. * 'module_colors': {string: string} Mapping from module name to color name. In the sheet, cells containing module names from this mapping will be colored with the corresponding color. You can find the list of available colors here: <http://www.simplistix.co.uk/presentations/python-excel.pdf>. * 'sheet_name': string Name for the sheet. If this parameter is missing, the name of sheet's directory will be used. * 'sheet_properties': [(string, string)] List of arbitrary (key, value) pairs that somehow describe the sheet. Will be dumped into the first row of the sheet in string form. Note that all keys are optional, although to get useful results, you'll want to specify at least 'configurations' and 'configuration_matchers'. Finally, run the script. Use the --help option for usage information. """ from __future__ import division import ast import errno import fnmatch import logging import numbers import os, os.path import re from argparse import ArgumentParser from glob import glob from itertools import ifilter import xlwt from testlog_parser import parseLogFile re_image_size = re.compile(r'^ \d+ x \d+$', re.VERBOSE) re_data_type = re.compile(r'^ (?: 8 | 16 | 32 | 64 ) [USF] C [1234] $', re.VERBOSE) time_style = xlwt.easyxf(num_format_str='#0.00') no_time_style = xlwt.easyxf('pattern: pattern solid, fore_color gray25') failed_style = xlwt.easyxf('pattern: pattern solid, fore_color red') noimpl_style = xlwt.easyxf('pattern: pattern solid, fore_color orange') style_dict = {"failed": failed_style, "noimpl":noimpl_style} speedup_style = time_style good_speedup_style = xlwt.easyxf('font: color green', num_format_str='#0.00') bad_speedup_style = xlwt.easyxf('font: color red', num_format_str='#0.00') no_speedup_style = no_time_style error_speedup_style = xlwt.easyxf('pattern: pattern solid, fore_color orange') header_style = xlwt.easyxf('font: bold true; alignment: horizontal centre, vertical top, wrap True') subheader_style = xlwt.easyxf('alignment: horizontal centre, vertical top') class Collector(object): def __init__(self, config_match_func, include_unmatched): self.__config_cache = {} self.config_match_func = config_match_func self.include_unmatched = include_unmatched self.tests = {} self.extra_configurations = set() # Format a sorted sequence of pairs as if it was a dictionary. # We can't just use a dictionary instead, since we want to preserve the sorted order of the keys. @staticmethod def __format_config_cache_key(pairs, multiline=False): return ( ('{\n' if multiline else '{') + (',\n' if multiline else ', ').join( (' ' if multiline else '') + repr(k) + ': ' + repr(v) for (k, v) in pairs) + ('\n}\n' if multiline else '}') ) def collect_from(self, xml_path, default_configuration): run = parseLogFile(xml_path) module = run.properties['module_name'] properties = run.properties.copy() del properties['module_name'] props_key = tuple(sorted(properties.iteritems())) # dicts can't be keys if props_key in self.__config_cache: configuration = self.__config_cache[props_key] else: configuration = self.config_match_func(properties) if configuration is None: if self.include_unmatched: if default_configuration is not None: configuration = default_configuration else: configuration = Collector.__format_config_cache_key(props_key, multiline=True) self.extra_configurations.add(configuration) else: logging.warning('failed to match properties to a configuration: %s', Collector.__format_config_cache_key(props_key)) else: same_config_props = [it[0] for it in self.__config_cache.iteritems() if it[1] == configuration] if len(same_config_props) > 0: logging.warning('property set %s matches the same configuration %r as property set %s', Collector.__format_config_cache_key(props_key), configuration, Collector.__format_config_cache_key(same_config_props[0])) self.__config_cache[props_key] = configuration if configuration is None: return module_tests = self.tests.setdefault(module, {}) for test in run.tests: test_results = module_tests.setdefault((test.shortName(), test.param()), {}) new_result = test.get("gmean") if test.status == 'run' else test.status test_results[configuration] = min( test_results.get(configuration), new_result, key=lambda r: (1, r) if isinstance(r, numbers.Number) else (2,) if r is not None else (3,) ) # prefer lower result; prefer numbers to errors and errors to nothing def make_match_func(matchers): def match_func(properties): for matcher in matchers: if all(properties.get(name) == value for (name, value) in matcher['properties'].iteritems()): return matcher['name'] return None return match_func def main(): arg_parser = ArgumentParser(description='Build an XLS performance report.') arg_parser.add_argument('sheet_dirs', nargs='+', metavar='DIR', help='directory containing perf test logs') arg_parser.add_argument('-o', '--output', metavar='XLS', default='report.xls', help='name of output file') arg_parser.add_argument('-c', '--config', metavar='CONF', help='global configuration file') arg_parser.add_argument('--include-unmatched', action='store_true', help='include results from XML files that were not recognized by configuration matchers') arg_parser.add_argument('--show-times-per-pixel', action='store_true', help='for tests that have an image size parameter, show per-pixel time, as well as total time') args = arg_parser.parse_args() logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) if args.config is not None: with open(args.config) as global_conf_file: global_conf = ast.literal_eval(global_conf_file.read()) else: global_conf = {} wb = xlwt.Workbook() for sheet_path in args.sheet_dirs: try: with open(os.path.join(sheet_path, 'sheet.conf')) as sheet_conf_file: sheet_conf = ast.literal_eval(sheet_conf_file.read()) except IOError as ioe: if ioe.errno != errno.ENOENT: raise sheet_conf = {} logging.debug('no sheet.conf for %s', sheet_path) sheet_conf = dict(global_conf.items() + sheet_conf.items()) config_names = sheet_conf.get('configurations', []) config_matchers = sheet_conf.get('configuration_matchers', []) collector = Collector(make_match_func(config_matchers), args.include_unmatched) for root, _, filenames in os.walk(sheet_path): logging.info('looking in %s', root) for filename in fnmatch.filter(filenames, '*.xml'): if os.path.normpath(sheet_path) == os.path.normpath(root): default_conf = None else: default_conf = os.path.relpath(root, sheet_path) collector.collect_from(os.path.join(root, filename), default_conf) config_names.extend(sorted(collector.extra_configurations - set(config_names))) sheet = wb.add_sheet(sheet_conf.get('sheet_name', os.path.basename(os.path.abspath(sheet_path)))) sheet_properties = sheet_conf.get('sheet_properties', []) sheet.write(0, 0, 'Properties:') sheet.write(0, 1, 'N/A' if len(sheet_properties) == 0 else ' '.join(str(k) + '=' + repr(v) for (k, v) in sheet_properties)) sheet.row(2).height = 800 sheet.panes_frozen = True sheet.remove_splits = True sheet_comparisons = sheet_conf.get('comparisons', []) row = 2 col = 0 for (w, caption) in [ (2500, 'Module'), (10000, 'Test'), (2000, 'Image\nwidth'), (2000, 'Image\nheight'), (2000, 'Data\ntype'), (7500, 'Other parameters')]: sheet.col(col).width = w if args.show_times_per_pixel: sheet.write_merge(row, row + 1, col, col, caption, header_style) else: sheet.write(row, col, caption, header_style) col += 1 for config_name in config_names: if args.show_times_per_pixel: sheet.col(col).width = 3000 sheet.col(col + 1).width = 3000 sheet.write_merge(row, row, col, col + 1, config_name, header_style) sheet.write(row + 1, col, 'total, ms', subheader_style) sheet.write(row + 1, col + 1, 'per pixel, ns', subheader_style) col += 2 else: sheet.col(col).width = 4000 sheet.write(row, col, config_name, header_style) col += 1 col += 1 # blank column between configurations and comparisons for comp in sheet_comparisons: sheet.col(col).width = 4000 caption = comp['to'] + '\nvs\n' + comp['from'] if args.show_times_per_pixel: sheet.write_merge(row, row + 1, col, col, caption, header_style) else: sheet.write(row, col, caption, header_style) col += 1 row += 2 if args.show_times_per_pixel else 1 sheet.horz_split_pos = row sheet.horz_split_first_visible = row module_colors = sheet_conf.get('module_colors', {}) module_styles = {module: xlwt.easyxf('pattern: pattern solid, fore_color {}'.format(color)) for module, color in module_colors.iteritems()} for module, tests in sorted(collector.tests.iteritems()): for ((test, param), configs) in sorted(tests.iteritems()): sheet.write(row, 0, module, module_styles.get(module, xlwt.Style.default_style)) sheet.write(row, 1, test) param_list = param[1:-1].split(', ') if param.startswith('(') and param.endswith(')') else [param] image_size = next(ifilter(re_image_size.match, param_list), None) if image_size is not None: (image_width, image_height) = map(int, image_size.split('x', 1)) sheet.write(row, 2, image_width) sheet.write(row, 3, image_height) del param_list[param_list.index(image_size)] data_type = next(ifilter(re_data_type.match, param_list), None) if data_type is not None: sheet.write(row, 4, data_type) del param_list[param_list.index(data_type)] sheet.row(row).write(5, ' | '.join(param_list)) col = 6 for c in config_names: if c in configs: sheet.write(row, col, configs[c], style_dict.get(configs[c], time_style)) else: sheet.write(row, col, None, no_time_style) col += 1 if args.show_times_per_pixel: sheet.write(row, col, xlwt.Formula('{0} * 1000000 / ({1} * {2})'.format( xlwt.Utils.rowcol_to_cell(row, col - 1), xlwt.Utils.rowcol_to_cell(row, 2), xlwt.Utils.rowcol_to_cell(row, 3) )), time_style ) col += 1 col += 1 # blank column for comp in sheet_comparisons: cmp_from = configs.get(comp["from"]) cmp_to = configs.get(comp["to"]) if isinstance(cmp_from, numbers.Number) and isinstance(cmp_to, numbers.Number): try: speedup = cmp_from / cmp_to sheet.write(row, col, speedup, good_speedup_style if speedup > 1.1 else bad_speedup_style if speedup < 0.9 else speedup_style) except ArithmeticError as e: sheet.write(row, col, None, error_speedup_style) else: sheet.write(row, col, None, no_speedup_style) col += 1 row += 1 if row % 1000 == 0: sheet.flush_row_data() wb.save(args.output) if __name__ == '__main__': main()
from __future__ import print_function import os import sys import csv from pprint import pprint from collections import deque try: long # Python 2 except NameError: long = int # Python 3 # trace.hpp REGION_FLAG_IMPL_MASK = 15 << 16 REGION_FLAG_IMPL_IPP = 1 << 16 REGION_FLAG_IMPL_OPENCL = 2 << 16 DEBUG = False if DEBUG: dprint = print dpprint = pprint else: def dprint(args, **kwargs): pass def dpprint(args, **kwargs): pass def tryNum(s): if s.startswith('0x'): try: return int(s, 16) except ValueError: pass try: return int(s) except ValueError: pass if sys.version_info[0] < 3: try: return long(s) except ValueError: pass return s def formatTimestamp(t): return "%.3f" % (t * 1e-6) try: from statistics import median except ImportError: def median(lst): sortedLst = sorted(lst) lstLen = len(lst) index = (lstLen - 1) // 2 if (lstLen % 2): return sortedLst[index] else: return (sortedLst[index] + sortedLst[index + 1]) * 0.5 def getCXXFunctionName(spec): def dropParams(spec): pos = len(spec) - 1 depth = 0 while pos >= 0: if spec[pos] == ')': depth = depth + 1 elif spec[pos] == '(': depth = depth - 1 if depth == 0: if pos == 0 or spec[pos - 1] in ['#', ':']: res = dropParams(spec[pos+1:-1]) return (spec[:pos] + res[0], res[1]) return (spec[:pos], spec[pos:]) pos = pos - 1 return (spec, '') def extractName(spec): pos = len(spec) - 1 inName = False while pos >= 0: if spec[pos] == ' ': if inName: return spec[pos+1:] elif spec[pos].isalnum(): inName = True pos = pos - 1 return spec if spec.startswith('IPP') or spec.startswith('OpenCL'): prefix_size = len('IPP') if spec.startswith('IPP') else len('OpenCL') prefix = spec[:prefix_size] if prefix_size < len(spec) and spec[prefix_size] in ['#', ':']: prefix = prefix + spec[prefix_size] prefix_size = prefix_size + 1 begin = prefix_size while begin < len(spec): if spec[begin].isalnum() or spec[begin] in ['_', ':']: break begin = begin + 1 if begin == len(spec): return spec end = begin while end < len(spec): if not (spec[end].isalnum() or spec[end] in ['_', ':']): break end = end + 1 return prefix + spec[begin:end] spec = spec.replace(') const', ')') # const methods (ret_type_name, params) = dropParams(spec) name = extractName(ret_type_name) if 'operator' in name: return name + params if name.startswith('&'): return name[1:] return name stack_size = 10 class Trace: def __init__(self, filename=None): self.tasks = {} self.tasks_list = [] self.locations = {} self.threads_stack = {} self.pending_files = deque() if filename: self.load(filename) class TraceTask: def __init__(self, threadID, taskID, locationID, beginTimestamp): self.threadID = threadID self.taskID = taskID self.locationID = locationID self.beginTimestamp = beginTimestamp self.endTimestamp = None self.parentTaskID = None self.parentThreadID = None self.childTask = [] self.selfTimeIPP = 0 self.selfTimeOpenCL = 0 self.totalTimeIPP = 0 self.totalTimeOpenCL = 0 def __repr__(self): return "TID={} ID={} loc={} parent={}:{} begin={} end={} IPP={}/{} OpenCL={}/{}".format( self.threadID, self.taskID, self.locationID, self.parentThreadID, self.parentTaskID, self.beginTimestamp, self.endTimestamp, self.totalTimeIPP, self.selfTimeIPP, self.totalTimeOpenCL, self.selfTimeOpenCL) class TraceLocation: def __init__(self, locationID, filename, line, name, flags): self.locationID = locationID self.filename = os.path.split(filename)[1] self.line = line self.name = getCXXFunctionName(name) self.flags = flags def __str__(self): return "{}#{}:{}".format(self.name, self.filename, self.line) def __repr__(self): return "ID={} {}:{}:{}".format(self.locationID, self.filename, self.line, self.name) def parse_file(self, filename): dprint("Process file: '{}'".format(filename)) with open(filename) as infile: for line in infile: line = str(line).strip() if line[0] == "#": if line.startswith("#thread file:"): name = str(line.split(':', 1)[1]).strip() self.pending_files.append(os.path.join(os.path.split(filename)[0], name)) continue self.parse_line(line) def parse_line(self, line): opts = line.split(',') dpprint(opts) if opts[0] == 'l': opts = list(csv.reader([line]))[0] # process quote more locationID = int(opts[1]) filename = str(opts[2]) line = int(opts[3]) name = opts[4] flags = tryNum(opts[5]) self.locations[locationID] = self.TraceLocation(locationID, filename, line, name, flags) return extra_opts = {} for e in opts[5:]: if not '=' in e: continue (k, v) = e.split('=') extra_opts[k] = tryNum(v) if extra_opts: dpprint(extra_opts) threadID = None taskID = None locationID = None ts = None if opts[0] in ['b', 'e']: threadID = int(opts[1]) taskID = int(opts[4]) locationID = int(opts[3]) ts = tryNum(opts[2]) thread_stack = None currentTask = (None, None) if threadID is not None: if not threadID in self.threads_stack: thread_stack = deque() self.threads_stack[threadID] = thread_stack else: thread_stack = self.threads_stack[threadID] currentTask = None if not thread_stack else thread_stack[-1] t = (threadID, taskID) if opts[0] == 'b': assert not t in self.tasks, "Duplicate task: " + str(t) + repr(self.tasks[t]) task = self.TraceTask(threadID, taskID, locationID, ts) self.tasks[t] = task self.tasks_list.append(task) thread_stack.append((threadID, taskID)) if currentTask: task.parentThreadID = currentTask[0] task.parentTaskID = currentTask[1] if 'parentThread' in extra_opts: task.parentThreadID = extra_opts['parentThread'] if 'parent' in extra_opts: task.parentTaskID = extra_opts['parent'] if opts[0] == 'e': task = self.tasks[t] task.endTimestamp = ts if 'tIPP' in extra_opts: task.selfTimeIPP = extra_opts['tIPP'] if 'tOCL' in extra_opts: task.selfTimeOpenCL = extra_opts['tOCL'] thread_stack.pop() def load(self, filename): self.pending_files.append(filename) if DEBUG: with open(filename, 'r') as f: print(f.read(), end='') while self.pending_files: self.parse_file(self.pending_files.pop()) def getParentTask(self, task): return self.tasks.get((task.parentThreadID, task.parentTaskID), None) def process(self): self.tasks_list.sort(key=lambda x: x.beginTimestamp) parallel_for_location = None for (id, l) in self.locations.items(): if l.name == 'parallel_for': parallel_for_location = l.locationID break for task in self.tasks_list: try: task.duration = task.endTimestamp - task.beginTimestamp task.selfDuration = task.duration except: task.duration = None task.selfDuration = None task.totalTimeIPP = task.selfTimeIPP task.totalTimeOpenCL = task.selfTimeOpenCL dpprint(self.tasks) dprint("Calculate total times") for task in self.tasks_list: parentTask = self.getParentTask(task) if parentTask: parentTask.selfDuration = parentTask.selfDuration - task.duration parentTask.childTask.append(task) timeIPP = task.selfTimeIPP timeOpenCL = task.selfTimeOpenCL while parentTask: if parentTask.locationID == parallel_for_location: # TODO parallel_for break parentLocation = self.locations[parentTask.locationID] if (parentLocation.flags & REGION_FLAG_IMPL_MASK) == REGION_FLAG_IMPL_IPP: parentTask.selfTimeIPP = parentTask.selfTimeIPP - timeIPP timeIPP = 0 else: parentTask.totalTimeIPP = parentTask.totalTimeIPP + timeIPP if (parentLocation.flags & REGION_FLAG_IMPL_MASK) == REGION_FLAG_IMPL_OPENCL: parentTask.selfTimeOpenCL = parentTask.selfTimeOpenCL - timeOpenCL timeOpenCL = 0 else: parentTask.totalTimeOpenCL = parentTask.totalTimeOpenCL + timeOpenCL parentTask = self.getParentTask(parentTask) dpprint(self.tasks) dprint("Calculate total times (parallel_for)") for task in self.tasks_list: if task.locationID == parallel_for_location: task.selfDuration = 0 childDuration = sum([t.duration for t in task.childTask]) if task.duration == 0 or childDuration == 0: continue timeCoef = task.duration / float(childDuration) childTimeIPP = sum([t.totalTimeIPP for t in task.childTask]) childTimeOpenCL = sum([t.totalTimeOpenCL for t in task.childTask]) if childTimeIPP == 0 and childTimeOpenCL == 0: continue timeIPP = childTimeIPP * timeCoef timeOpenCL = childTimeOpenCL * timeCoef parentTask = task while parentTask: parentLocation = self.locations[parentTask.locationID] if (parentLocation.flags & REGION_FLAG_IMPL_MASK) == REGION_FLAG_IMPL_IPP: parentTask.selfTimeIPP = parentTask.selfTimeIPP - timeIPP timeIPP = 0 else: parentTask.totalTimeIPP = parentTask.totalTimeIPP + timeIPP if (parentLocation.flags & REGION_FLAG_IMPL_MASK) == REGION_FLAG_IMPL_OPENCL: parentTask.selfTimeOpenCL = parentTask.selfTimeOpenCL - timeOpenCL timeOpenCL = 0 else: parentTask.totalTimeOpenCL = parentTask.totalTimeOpenCL + timeOpenCL parentTask = self.getParentTask(parentTask) dpprint(self.tasks) dprint("Done") def dump(self, max_entries): assert isinstance(max_entries, int) class CallInfo(): def __init__(self, callID): self.callID = callID self.totalTimes = [] self.selfTimes = [] self.threads = set() self.selfTimesIPP = [] self.selfTimesOpenCL = [] self.totalTimesIPP = [] self.totalTimesOpenCL = [] calls = {} for currentTask in self.tasks_list: task = currentTask callID = [] for i in range(stack_size): callID.append(task.locationID) task = self.getParentTask(task) if not task: break callID = tuple(callID) if not callID in calls: call = CallInfo(callID) calls[callID] = call else: call = calls[callID] call.totalTimes.append(currentTask.duration) call.selfTimes.append(currentTask.selfDuration) call.threads.add(currentTask.threadID) call.selfTimesIPP.append(currentTask.selfTimeIPP) call.selfTimesOpenCL.append(currentTask.selfTimeOpenCL) call.totalTimesIPP.append(currentTask.totalTimeIPP) call.totalTimesOpenCL.append(currentTask.totalTimeOpenCL) dpprint(self.tasks) dpprint(self.locations) dpprint(calls) calls_self_sum = {k: sum(v.selfTimes) for (k, v) in calls.items()} calls_total_sum = {k: sum(v.totalTimes) for (k, v) in calls.items()} calls_median = {k: median(v.selfTimes) for (k, v) in calls.items()} calls_sorted = sorted(calls.keys(), key=lambda x: calls_self_sum[x], reverse=True) calls_self_sum_IPP = {k: sum(v.selfTimesIPP) for (k, v) in calls.items()} calls_total_sum_IPP = {k: sum(v.totalTimesIPP) for (k, v) in calls.items()} calls_self_sum_OpenCL = {k: sum(v.selfTimesOpenCL) for (k, v) in calls.items()} calls_total_sum_OpenCL = {k: sum(v.totalTimesOpenCL) for (k, v) in calls.items()} if max_entries > 0 and len(calls_sorted) > max_entries: calls_sorted = calls_sorted[:max_entries] def formatPercents(p): if p is not None: return "{:>3d}".format(int(p*100)) return '' name_width = 70 timestamp_width = 12 def fmtTS(): return '{:>' + str(timestamp_width) + '}' fmt = "{:>3} {:<"+str(name_width)+"} {:>8} {:>3}"+((' '+fmtTS())*5)+((' '+fmtTS()+' {:>3}')*2) fmt2 = "{:>3} {:<"+str(name_width)+"} {:>8} {:>3}"+((' '+fmtTS())*5)+((' '+fmtTS()+' {:>3}')*2) print(fmt.format("ID", "name", "count", "thr", "min", "max", "median", "avg", "*self*", "IPP", "%", "OpenCL", "%")) print(fmt2.format("", "", "", "", "t-min", "t-max", "t-median", "t-avg", "total", "t-IPP", "%", "t-OpenCL", "%")) for (index, callID) in enumerate(calls_sorted): call_self_times = calls[callID].selfTimes loc0 = self.locations[callID[0]] loc_array = [] # [str(callID)] for (i, l) in enumerate(callID): loc = self.locations[l] loc_array.append(loc.name if i > 0 else str(loc)) loc_str = '|'.join(loc_array) if len(loc_str) > name_width: loc_str = loc_str[:name_width-3]+'...' print(fmt.format(index + 1, loc_str, len(call_self_times), len(calls[callID].threads), formatTimestamp(min(call_self_times)), formatTimestamp(max(call_self_times)), formatTimestamp(calls_median[callID]), formatTimestamp(sum(call_self_times)/float(len(call_self_times))), formatTimestamp(sum(call_self_times)), formatTimestamp(calls_self_sum_IPP[callID]), formatPercents(calls_self_sum_IPP[callID] / float(calls_self_sum[callID])) if calls_self_sum[callID] > 0 else formatPercents(None), formatTimestamp(calls_self_sum_OpenCL[callID]), formatPercents(calls_self_sum_OpenCL[callID] / float(calls_self_sum[callID])) if calls_self_sum[callID] > 0 else formatPercents(None), )) call_total_times = calls[callID].totalTimes print(fmt2.format("", "", "", "", formatTimestamp(min(call_total_times)), formatTimestamp(max(call_total_times)), formatTimestamp(median(call_total_times)), formatTimestamp(sum(call_total_times)/float(len(call_total_times))), formatTimestamp(sum(call_total_times)), formatTimestamp(calls_total_sum_IPP[callID]), formatPercents(calls_total_sum_IPP[callID] / float(calls_total_sum[callID])) if calls_total_sum[callID] > 0 else formatPercents(None), formatTimestamp(calls_total_sum_OpenCL[callID]), formatPercents(calls_total_sum_OpenCL[callID] / float(calls_total_sum[callID])) if calls_total_sum[callID] > 0 else formatPercents(None), )) print() if __name__ == "__main__": tracefile = sys.argv[1] if len(sys.argv) > 1 else 'OpenCVTrace.txt' count = int(sys.argv[2]) if len(sys.argv) > 2 else 10 trace = Trace(tracefile) trace.process() trace.dump(max_entries = count) print("OK")
#!/usr/bin/env python import testlog_parser, sys, os, xml, re, glob from table_formatter import * from optparse import OptionParser if __name__ == "__main__": parser = OptionParser() parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar="FMT", default="auto") parser.add_option("-u", "--units", dest="units", help="units for output values (s, ms (default), us, ns or ticks)", metavar="UNITS", default="ms") parser.add_option("-c", "--columns", dest="columns", help="comma-separated list of columns to show", metavar="COLS", default="") parser.add_option("-f", "--filter", dest="filter", help="regex to filter tests", metavar="REGEX", default=None) parser.add_option("", "--show-all", action="store_true", dest="showall", default=False, help="also include empty and \"notrun\" lines") (options, args) = parser.parse_args() if len(args) < 1: print >> sys.stderr, "Usage:\n", os.path.basename(sys.argv[0]), "<log_name1>.xml" exit(0) options.generateHtml = detectHtmlOutputType(options.format) # expand wildcards and filter duplicates files = [] files1 = [] for arg in args: if ("*" in arg) or ("?" in arg): files1.extend([os.path.abspath(f) for f in glob.glob(arg)]) else: files.append(os.path.abspath(arg)) seen = set() files = [ x for x in files if x not in seen and not seen.add(x)] files.extend((set(files1) - set(files))) args = files # load test data tests = [] files = [] for arg in set(args): try: cases = testlog_parser.parseLogFile(arg) if cases: files.append(os.path.basename(arg)) tests.extend(cases) except: pass if options.filter: expr = re.compile(options.filter) tests = [t for t in tests if expr.search(str(t))] tbl = table(", ".join(files)) if options.columns: metrics = [s.strip() for s in options.columns.split(",")] metrics = [m for m in metrics if m and not m.endswith("%") and m in metrix_table] else: metrics = None if not metrics: metrics = ["name", "samples", "outliers", "min", "median", "gmean", "mean", "stddev"] if "name" not in metrics: metrics.insert(0, "name") for m in metrics: if m == "name": tbl.newColumn(m, metrix_table[m][0]) else: tbl.newColumn(m, metrix_table[m][0], align = "center") needNewRow = True for case in sorted(tests, key=lambda x: str(x)): if needNewRow: tbl.newRow() if not options.showall: needNewRow = False status = case.get("status") if status != "run": if status != "notrun": needNewRow = True for m in metrics: if m == "name": tbl.newCell(m, str(case)) else: tbl.newCell(m, status, color = "red") else: needNewRow = True for m in metrics: val = metrix_table[m][1](case, None, options.units) if isinstance(val, float): tbl.newCell(m, "%.2f %s" % (val, options.units), val) else: tbl.newCell(m, val, val) if not needNewRow: tbl.trimLastRow() # output table if options.generateHtml: if options.format == "moinwiki": tbl.htmlPrintTable(sys.stdout, True) else: htmlPrintHeader(sys.stdout, "Report %s tests from %s" % (len(tests), ", ".join(files))) tbl.htmlPrintTable(sys.stdout) htmlPrintFooter(sys.stdout) else: tbl.consolePrintTable(sys.stdout)
#!/usr/bin/env python # Python 2/3 compatibility from __future__ import print_function import numpy as np import cv2 as cv from tests_common import NewOpenCVTests class solvepnp_test(NewOpenCVTests): def test_regression_16040(self): obj_points = np.array([[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]], dtype=np.float32) img_points = np.array( [[700, 400], [700, 600], [900, 600], [900, 400]], dtype=np.float32 ) cameraMatrix = np.array( [[712.0634, 0, 800], [0, 712.540, 500], [0, 0, 1]], dtype=np.float32 ) distCoeffs = np.array([[0, 0, 0, 0]], dtype=np.float32) r = np.array([], dtype=np.float32) x, r, t, e = cv.solvePnPGeneric( obj_points, img_points, cameraMatrix, distCoeffs, reprojectionError=r ) def test_regression_16040_2(self): obj_points = np.array([[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]], dtype=np.float32) img_points = np.array( [[[700, 400], [700, 600], [900, 600], [900, 400]]], dtype=np.float32 ) cameraMatrix = np.array( [[712.0634, 0, 800], [0, 712.540, 500], [0, 0, 1]], dtype=np.float32 ) distCoeffs = np.array([[0, 0, 0, 0]], dtype=np.float32) r = np.array([], dtype=np.float32) x, r, t, e = cv.solvePnPGeneric( obj_points, img_points, cameraMatrix, distCoeffs, reprojectionError=r ) def test_regression_16049(self): obj_points = np.array([[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]], dtype=np.float32) img_points = np.array( [[[700, 400], [700, 600], [900, 600], [900, 400]]], dtype=np.float32 ) cameraMatrix = np.array( [[712.0634, 0, 800], [0, 712.540, 500], [0, 0, 1]], dtype=np.float32 ) distCoeffs = np.array([[0, 0, 0, 0]], dtype=np.float32) x, r, t, e = cv.solvePnPGeneric( obj_points, img_points, cameraMatrix, distCoeffs ) if e is None: # noArray() is supported, see https://github.com/opencv/opencv/issues/16049 pass else: eDump = cv.utils.dumpInputArray(e) self.assertEqual(eDump, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=1 dims(-1)=2 size(-1)=1x1 type(-1)=CV_32FC1") if __name__ == '__main__': NewOpenCVTests.bootstrap()
#!/usr/bin/env python ''' camera calibration for distorted images with chess board samples reads distorted images, calculates the calibration and write undistorted images ''' # Python 2/3 compatibility from __future__ import print_function import numpy as np import cv2 as cv from tests_common import NewOpenCVTests class calibration_test(NewOpenCVTests): def test_calibration(self): img_names = [] for i in range(1, 15): if i < 10: img_names.append('samples/data/left0{}.jpg'.format(str(i))) elif i != 10: img_names.append('samples/data/left{}.jpg'.format(str(i))) square_size = 1.0 pattern_size = (9, 6) pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32) pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2) pattern_points *= square_size obj_points = [] img_points = [] h, w = 0, 0 for fn in img_names: img = self.get_sample(fn, 0) if img is None: continue h, w = img.shape[:2] found, corners = cv.findChessboardCorners(img, pattern_size) if found: term = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_COUNT, 30, 0.1) cv.cornerSubPix(img, corners, (5, 5), (-1, -1), term) if not found: continue img_points.append(corners.reshape(-1, 2)) obj_points.append(pattern_points) # calculate camera distortion rms, camera_matrix, dist_coefs, _rvecs, _tvecs = cv.calibrateCamera(obj_points, img_points, (w, h), None, None, flags = 0) eps = 0.01 normCamEps = 10.0 normDistEps = 0.05 cameraMatrixTest = [[ 532.80992189, 0., 342.4952186 ], [ 0., 532.93346422, 233.8879292 ], [ 0., 0., 1. ]] distCoeffsTest = [ -2.81325576e-01, 2.91130406e-02, 1.21234330e-03, -1.40825372e-04, 1.54865844e-01] self.assertLess(abs(rms - 0.196334638034), eps) self.assertLess(cv.norm(camera_matrix - cameraMatrixTest, cv.NORM_L1), normCamEps) self.assertLess(cv.norm(dist_coefs - distCoeffsTest, cv.NORM_L1), normDistEps) if __name__ == '__main__': NewOpenCVTests.bootstrap()
#!/usr/bin/python # Copyright 2016 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Convert gclient's DEPS file to repo's manifest xml file.""" from __future__ import print_function import argparse import os import sys REMOTES = { 'chromium': 'https://chromium.googlesource.com/', 'github': 'https://github.com/', } REVIEWS = { 'chromium': 'https://chromium-review.googlesource.com', } MANIFEST_HEAD = """<?xml version='1.0' encoding='UTF-8'?> <!-- AUTOGENERATED BY %(prog)s; DO NOT EDIT --> <manifest> <default revision='refs/heads/master' remote='chromium' sync-c='true' sync-j='8' /> """ MANIFEST_REMOTE = """ <remote name='%(name)s' fetch='%(fetch)s' review='%(review)s' /> """ MANIFEST_PROJECT = """ <project path='%(path)s' name='%(name)s' revision='%(revision)s' remote='%(remote)s' /> """ MANIFEST_TAIL = """ </manifest> """ def ConvertDepsToManifest(deps, manifest): """Convert the |deps| file to the |manifest|.""" # Load the DEPS file data. ctx = {} execfile(deps, ctx) new_contents = '' # Write out the common header. data = { 'prog': os.path.basename(__file__), } new_contents += MANIFEST_HEAD % data # Write out the <remote> sections. for name, fetch in REMOTES.items(): data = { 'name': name, 'fetch': fetch, 'review': REVIEWS.get(name, ''), } new_contents += MANIFEST_REMOTE % data # Write out the main repo itself. data = { 'path': 'src', 'name': 'breakpad/breakpad', 'revision': 'refs/heads/master', 'remote': 'chromium', } new_contents += MANIFEST_PROJECT % data # Write out the <project> sections. for path, url in ctx['deps'].items(): for name, fetch in REMOTES.items(): if url.startswith(fetch): remote = name break else: raise ValueError('Unknown DEPS remote: %s: %s' % (path, url)) # The DEPS url will look like: # https://chromium.googlesource.com/external/gyp/@e8ab0833a42691cd2 remote_path, rev = url.split('@') remote_path = remote_path[len(fetch):] # If it's not a revision, assume it's a tag. Repo wants full ref names. if len(rev) != 40: rev = 'refs/tags/%s' % rev data = { 'path': path, 'name': remote_path, 'revision': rev, 'remote': remote, } new_contents += MANIFEST_PROJECT % data # Write out the common footer. new_contents += MANIFEST_TAIL # See if the manifest has actually changed contents to avoid thrashing. try: old_contents = open(manifest).read() except IOError: # In case the file doesn't exist yet. old_contents = '' if old_contents != new_contents: print('Updating %s due to changed %s' % (manifest, deps)) with open(manifest, 'w') as fp: fp.write(new_contents) def GetParser(): """Return a CLI parser.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('deps', help='The DEPS file to convert') parser.add_argument('manifest', help='The manifest xml to generate') return parser def main(argv): """The main func!""" parser = GetParser() opts = parser.parse_args(argv) ConvertDepsToManifest(opts.deps, opts.manifest) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Normalizes and de-duplicates paths within Breakpad symbol files. When using DWARF for storing debug symbols, some file information will be stored relative to the current working directory of the current compilation unit, and may be further relativized based upon how the file was #included. This helper can be used to parse the Breakpad symbol file generated from such DWARF files and normalize and de-duplicate the FILE records found within, updating any references to the FILE records in the other record types. """ import macpath import ntpath import optparse import os import posixpath import sys class BreakpadParseError(Exception): """Unsupported Breakpad symbol record exception class.""" pass class SymbolFileParser(object): """Parser for Breakpad symbol files. The format of these files is documented at https://chromium.googlesource.com/breakpad/breakpad/+/master/docs/symbol_files.md """ def __init__(self, input_stream, output_stream, ignored_prefixes=None, path_handler=os.path): """Inits a SymbolFileParser to read symbol records from |input_stream| and write the processed output to |output_stream|. |ignored_prefixes| contains a list of optional path prefixes that should be stripped from the final, normalized path outputs. For example, if the Breakpad symbol file had all paths starting with a common prefix, such as: FILE 1 /b/build/src/foo.cc FILE 2 /b/build/src/bar.cc Then adding "/b/build/src" as an ignored prefix would result in an output file that contained: FILE 1 foo.cc FILE 2 bar.cc Note that |ignored_prefixes| does not necessarily contain file system paths, as the contents of the DWARF DW_AT_comp_dir attribute is dependent upon the host system and compiler, and may contain additional information such as hostname or compiler version. """ self.unique_files = {} self.duplicate_files = {} self.input_stream = input_stream self.output_stream = output_stream self.ignored_prefixes = ignored_prefixes or [] self.path_handler = path_handler def Process(self): """Processes the Breakpad symbol file.""" for line in self.input_stream: parsed = self._ParseRecord(line.rstrip()) if parsed: self.output_stream.write(parsed + '\n') def _ParseRecord(self, record): """Parses a single Breakpad symbol record - a single line from the symbol file. Returns: The modified string to write to the output file, or None if no line should be written. """ record_type = record.partition(' ')[0] if record_type == 'FILE': return self._ParseFileRecord(record) elif self._IsLineRecord(record_type): return self._ParseLineRecord(record) else: # Simply pass the record through unaltered. return record def _NormalizePath(self, path): """Normalizes a file path to its canonical form. As this may not execute on the machine or file system originally responsible for compilation, it may be necessary to further correct paths for symlinks, junctions, or other such file system indirections. Returns: A unique, canonical representation for the the file path. """ return self.path_handler.normpath(path) def _AdjustPath(self, path): """Adjusts the supplied path after performing path de-duplication. This may be used to perform secondary adjustments, such as removing a common prefix, such as "/D/build", or replacing the file system path with information from the version control system. Returns: The actual path to use when writing the FILE record. """ return path[len(filter(path.startswith, self.ignored_prefixes + [''])[0]):] def _ParseFileRecord(self, file_record): """Parses and corrects a FILE record.""" file_info = file_record[5:].split(' ', 3) if len(file_info) > 2: raise BreakpadParseError('Unsupported FILE record: ' + file_record) file_index = int(file_info[0]) file_name = self._NormalizePath(file_info[1]) existing_file_index = self.unique_files.get(file_name) if existing_file_index is None: self.unique_files[file_name] = file_index file_info[1] = self._AdjustPath(file_name) return 'FILE ' + ' '.join(file_info) else: self.duplicate_files[file_index] = existing_file_index return None def _IsLineRecord(self, record_type): """Determines if the current record type is a Line record""" try: line = int(record_type, 16) except (ValueError, TypeError): return False return True def _ParseLineRecord(self, line_record): """Parses and corrects a Line record.""" line_info = line_record.split(' ', 5) if len(line_info) > 4: raise BreakpadParseError('Unsupported Line record: ' + line_record) file_index = int(line_info[3]) line_info[3] = str(self.duplicate_files.get(file_index, file_index)) return ' '.join(line_info) def main(): option_parser = optparse.OptionParser() option_parser.add_option("-p", "--prefix", action="append", dest="prefixes", type="string", default=[], help="A path prefix that should be removed from " "all FILE lines. May be repeated to specify " "multiple prefixes.") option_parser.add_option("-t", "--path_type", action="store", type="choice", dest="path_handler", choices=['win32', 'posix'], help="Indicates how file paths should be " "interpreted. The default is to treat paths " "the same as the OS running Python (eg: " "os.path)") options, args = option_parser.parse_args() if args: option_parser.error('Unknown argument: %s' % args) path_handler = { 'win32': ntpath, 'posix': posixpath }.get(options.path_handler, os.path) try: symbol_parser = SymbolFileParser(sys.stdin, sys.stdout, options.prefixes, path_handler) symbol_parser.Process() except BreakpadParseError, e: print >> sys.stderr, 'Got an error while processing symbol file' print >> sys.stderr, str(e) return 1 return 0 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Unit tests for filter_syms.py""" import cStringIO import ntpath import os import StringIO import sys import unittest ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(ROOT_DIR, '..')) # In root import filter_syms class FilterSysmsTest(unittest.TestCase): def assertParsed(self, input_data, ignored_prefixes, expected): input_io = cStringIO.StringIO(input_data) output_io = cStringIO.StringIO() parser = filter_syms.SymbolFileParser(input_io, output_io, ignored_prefixes, ntpath) parser.Process() self.assertEqual(output_io.getvalue(), expected) def testDuplicateFiles(self): """Tests that duplicate files in FILE records are correctly removed and that Line records are updated.""" INPUT = \ """MODULE windows x86 111111111111111111111111111111111 module1.pdb INFO CODE_ID FFFFFFFF module1.exe FILE 1 foo/../file1_1.cc FILE 2 bar/../file1_1.cc FILE 3 baz/../file1_1.cc FUNC 1000 c 0 Function1_1 1000 8 45 2 1008 4 46 3 100c 4 44 1 """ EXPECTED_OUTPUT = \ """MODULE windows x86 111111111111111111111111111111111 module1.pdb INFO CODE_ID FFFFFFFF module1.exe FILE 1 file1_1.cc FUNC 1000 c 0 Function1_1 1000 8 45 1 1008 4 46 1 100c 4 44 1 """ self.assertParsed(INPUT, [], EXPECTED_OUTPUT) def testIgnoredPrefix(self): """Tests that prefixes in FILE records are correctly removed.""" INPUT = \ """MODULE windows x86 111111111111111111111111111111111 module1.pdb INFO CODE_ID FFFFFFFF module1.exe FILE 1 /src/build/foo/../file1_1.cc FILE 2 /src/build/bar/../file1_2.cc FILE 3 /src/build/baz/../file1_2.cc FUNC 1000 c 0 Function1_1 1000 8 45 2 1008 4 46 3 100c 4 44 1 """ EXPECTED_OUTPUT = \ """MODULE windows x86 111111111111111111111111111111111 module1.pdb INFO CODE_ID FFFFFFFF module1.exe FILE 1 file1_1.cc FILE 2 file1_2.cc FUNC 1000 c 0 Function1_1 1000 8 45 2 1008 4 46 2 100c 4 44 1 """ IGNORED_PREFIXES = ['\\src\\build\\'] self.assertParsed(INPUT, IGNORED_PREFIXES, EXPECTED_OUTPUT) def testIgnoredPrefixesDuplicateFiles(self): """Tests that de-duplication of FILE records happens BEFORE prefixes are removed.""" INPUT = \ """MODULE windows x86 111111111111111111111111111111111 module1.pdb INFO CODE_ID FFFFFFFF module1.exe FILE 1 /src/build/foo/../file1_1.cc FILE 2 /src/build/bar/../file1_2.cc FILE 3 D:/src/build2/baz/../file1_2.cc FUNC 1000 c 0 Function1_1 1000 8 45 2 1008 4 46 3 100c 4 44 1 """ EXPECTED_OUTPUT = \ """MODULE windows x86 111111111111111111111111111111111 module1.pdb INFO CODE_ID FFFFFFFF module1.exe FILE 1 file1_1.cc FILE 2 file1_2.cc FILE 3 file1_2.cc FUNC 1000 c 0 Function1_1 1000 8 45 2 1008 4 46 3 100c 4 44 1 """ IGNORED_PREFIXES = ['\\src\\build\\', 'D:\\src\\build2\\'] self.assertParsed(INPUT, IGNORED_PREFIXES, EXPECTED_OUTPUT) if __name__ == '__main__': unittest.main()
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import os import os.path as osp import argparse import math from tqdm import tqdm import torch.nn as nn import torch.backends.cudnn as cudnn import torch.utils.data from torchvision import transforms, datasets from ofa.utils import AverageMeter, accuracy from ofa.model_zoo import ofa_specialized specialized_network_list = [ ################# FLOPs ################# "flops@[email protected]_finetune@75", "flops@[email protected]_finetune@75", "flops@[email protected]_finetune@75", ################# ResNet50 Design Space ################# "[email protected][email protected]", "[email protected][email protected]", "[email protected][email protected]", "[email protected][email protected]", "[email protected][email protected]", "[email protected][email protected]_finetune@25", "[email protected][email protected]_finetune@25", "[email protected][email protected]_finetune@25", ################# Google pixel1 ################# "pixel1_lat@[email protected]_finetune@75", "pixel1_lat@[email protected]_finetune@75", "pixel1_lat@[email protected]_finetune@75", "pixel1_lat@[email protected]_finetune@75", "pixel1_lat@[email protected]_finetune@25", "pixel1_lat@[email protected]_finetune@25", "pixel1_lat@[email protected]_finetune@25", ################# Google pixel2 ################# "pixel2_lat@[email protected]_finetune@25", "pixel2_lat@[email protected]_finetune@25", "pixel2_lat@[email protected]_finetune@25", "pixel2_lat@[email protected]_finetune@25", ################# Samsung note10 ################# "note10_lat@[email protected]_finetune@75", "note10_lat@[email protected]_finetune@75", "note10_lat@[email protected]_finetune@75", "note10_lat@[email protected]_finetune@75", "note10_lat@[email protected]_finetune@25", "note10_lat@[email protected]_finetune@25", "note10_lat@[email protected]_finetune@25", "note10_lat@[email protected]_finetune@25", ################# Samsung note8 ################# "note8_lat@[email protected]_finetune@25", "note8_lat@[email protected]_finetune@25", "note8_lat@[email protected]_finetune@25", "note8_lat@[email protected]_finetune@25", ################# Samsung S7 Edge ################# "s7edge_lat@[email protected]_finetune@25", "s7edge_lat@[email protected]_finetune@25", "s7edge_lat@[email protected]_finetune@25", "s7edge_lat@[email protected]_finetune@25", ################# LG G8 ################# "LG-G8_lat@[email protected]_finetune@25", "LG-G8_lat@[email protected]_finetune@25", "LG-G8_lat@[email protected]_finetune@25", "LG-G8_lat@[email protected]_finetune@25", ################# 1080ti GPU (Batch Size 64) ################# "1080ti_gpu64@[email protected]_finetune@25", "1080ti_gpu64@[email protected]_finetune@25", "1080ti_gpu64@[email protected]_finetune@25", "1080ti_gpu64@[email protected]_finetune@25", ################# V100 GPU (Batch Size 64) ################# "v100_gpu64@[email protected]_finetune@25", "v100_gpu64@[email protected]_finetune@25", "v100_gpu64@[email protected]_finetune@25", "v100_gpu64@[email protected]_finetune@25", ################# Jetson TX2 GPU (Batch Size 16) ################# "tx2_gpu16@[email protected]_finetune@25", "tx2_gpu16@[email protected]_finetune@25", "tx2_gpu16@[email protected]_finetune@25", "tx2_gpu16@[email protected]_finetune@25", ################# Intel Xeon CPU with MKL-DNN (Batch Size 1) ################# "cpu_lat@[email protected]_finetune@25", "cpu_lat@[email protected]_finetune@25", "cpu_lat@[email protected]_finetune@25", "cpu_lat@[email protected]_finetune@25", ] parser = argparse.ArgumentParser() parser.add_argument( "-p", "--path", help="The path of imagenet", type=str, default="/dataset/imagenet" ) parser.add_argument("-g", "--gpu", help="The gpu(s) to use", type=str, default="all") parser.add_argument( "-b", "--batch-size", help="The batch on every device for validation", type=int, default=100, ) parser.add_argument("-j", "--workers", help="Number of workers", type=int, default=20) parser.add_argument( "-n", "--net", metavar="NET", default="pixel1_lat@[email protected]_finetune@75", choices=specialized_network_list, help="OFA specialized networks: " + " | ".join(specialized_network_list) + " (default: pixel1_lat@[email protected]_finetune@75)", ) args = parser.parse_args() if args.gpu == "all": device_list = range(torch.cuda.device_count()) args.gpu = ",".join(str(_) for _ in device_list) else: device_list = [int(_) for _ in args.gpu.split(",")] os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu net, image_size = ofa_specialized(net_id=args.net, pretrained=True) args.batch_size = args.batch_size * max(len(device_list), 1) data_loader = torch.utils.data.DataLoader( datasets.ImageFolder( osp.join(args.path, "val"), transforms.Compose( [ transforms.Resize(int(math.ceil(image_size / 0.875))), transforms.CenterCrop(image_size), transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ), ] ), ), batch_size=args.batch_size, shuffle=True, num_workers=args.workers, pin_memory=True, drop_last=False, ) net = torch.nn.DataParallel(net).cuda() cudnn.benchmark = True criterion = nn.CrossEntropyLoss().cuda() net.eval() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() with torch.no_grad(): with tqdm(total=len(data_loader), desc="Validate") as t: for i, (images, labels) in enumerate(data_loader): images, labels = images.cuda(), labels.cuda() # compute output output = net(images) loss = criterion(output, labels) # measure accuracy and record loss acc1, acc5 = accuracy(output, labels, topk=(1, 5)) losses.update(loss.item(), images.size(0)) top1.update(acc1[0].item(), images.size(0)) top5.update(acc5[0].item(), images.size(0)) t.set_postfix( { "loss": losses.avg, "top1": top1.avg, "top5": top5.avg, "img_size": images.size(2), } ) t.update(1) print("Test OFA specialized net <%s> with image size %d:" % (args.net, image_size)) print("Results: loss=%.5f,\t top1=%.1f,\t top5=%.1f" % (losses.avg, top1.avg, top5.avg))
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import argparse import numpy as np import os import random import horovod.torch as hvd import torch from ofa.imagenet_classification.elastic_nn.modules.dynamic_op import ( DynamicSeparableConv2d, ) from ofa.imagenet_classification.elastic_nn.networks import OFAMobileNetV3 from ofa.imagenet_classification.run_manager import DistributedImageNetRunConfig from ofa.imagenet_classification.networks import MobileNetV3Large from ofa.imagenet_classification.run_manager.distributed_run_manager import ( DistributedRunManager, ) from ofa.utils import download_url, MyRandomResizedCrop from ofa.imagenet_classification.elastic_nn.training.progressive_shrinking import ( load_models, ) parser = argparse.ArgumentParser() parser.add_argument( "--task", type=str, default="depth", choices=[ "kernel", "depth", "expand", ], ) parser.add_argument("--phase", type=int, default=1, choices=[1, 2]) parser.add_argument("--resume", action="store_true") args = parser.parse_args() if args.task == "kernel": args.path = "exp/normal2kernel" args.dynamic_batch_size = 1 args.n_epochs = 120 args.base_lr = 3e-2 args.warmup_epochs = 5 args.warmup_lr = -1 args.ks_list = "3,5,7" args.expand_list = "6" args.depth_list = "4" elif args.task == "depth": args.path = "exp/kernel2kernel_depth/phase%d" % args.phase args.dynamic_batch_size = 2 if args.phase == 1: args.n_epochs = 25 args.base_lr = 2.5e-3 args.warmup_epochs = 0 args.warmup_lr = -1 args.ks_list = "3,5,7" args.expand_list = "6" args.depth_list = "3,4" else: args.n_epochs = 120 args.base_lr = 7.5e-3 args.warmup_epochs = 5 args.warmup_lr = -1 args.ks_list = "3,5,7" args.expand_list = "6" args.depth_list = "2,3,4" elif args.task == "expand": args.path = "exp/kernel_depth2kernel_depth_width/phase%d" % args.phase args.dynamic_batch_size = 4 if args.phase == 1: args.n_epochs = 25 args.base_lr = 2.5e-3 args.warmup_epochs = 0 args.warmup_lr = -1 args.ks_list = "3,5,7" args.expand_list = "4,6" args.depth_list = "2,3,4" else: args.n_epochs = 120 args.base_lr = 7.5e-3 args.warmup_epochs = 5 args.warmup_lr = -1 args.ks_list = "3,5,7" args.expand_list = "3,4,6" args.depth_list = "2,3,4" else: raise NotImplementedError args.manual_seed = 0 args.lr_schedule_type = "cosine" args.base_batch_size = 64 args.valid_size = 10000 args.opt_type = "sgd" args.momentum = 0.9 args.no_nesterov = False args.weight_decay = 3e-5 args.label_smoothing = 0.1 args.no_decay_keys = "bn#bias" args.fp16_allreduce = False args.model_init = "he_fout" args.validation_frequency = 1 args.print_frequency = 10 args.n_worker = 8 args.resize_scale = 0.08 args.distort_color = "tf" args.image_size = "128,160,192,224" args.continuous_size = True args.not_sync_distributed_image_size = False args.bn_momentum = 0.1 args.bn_eps = 1e-5 args.dropout = 0.1 args.base_stage_width = "proxyless" args.width_mult_list = "1.0" args.dy_conv_scaling_mode = 1 args.independent_distributed_sampling = False args.kd_ratio = 1.0 args.kd_type = "ce" if __name__ == "__main__": os.makedirs(args.path, exist_ok=True) # Initialize Horovod hvd.init() # Pin GPU to be used to process local rank (one GPU per process) torch.cuda.set_device(hvd.local_rank()) args.teacher_path = download_url( "https://hanlab.mit.edu/files/OnceForAll/ofa_checkpoints/ofa_D4_E6_K7", model_dir=".torch/ofa_checkpoints/%d" % hvd.rank(), ) num_gpus = hvd.size() torch.manual_seed(args.manual_seed) torch.cuda.manual_seed_all(args.manual_seed) np.random.seed(args.manual_seed) random.seed(args.manual_seed) # image size args.image_size = [int(img_size) for img_size in args.image_size.split(",")] if len(args.image_size) == 1: args.image_size = args.image_size[0] MyRandomResizedCrop.CONTINUOUS = args.continuous_size MyRandomResizedCrop.SYNC_DISTRIBUTED = not args.not_sync_distributed_image_size # build run config from args args.lr_schedule_param = None args.opt_param = { "momentum": args.momentum, "nesterov": not args.no_nesterov, } args.init_lr = args.base_lr * num_gpus # linearly rescale the learning rate if args.warmup_lr < 0: args.warmup_lr = args.base_lr args.train_batch_size = args.base_batch_size args.test_batch_size = args.base_batch_size * 4 run_config = DistributedImageNetRunConfig( **args.__dict__, num_replicas=num_gpus, rank=hvd.rank() ) # print run config information if hvd.rank() == 0: print("Run config:") for k, v in run_config.config.items(): print("\t%s: %s" % (k, v)) if args.dy_conv_scaling_mode == -1: args.dy_conv_scaling_mode = None DynamicSeparableConv2d.KERNEL_TRANSFORM_MODE = args.dy_conv_scaling_mode # build net from args args.width_mult_list = [ float(width_mult) for width_mult in args.width_mult_list.split(",") ] args.ks_list = [int(ks) for ks in args.ks_list.split(",")] args.expand_list = [int(e) for e in args.expand_list.split(",")] args.depth_list = [int(d) for d in args.depth_list.split(",")] args.width_mult_list = ( args.width_mult_list[0] if len(args.width_mult_list) == 1 else args.width_mult_list ) net = OFAMobileNetV3( n_classes=run_config.data_provider.n_classes, bn_param=(args.bn_momentum, args.bn_eps), dropout_rate=args.dropout, base_stage_width=args.base_stage_width, width_mult=args.width_mult_list, ks_list=args.ks_list, expand_ratio_list=args.expand_list, depth_list=args.depth_list, ) # teacher model if args.kd_ratio > 0: args.teacher_model = MobileNetV3Large( n_classes=run_config.data_provider.n_classes, bn_param=(args.bn_momentum, args.bn_eps), dropout_rate=0, width_mult=1.0, ks=7, expand_ratio=6, depth_param=4, ) args.teacher_model.cuda() """ Distributed RunManager """ # Horovod: (optional) compression algorithm. compression = hvd.Compression.fp16 if args.fp16_allreduce else hvd.Compression.none distributed_run_manager = DistributedRunManager( args.path, net, run_config, compression, backward_steps=args.dynamic_batch_size, is_root=(hvd.rank() == 0), ) distributed_run_manager.save_config() # hvd broadcast distributed_run_manager.broadcast() # load teacher net weights if args.kd_ratio > 0: load_models( distributed_run_manager, args.teacher_model, model_path=args.teacher_path ) # training from ofa.imagenet_classification.elastic_nn.training.progressive_shrinking import ( validate, train, ) validate_func_dict = { "image_size_list": {224} if isinstance(args.image_size, int) else sorted({160, 224}), "ks_list": sorted({min(args.ks_list), max(args.ks_list)}), "expand_ratio_list": sorted({min(args.expand_list), max(args.expand_list)}), "depth_list": sorted({min(net.depth_list), max(net.depth_list)}), } if args.task == "kernel": validate_func_dict["ks_list"] = sorted(args.ks_list) if distributed_run_manager.start_epoch == 0: args.ofa_checkpoint_path = download_url( "https://hanlab.mit.edu/files/OnceForAll/ofa_checkpoints/ofa_D4_E6_K7", model_dir=".torch/ofa_checkpoints/%d" % hvd.rank(), ) load_models( distributed_run_manager, distributed_run_manager.net, args.ofa_checkpoint_path, ) distributed_run_manager.write_log( "%.3f\t%.3f\t%.3f\t%s" % validate(distributed_run_manager, is_test=True, **validate_func_dict), "valid", ) else: assert args.resume train( distributed_run_manager, args, lambda _run_manager, epoch, is_test: validate( _run_manager, epoch, is_test, **validate_func_dict ), ) elif args.task == "depth": from ofa.imagenet_classification.elastic_nn.training.progressive_shrinking import ( train_elastic_depth, ) if args.phase == 1: args.ofa_checkpoint_path = download_url( "https://hanlab.mit.edu/files/OnceForAll/ofa_checkpoints/ofa_D4_E6_K357", model_dir=".torch/ofa_checkpoints/%d" % hvd.rank(), ) else: args.ofa_checkpoint_path = download_url( "https://hanlab.mit.edu/files/OnceForAll/ofa_checkpoints/ofa_D34_E6_K357", model_dir=".torch/ofa_checkpoints/%d" % hvd.rank(), ) train_elastic_depth(train, distributed_run_manager, args, validate_func_dict) elif args.task == "expand": from ofa.imagenet_classification.elastic_nn.training.progressive_shrinking import ( train_elastic_expand, ) if args.phase == 1: args.ofa_checkpoint_path = download_url( "https://hanlab.mit.edu/files/OnceForAll/ofa_checkpoints/ofa_D234_E6_K357", model_dir=".torch/ofa_checkpoints/%d" % hvd.rank(), ) else: args.ofa_checkpoint_path = download_url( "https://hanlab.mit.edu/files/OnceForAll/ofa_checkpoints/ofa_D234_E46_K357", model_dir=".torch/ofa_checkpoints/%d" % hvd.rank(), ) train_elastic_expand(train, distributed_run_manager, args, validate_func_dict) else: raise NotImplementedError
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import os import torch import argparse from ofa.imagenet_classification.data_providers.imagenet import ImagenetDataProvider from ofa.imagenet_classification.run_manager import ImagenetRunConfig, RunManager from ofa.model_zoo import ofa_net parser = argparse.ArgumentParser() parser.add_argument( "-p", "--path", help="The path of imagenet", type=str, default="/dataset/imagenet" ) parser.add_argument("-g", "--gpu", help="The gpu(s) to use", type=str, default="all") parser.add_argument( "-b", "--batch-size", help="The batch on every device for validation", type=int, default=100, ) parser.add_argument("-j", "--workers", help="Number of workers", type=int, default=20) parser.add_argument( "-n", "--net", metavar="OFANET", default="ofa_resnet50", choices=[ "ofa_mbv3_d234_e346_k357_w1.0", "ofa_mbv3_d234_e346_k357_w1.2", "ofa_proxyless_d234_e346_k357_w1.3", "ofa_resnet50", ], help="OFA networks", ) args = parser.parse_args() if args.gpu == "all": device_list = range(torch.cuda.device_count()) args.gpu = ",".join(str(_) for _ in device_list) else: device_list = [int(_) for _ in args.gpu.split(",")] os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu args.batch_size = args.batch_size * max(len(device_list), 1) ImagenetDataProvider.DEFAULT_PATH = args.path ofa_network = ofa_net(args.net, pretrained=True) run_config = ImagenetRunConfig(test_batch_size=args.batch_size, n_worker=args.workers) """ Randomly sample a sub-network, you can also manually set the sub-network using: ofa_network.set_active_subnet(ks=7, e=6, d=4) """ ofa_network.sample_active_subnet() subnet = ofa_network.get_active_subnet(preserve_weight=True) """ Test sampled subnet """ run_manager = RunManager(".tmp/eval_subnet", subnet, run_config, init=False) # assign image size: 128, 132, ..., 224 run_config.data_provider.assign_active_img_size(224) run_manager.reset_running_statistics(net=subnet) print("Test random subnet:") print(subnet.module_str) loss, (top1, top5) = run_manager.validate(net=subnet) print("Results: loss=%.5f,\t top1=%.1f,\t top5=%.1f" % (loss, top1, top5))
#!/usr/bin/env python import os, sys import shutil import datetime from setuptools import setup, find_packages from setuptools.command.install import install # readme = open('README.md').read() readme = """ # Once for All: Train One Network and Specialize it for Efficient Deployment [[arXiv]](https://arxiv.org/abs/1908.09791) [[Slides]](https://file.lzhu.me/projects/OnceForAll/OFA%20Slides.pdf) [[Video]](https://youtu.be/a_OeT8MXzWI) ```BibTex @inproceedings{ cai2020once, title={Once for All: Train One Network and Specialize it for Efficient Deployment}, author={Han Cai and Chuang Gan and Tianzhe Wang and Zhekai Zhang and Song Han}, booktitle={International Conference on Learning Representations}, year={2020}, url={https://arxiv.org/pdf/1908.09791.pdf} } ``` ## News - Fisrt place in the 4th [Low-Power Computer Vision Challenge](https://lpcv.ai/competitions/2019), both classification and detection track. - First place in the 3rd [Low-Power Computer Vision Challenge](https://lpcv.ai/competitions/2019), DSP track at ICCV’19 using the Once-for-all Network. ## Check our [GitHub](https://github.com/mit-han-lab/once-for-all) for more details. """ VERSION = "0.1.0" requirements = [ "torch", ] # import subprocess # commit_hash = subprocess.check_output("git rev-parse HEAD", shell=True).decode('UTF-8').rstrip() # VERSION += "_" + str(int(commit_hash, 16))[:8] VERSION += "_" + datetime.datetime.now().strftime("%Y%m%d%H%M") # print(VERSION) setup( # Metadata name="ofa", version=VERSION, author="MTI HAN LAB ", author_email="[email protected]", url="https://github.com/mit-han-lab/once-for-all", description="Once for All: Train One Network and Specialize it for Efficient Deployment.", long_description=readme, long_description_content_type="text/markdown", license="MIT", # Package info packages=find_packages(exclude=("*test*",)), # zip_safe=True, install_requires=requirements, # Classifiers classifiers=[ "Programming Language :: Python :: 3", ], )
dependencies = ['torch', 'torchvision'] from functools import partial from ofa.model_zoo import ofa_net, ofa_specialized # general model ofa_supernet_resnet50 = partial(ofa_net, net_id="ofa_resnet50", pretrained=True) ofa_supernet_mbv3_w10 = partial(ofa_net, net_id="ofa_mbv3_d234_e346_k357_w1.0", pretrained=True) ofa_supernet_mbv3_w12 = partial(ofa_net, net_id="ofa_mbv3_d234_e346_k357_w1.2", pretrained=True) ofa_supernet_proxyless = partial(ofa_net, net_id="ofa_proxyless_d234_e346_k357_w1.3", pretrained=True) # specialized resnet50D_MAC_4_1B = partial(ofa_specialized, net_id="[email protected][email protected]") resnet50D_MAC_3_7B = partial(ofa_specialized, net_id="[email protected][email protected]") resnet50D_MAC_3_0B = partial(ofa_specialized, net_id="[email protected][email protected]") resnet50D_MAC_2_4B = partial(ofa_specialized, net_id="[email protected][email protected]") resnet50D_MAC_1_8B = partial(ofa_specialized, net_id="[email protected][email protected]") resnet50D_MAC_1_2B = partial(ofa_specialized, net_id="[email protected][email protected]_finetune@25") resnet50D_MAC_0_9B = partial(ofa_specialized, net_id="[email protected][email protected]_finetune@25") resnet50D_MAC_0_6B = partial(ofa_specialized, net_id="[email protected][email protected]_finetune@25") def ofa_specialized_get(): return ofa_specialized
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import json import torch from ofa.utils import download_url from ofa.imagenet_classification.networks import get_net_by_name, proxyless_base from ofa.imagenet_classification.elastic_nn.networks import ( OFAMobileNetV3, OFAProxylessNASNets, OFAResNets, ) __all__ = [ "ofa_specialized", "ofa_net", "proxylessnas_net", "proxylessnas_mobile", "proxylessnas_cpu", "proxylessnas_gpu", ] def ofa_specialized(net_id, pretrained=True): url_base = "https://hanlab.mit.edu/files/OnceForAll/ofa_specialized/" net_config = json.load( open( download_url( url_base + net_id + "/net.config", model_dir=".torch/ofa_specialized/%s/" % net_id, ) ) ) net = get_net_by_name(net_config["name"]).build_from_config(net_config) image_size = json.load( open( download_url( url_base + net_id + "/run.config", model_dir=".torch/ofa_specialized/%s/" % net_id, ) ) )["image_size"] if pretrained: init = torch.load( download_url( url_base + net_id + "/init", model_dir=".torch/ofa_specialized/%s/" % net_id, ), map_location="cpu", )["state_dict"] net.load_state_dict(init) return net, image_size def ofa_net(net_id, pretrained=True): if net_id == "ofa_proxyless_d234_e346_k357_w1.3": net = OFAProxylessNASNets( dropout_rate=0, width_mult=1.3, ks_list=[3, 5, 7], expand_ratio_list=[3, 4, 6], depth_list=[2, 3, 4], ) elif net_id == "ofa_mbv3_d234_e346_k357_w1.0": net = OFAMobileNetV3( dropout_rate=0, width_mult=1.0, ks_list=[3, 5, 7], expand_ratio_list=[3, 4, 6], depth_list=[2, 3, 4], ) elif net_id == "ofa_mbv3_d234_e346_k357_w1.2": net = OFAMobileNetV3( dropout_rate=0, width_mult=1.2, ks_list=[3, 5, 7], expand_ratio_list=[3, 4, 6], depth_list=[2, 3, 4], ) elif net_id == "ofa_resnet50": net = OFAResNets( dropout_rate=0, depth_list=[0, 1, 2], expand_ratio_list=[0.2, 0.25, 0.35], width_mult_list=[0.65, 0.8, 1.0], ) net_id = "ofa_resnet50_d=0+1+2_e=0.2+0.25+0.35_w=0.65+0.8+1.0" else: raise ValueError("Not supported: %s" % net_id) if pretrained: url_base = "https://hanlab.mit.edu/files/OnceForAll/ofa_nets/" init = torch.load( download_url(url_base + net_id, model_dir=".torch/ofa_nets"), map_location="cpu", )["state_dict"] net.load_state_dict(init) return net def proxylessnas_net(net_id, pretrained=True): net = proxyless_base( net_config="https://hanlab.mit.edu/files/proxylessNAS/%s.config" % net_id, ) if pretrained: net.load_state_dict( torch.load( download_url( "https://hanlab.mit.edu/files/proxylessNAS/%s.pth" % net_id ), map_location="cpu", )["state_dict"] ) return net def proxylessnas_mobile(pretrained=True): return proxylessnas_net("proxyless_mobile", pretrained) def proxylessnas_cpu(pretrained=True): return proxylessnas_net("proxyless_cpu", pretrained) def proxylessnas_gpu(pretrained=True): return proxylessnas_net("proxyless_gpu", pretrained)
import yaml from ofa.utils import download_url class LatencyEstimator(object): def __init__( self, local_dir="~/.hancai/latency_tools/", url="https://hanlab.mit.edu/files/proxylessNAS/LatencyTools/mobile_trim.yaml", ): if url.startswith("http"): fname = download_url(url, local_dir, overwrite=True) else: fname = url with open(fname, "r") as fp: self.lut = yaml.load(fp) @staticmethod def repr_shape(shape): if isinstance(shape, (list, tuple)): return "x".join(str(_) for _ in shape) elif isinstance(shape, str): return shape else: return TypeError def query( self, l_type: str, input_shape, output_shape, mid=None, ks=None, stride=None, id_skip=None, se=None, h_swish=None, ): infos = [ l_type, "input:%s" % self.repr_shape(input_shape), "output:%s" % self.repr_shape(output_shape), ] if l_type in ("expanded_conv",): assert None not in (mid, ks, stride, id_skip, se, h_swish) infos += [ "expand:%d" % mid, "kernel:%d" % ks, "stride:%d" % stride, "idskip:%d" % id_skip, "se:%d" % se, "hs:%d" % h_swish, ] key = "-".join(infos) return self.lut[key]["mean"] def predict_network_latency(self, net, image_size=224): predicted_latency = 0 # first conv predicted_latency += self.query( "Conv", [image_size, image_size, 3], [(image_size + 1) // 2, (image_size + 1) // 2, net.first_conv.out_channels], ) # blocks fsize = (image_size + 1) // 2 for block in net.blocks: mb_conv = block.mobile_inverted_conv shortcut = block.shortcut if mb_conv is None: continue if shortcut is None: idskip = 0 else: idskip = 1 out_fz = int((fsize - 1) / mb_conv.stride + 1) block_latency = self.query( "expanded_conv", [fsize, fsize, mb_conv.in_channels], [out_fz, out_fz, mb_conv.out_channels], mid=mb_conv.depth_conv.conv.in_channels, ks=mb_conv.kernel_size, stride=mb_conv.stride, id_skip=idskip, se=1 if mb_conv.use_se else 0, h_swish=1 if mb_conv.act_func == "h_swish" else 0, ) predicted_latency += block_latency fsize = out_fz # final expand layer predicted_latency += self.query( "Conv_1", [fsize, fsize, net.final_expand_layer.in_channels], [fsize, fsize, net.final_expand_layer.out_channels], ) # global average pooling predicted_latency += self.query( "AvgPool2D", [fsize, fsize, net.final_expand_layer.out_channels], [1, 1, net.final_expand_layer.out_channels], ) # feature mix layer predicted_latency += self.query( "Conv_2", [1, 1, net.feature_mix_layer.in_channels], [1, 1, net.feature_mix_layer.out_channels], ) # classifier predicted_latency += self.query( "Logits", [1, 1, net.classifier.in_features], [net.classifier.out_features] ) return predicted_latency def predict_network_latency_given_spec(self, spec): image_size = spec["r"][0] predicted_latency = 0 # first conv predicted_latency += self.query( "Conv", [image_size, image_size, 3], [(image_size + 1) // 2, (image_size + 1) // 2, 24], ) # blocks fsize = (image_size + 1) // 2 # first block predicted_latency += self.query( "expanded_conv", [fsize, fsize, 24], [fsize, fsize, 24], mid=24, ks=3, stride=1, id_skip=1, se=0, h_swish=0, ) in_channel = 24 stride_stages = [2, 2, 2, 1, 2] width_stages = [32, 48, 96, 136, 192] act_stages = ["relu", "relu", "h_swish", "h_swish", "h_swish"] se_stages = [False, True, False, True, True] for i in range(20): stage = i // 4 depth_max = spec["d"][stage] depth = i % 4 + 1 if depth > depth_max: continue ks, e = spec["ks"][i], spec["e"][i] if i % 4 == 0: stride = stride_stages[stage] idskip = 0 else: stride = 1 idskip = 1 out_channel = width_stages[stage] out_fz = int((fsize - 1) / stride + 1) mid_channel = round(in_channel * e) block_latency = self.query( "expanded_conv", [fsize, fsize, in_channel], [out_fz, out_fz, out_channel], mid=mid_channel, ks=ks, stride=stride, id_skip=idskip, se=1 if se_stages[stage] else 0, h_swish=1 if act_stages[stage] == "h_swish" else 0, ) predicted_latency += block_latency fsize = out_fz in_channel = out_channel # final expand layer predicted_latency += self.query( "Conv_1", [fsize, fsize, 192], [fsize, fsize, 1152], ) # global average pooling predicted_latency += self.query( "AvgPool2D", [fsize, fsize, 1152], [1, 1, 1152], ) # feature mix layer predicted_latency += self.query("Conv_2", [1, 1, 1152], [1, 1, 1536]) # classifier predicted_latency += self.query("Logits", [1, 1, 1536], [1000]) return predicted_latency class LatencyTable: def __init__(self, device="note10", resolutions=(160, 176, 192, 208, 224)): self.latency_tables = {} for image_size in resolutions: self.latency_tables[image_size] = LatencyEstimator( url="https://hanlab.mit.edu/files/OnceForAll/tutorial/latency_table@%s/%d_lookup_table.yaml" % (device, image_size) ) print("Built latency table for image size: %d." % image_size) def predict_efficiency(self, spec: dict): return self.latency_tables[spec["r"][0]].predict_network_latency_given_spec( spec )
import copy import random from tqdm import tqdm import numpy as np __all__ = ["EvolutionFinder"] class ArchManager: def __init__(self): self.num_blocks = 20 self.num_stages = 5 self.kernel_sizes = [3, 5, 7] self.expand_ratios = [3, 4, 6] self.depths = [2, 3, 4] self.resolutions = [160, 176, 192, 208, 224] def random_sample(self): sample = {} d = [] e = [] ks = [] for i in range(self.num_stages): d.append(random.choice(self.depths)) for i in range(self.num_blocks): e.append(random.choice(self.expand_ratios)) ks.append(random.choice(self.kernel_sizes)) sample = { "wid": None, "ks": ks, "e": e, "d": d, "r": [random.choice(self.resolutions)], } return sample def random_resample(self, sample, i): assert i >= 0 and i < self.num_blocks sample["ks"][i] = random.choice(self.kernel_sizes) sample["e"][i] = random.choice(self.expand_ratios) def random_resample_depth(self, sample, i): assert i >= 0 and i < self.num_stages sample["d"][i] = random.choice(self.depths) def random_resample_resolution(self, sample): sample["r"][0] = random.choice(self.resolutions) class EvolutionFinder: valid_constraint_range = { "flops": [150, 600], "note10": [15, 60], } def __init__( self, constraint_type, efficiency_constraint, efficiency_predictor, accuracy_predictor, **kwargs ): self.constraint_type = constraint_type if not constraint_type in self.valid_constraint_range.keys(): self.invite_reset_constraint_type() self.efficiency_constraint = efficiency_constraint if not ( efficiency_constraint <= self.valid_constraint_range[constraint_type][1] and efficiency_constraint >= self.valid_constraint_range[constraint_type][0] ): self.invite_reset_constraint() self.efficiency_predictor = efficiency_predictor self.accuracy_predictor = accuracy_predictor self.arch_manager = ArchManager() self.num_blocks = self.arch_manager.num_blocks self.num_stages = self.arch_manager.num_stages self.mutate_prob = kwargs.get("mutate_prob", 0.1) self.population_size = kwargs.get("population_size", 100) self.max_time_budget = kwargs.get("max_time_budget", 500) self.parent_ratio = kwargs.get("parent_ratio", 0.25) self.mutation_ratio = kwargs.get("mutation_ratio", 0.5) def invite_reset_constraint_type(self): print( "Invalid constraint type! Please input one of:", list(self.valid_constraint_range.keys()), ) new_type = input() while new_type not in self.valid_constraint_range.keys(): print( "Invalid constraint type! Please input one of:", list(self.valid_constraint_range.keys()), ) new_type = input() self.constraint_type = new_type def invite_reset_constraint(self): print( "Invalid constraint_value! Please input an integer in interval: [%d, %d]!" % ( self.valid_constraint_range[self.constraint_type][0], self.valid_constraint_range[self.constraint_type][1], ) ) new_cons = input() while ( (not new_cons.isdigit()) or (int(new_cons) > self.valid_constraint_range[self.constraint_type][1]) or (int(new_cons) < self.valid_constraint_range[self.constraint_type][0]) ): print( "Invalid constraint_value! Please input an integer in interval: [%d, %d]!" % ( self.valid_constraint_range[self.constraint_type][0], self.valid_constraint_range[self.constraint_type][1], ) ) new_cons = input() new_cons = int(new_cons) self.efficiency_constraint = new_cons def set_efficiency_constraint(self, new_constraint): self.efficiency_constraint = new_constraint def random_sample(self): constraint = self.efficiency_constraint while True: sample = self.arch_manager.random_sample() efficiency = self.efficiency_predictor.predict_efficiency(sample) if efficiency <= constraint: return sample, efficiency def mutate_sample(self, sample): constraint = self.efficiency_constraint while True: new_sample = copy.deepcopy(sample) if random.random() < self.mutate_prob: self.arch_manager.random_resample_resolution(new_sample) for i in range(self.num_blocks): if random.random() < self.mutate_prob: self.arch_manager.random_resample(new_sample, i) for i in range(self.num_stages): if random.random() < self.mutate_prob: self.arch_manager.random_resample_depth(new_sample, i) efficiency = self.efficiency_predictor.predict_efficiency(new_sample) if efficiency <= constraint: return new_sample, efficiency def crossover_sample(self, sample1, sample2): constraint = self.efficiency_constraint while True: new_sample = copy.deepcopy(sample1) for key in new_sample.keys(): if not isinstance(new_sample[key], list): continue for i in range(len(new_sample[key])): new_sample[key][i] = random.choice( [sample1[key][i], sample2[key][i]] ) efficiency = self.efficiency_predictor.predict_efficiency(new_sample) if efficiency <= constraint: return new_sample, efficiency def run_evolution_search(self, verbose=False): """Run a single roll-out of regularized evolution to a fixed time budget.""" max_time_budget = self.max_time_budget population_size = self.population_size mutation_numbers = int(round(self.mutation_ratio * population_size)) parents_size = int(round(self.parent_ratio * population_size)) constraint = self.efficiency_constraint best_valids = [-100] population = [] # (validation, sample, latency) tuples child_pool = [] efficiency_pool = [] best_info = None if verbose: print("Generate random population...") for _ in range(population_size): sample, efficiency = self.random_sample() child_pool.append(sample) efficiency_pool.append(efficiency) accs = self.accuracy_predictor.predict_accuracy(child_pool) for i in range(population_size): population.append((accs[i].item(), child_pool[i], efficiency_pool[i])) if verbose: print("Start Evolution...") # After the population is seeded, proceed with evolving the population. for iter in tqdm( range(max_time_budget), desc="Searching with %s constraint (%s)" % (self.constraint_type, self.efficiency_constraint), ): parents = sorted(population, key=lambda x: x[0])[::-1][:parents_size] acc = parents[0][0] if verbose: print("Iter: {} Acc: {}".format(iter - 1, parents[0][0])) if acc > best_valids[-1]: best_valids.append(acc) best_info = parents[0] else: best_valids.append(best_valids[-1]) population = parents child_pool = [] efficiency_pool = [] for i in range(mutation_numbers): par_sample = population[np.random.randint(parents_size)][1] # Mutate new_sample, efficiency = self.mutate_sample(par_sample) child_pool.append(new_sample) efficiency_pool.append(efficiency) for i in range(population_size - mutation_numbers): par_sample1 = population[np.random.randint(parents_size)][1] par_sample2 = population[np.random.randint(parents_size)][1] # Crossover new_sample, efficiency = self.crossover_sample(par_sample1, par_sample2) child_pool.append(new_sample) efficiency_pool.append(efficiency) accs = self.accuracy_predictor.predict_accuracy(child_pool) for i in range(population_size): population.append((accs[i].item(), child_pool[i], efficiency_pool[i])) return best_valids, best_info
from .accuracy_predictor import AccuracyPredictor from .flops_table import FLOPsTable from .latency_table import LatencyTable from .evolution_finder import EvolutionFinder from .imagenet_eval_helper import evaluate_ofa_subnet, evaluate_ofa_specialized
import torch.nn as nn import torch import copy from ofa.utils import download_url # Helper for constructing the one-hot vectors. def construct_maps(keys): d = dict() keys = list(set(keys)) for k in keys: if k not in d: d[k] = len(list(d.keys())) return d ks_map = construct_maps(keys=(3, 5, 7)) ex_map = construct_maps(keys=(3, 4, 6)) dp_map = construct_maps(keys=(2, 3, 4)) class AccuracyPredictor: def __init__(self, pretrained=True, device="cuda:0"): self.device = device self.model = nn.Sequential( nn.Linear(128, 400), nn.ReLU(), nn.Linear(400, 400), nn.ReLU(), nn.Linear(400, 400), nn.ReLU(), nn.Linear(400, 1), ) if pretrained: # load pretrained model fname = download_url( "https://hanlab.mit.edu/files/OnceForAll/tutorial/acc_predictor.pth" ) self.model.load_state_dict( torch.load(fname, map_location=torch.device("cpu")) ) self.model = self.model.to(self.device) # TODO: merge it with serialization utils. @torch.no_grad() def predict_accuracy(self, population): all_feats = [] for sample in population: ks_list = copy.deepcopy(sample["ks"]) ex_list = copy.deepcopy(sample["e"]) d_list = copy.deepcopy(sample["d"]) r = copy.deepcopy(sample["r"])[0] feats = ( AccuracyPredictor.spec2feats(ks_list, ex_list, d_list, r) .reshape(1, -1) .to(self.device) ) all_feats.append(feats) all_feats = torch.cat(all_feats, 0) pred = self.model(all_feats).cpu() return pred @staticmethod def spec2feats(ks_list, ex_list, d_list, r): # This function converts a network config to a feature vector (128-D). start = 0 end = 4 for d in d_list: for j in range(start + d, end): ks_list[j] = 0 ex_list[j] = 0 start += 4 end += 4 # convert to onehot ks_onehot = [0 for _ in range(60)] ex_onehot = [0 for _ in range(60)] r_onehot = [0 for _ in range(8)] for i in range(20): start = i * 3 if ks_list[i] != 0: ks_onehot[start + ks_map[ks_list[i]]] = 1 if ex_list[i] != 0: ex_onehot[start + ex_map[ex_list[i]]] = 1 r_onehot[(r - 112) // 16] = 1 return torch.Tensor(ks_onehot + ex_onehot + r_onehot)
import time import copy import torch import torch.nn as nn import numpy as np from ofa.utils.layers import * __all__ = ["FLOPsTable"] def rm_bn_from_net(net): for m in net.modules(): if isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d): m.forward = lambda x: x class FLOPsTable: def __init__( self, pred_type="flops", device="cuda:0", multiplier=1.2, batch_size=64, load_efficiency_table=None, ): assert pred_type in ["flops", "latency"] self.multiplier = multiplier self.pred_type = pred_type self.device = device self.batch_size = batch_size self.efficiency_dict = {} if load_efficiency_table is not None: self.efficiency_dict = np.load( load_efficiency_table, allow_pickle=True ).item() else: self.build_lut(batch_size) @torch.no_grad() def measure_single_layer_latency( self, layer: nn.Module, input_size: tuple, warmup_steps=10, measure_steps=50 ): total_time = 0 inputs = torch.randn(*input_size, device=self.device) layer.eval() rm_bn_from_net(layer) network = layer.to(self.device) torch.cuda.synchronize() for i in range(warmup_steps): network(inputs) torch.cuda.synchronize() torch.cuda.synchronize() st = time.time() for i in range(measure_steps): network(inputs) torch.cuda.synchronize() ed = time.time() total_time += ed - st latency = total_time / measure_steps * 1000 return latency @torch.no_grad() def measure_single_layer_flops(self, layer: nn.Module, input_size: tuple): import thop inputs = torch.randn(*input_size, device=self.device) network = layer.to(self.device) layer.eval() rm_bn_from_net(layer) flops, params = thop.profile(network, (inputs,), verbose=False) return flops / 1e6 def build_lut(self, batch_size=1, resolutions=[160, 176, 192, 208, 224]): for resolution in resolutions: self.build_single_lut(batch_size, resolution) np.save("local_lut.npy", self.efficiency_dict) def build_single_lut(self, batch_size=1, base_resolution=224): print( "Building the %s lookup table (resolution=%d)..." % (self.pred_type, base_resolution) ) # block, input_size, in_channels, out_channels, expand_ratio, kernel_size, stride, act, se configurations = [ (ConvLayer, base_resolution, 3, 16, 3, 2, "relu"), ( ResidualBlock, base_resolution // 2, 16, 16, [1], [3, 5, 7], 1, "relu", False, ), ( ResidualBlock, base_resolution // 2, 16, 24, [3, 4, 6], [3, 5, 7], 2, "relu", False, ), ( ResidualBlock, base_resolution // 4, 24, 24, [3, 4, 6], [3, 5, 7], 1, "relu", False, ), ( ResidualBlock, base_resolution // 4, 24, 24, [3, 4, 6], [3, 5, 7], 1, "relu", False, ), ( ResidualBlock, base_resolution // 4, 24, 24, [3, 4, 6], [3, 5, 7], 1, "relu", False, ), ( ResidualBlock, base_resolution // 4, 24, 40, [3, 4, 6], [3, 5, 7], 2, "relu", True, ), ( ResidualBlock, base_resolution // 8, 40, 40, [3, 4, 6], [3, 5, 7], 1, "relu", True, ), ( ResidualBlock, base_resolution // 8, 40, 40, [3, 4, 6], [3, 5, 7], 1, "relu", True, ), ( ResidualBlock, base_resolution // 8, 40, 40, [3, 4, 6], [3, 5, 7], 1, "relu", True, ), ( ResidualBlock, base_resolution // 8, 40, 80, [3, 4, 6], [3, 5, 7], 2, "h_swish", False, ), ( ResidualBlock, base_resolution // 16, 80, 80, [3, 4, 6], [3, 5, 7], 1, "h_swish", False, ), ( ResidualBlock, base_resolution // 16, 80, 80, [3, 4, 6], [3, 5, 7], 1, "h_swish", False, ), ( ResidualBlock, base_resolution // 16, 80, 80, [3, 4, 6], [3, 5, 7], 1, "h_swish", False, ), ( ResidualBlock, base_resolution // 16, 80, 112, [3, 4, 6], [3, 5, 7], 1, "h_swish", True, ), ( ResidualBlock, base_resolution // 16, 112, 112, [3, 4, 6], [3, 5, 7], 1, "h_swish", True, ), ( ResidualBlock, base_resolution // 16, 112, 112, [3, 4, 6], [3, 5, 7], 1, "h_swish", True, ), ( ResidualBlock, base_resolution // 16, 112, 112, [3, 4, 6], [3, 5, 7], 1, "h_swish", True, ), ( ResidualBlock, base_resolution // 16, 112, 160, [3, 4, 6], [3, 5, 7], 2, "h_swish", True, ), ( ResidualBlock, base_resolution // 32, 160, 160, [3, 4, 6], [3, 5, 7], 1, "h_swish", True, ), ( ResidualBlock, base_resolution // 32, 160, 160, [3, 4, 6], [3, 5, 7], 1, "h_swish", True, ), ( ResidualBlock, base_resolution // 32, 160, 160, [3, 4, 6], [3, 5, 7], 1, "h_swish", True, ), (ConvLayer, base_resolution // 32, 160, 960, 1, 1, "h_swish"), (ConvLayer, 1, 960, 1280, 1, 1, "h_swish"), (LinearLayer, 1, 1280, 1000, 1, 1), ] efficiency_dict = {"mobile_inverted_blocks": [], "other_blocks": {}} for layer_idx in range(len(configurations)): config = configurations[layer_idx] op_type = config[0] if op_type == ResidualBlock: ( _, input_size, in_channels, out_channels, expand_list, ks_list, stride, act, se, ) = config in_channels = int(round(in_channels * self.multiplier)) out_channels = int(round(out_channels * self.multiplier)) template_config = { "name": ResidualBlock.__name__, "mobile_inverted_conv": { "name": MBConvLayer.__name__, "in_channels": in_channels, "out_channels": out_channels, "kernel_size": kernel_size, "stride": stride, "expand_ratio": 0, # 'mid_channels': None, "act_func": act, "use_se": se, }, "shortcut": { "name": IdentityLayer.__name__, "in_channels": in_channels, "out_channels": out_channels, } if (in_channels == out_channels and stride == 1) else None, } sub_dict = {} for ks in ks_list: for e in expand_list: build_config = copy.deepcopy(template_config) build_config["mobile_inverted_conv"]["expand_ratio"] = e build_config["mobile_inverted_conv"]["kernel_size"] = ks layer = ResidualBlock.build_from_config(build_config) input_shape = (batch_size, in_channels, input_size, input_size) if self.pred_type == "flops": measure_result = ( self.measure_single_layer_flops(layer, input_shape) / batch_size ) elif self.pred_type == "latency": measure_result = self.measure_single_layer_latency( layer, input_shape ) sub_dict[(ks, e)] = measure_result efficiency_dict["mobile_inverted_blocks"].append(sub_dict) elif op_type == ConvLayer: ( _, input_size, in_channels, out_channels, kernel_size, stride, activation, ) = config in_channels = int(round(in_channels * self.multiplier)) out_channels = int(round(out_channels * self.multiplier)) build_config = { # 'name': ConvLayer.__name__, "in_channels": in_channels, "out_channels": out_channels, "kernel_size": kernel_size, "stride": stride, "dilation": 1, "groups": 1, "bias": False, "use_bn": True, "has_shuffle": False, "act_func": activation, } layer = ConvLayer.build_from_config(build_config) input_shape = (batch_size, in_channels, input_size, input_size) if self.pred_type == "flops": measure_result = ( self.measure_single_layer_flops(layer, input_shape) / batch_size ) elif self.pred_type == "latency": measure_result = self.measure_single_layer_latency( layer, input_shape ) efficiency_dict["other_blocks"][layer_idx] = measure_result elif op_type == LinearLayer: _, input_size, in_channels, out_channels, kernel_size, stride = config in_channels = int(round(in_channels * self.multiplier)) out_channels = int(round(out_channels * self.multiplier)) build_config = { # 'name': LinearLayer.__name__, "in_features": in_channels, "out_features": out_channels, } layer = LinearLayer.build_from_config(build_config) input_shape = (batch_size, in_channels) if self.pred_type == "flops": measure_result = ( self.measure_single_layer_flops(layer, input_shape) / batch_size ) elif self.pred_type == "latency": measure_result = self.measure_single_layer_latency( layer, input_shape ) efficiency_dict["other_blocks"][layer_idx] = measure_result else: raise NotImplementedError self.efficiency_dict[base_resolution] = efficiency_dict print( "Built the %s lookup table (resolution=%d)!" % (self.pred_type, base_resolution) ) return efficiency_dict def predict_efficiency(self, sample): input_size = sample.get("r", [224]) input_size = input_size[0] assert "ks" in sample and "e" in sample and "d" in sample assert len(sample["ks"]) == len(sample["e"]) and len(sample["ks"]) == 20 assert len(sample["d"]) == 5 total_stats = 0.0 for i in range(20): stage = i // 4 depth_max = sample["d"][stage] depth = i % 4 + 1 if depth > depth_max: continue ks, e = sample["ks"][i], sample["e"][i] total_stats += self.efficiency_dict[input_size]["mobile_inverted_blocks"][ i + 1 ][(ks, e)] for key in self.efficiency_dict[input_size]["other_blocks"]: total_stats += self.efficiency_dict[input_size]["other_blocks"][key] total_stats += self.efficiency_dict[input_size]["mobile_inverted_blocks"][0][ (3, 1) ] return total_stats
import os.path as osp import numpy as np import math from tqdm import tqdm import torch.nn as nn import torch.backends.cudnn as cudnn import torch.utils.data from torchvision import transforms, datasets from ofa.utils import AverageMeter, accuracy from ofa.model_zoo import ofa_specialized from ofa.imagenet_classification.elastic_nn.utils import set_running_statistics def evaluate_ofa_subnet( ofa_net, path, net_config, data_loader, batch_size, device="cuda:0" ): assert "ks" in net_config and "d" in net_config and "e" in net_config assert ( len(net_config["ks"]) == 20 and len(net_config["e"]) == 20 and len(net_config["d"]) == 5 ) ofa_net.set_active_subnet(ks=net_config["ks"], d=net_config["d"], e=net_config["e"]) subnet = ofa_net.get_active_subnet().to(device) calib_bn(subnet, path, net_config["r"][0], batch_size) top1 = validate(subnet, path, net_config["r"][0], data_loader, batch_size, device) return top1 def calib_bn(net, path, image_size, batch_size, num_images=2000): # print('Creating dataloader for resetting BN running statistics...') dataset = datasets.ImageFolder( osp.join(path, "train"), transforms.Compose( [ transforms.RandomResizedCrop(image_size), transforms.RandomHorizontalFlip(), transforms.ColorJitter(brightness=32.0 / 255.0, saturation=0.5), transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ), ] ), ) chosen_indexes = np.random.choice(list(range(len(dataset))), num_images) sub_sampler = torch.utils.data.sampler.SubsetRandomSampler(chosen_indexes) data_loader = torch.utils.data.DataLoader( dataset, sampler=sub_sampler, batch_size=batch_size, num_workers=16, pin_memory=True, drop_last=False, ) # print('Resetting BN running statistics (this may take 10-20 seconds)...') set_running_statistics(net, data_loader) def validate(net, path, image_size, data_loader, batch_size=100, device="cuda:0"): if "cuda" in device: net = torch.nn.DataParallel(net).to(device) else: net = net.to(device) data_loader.dataset.transform = transforms.Compose( [ transforms.Resize(int(math.ceil(image_size / 0.875))), transforms.CenterCrop(image_size), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ] ) cudnn.benchmark = True criterion = nn.CrossEntropyLoss().to(device) net.eval() net = net.to(device) losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() with torch.no_grad(): with tqdm(total=len(data_loader), desc="Validate") as t: for i, (images, labels) in enumerate(data_loader): images, labels = images.to(device), labels.to(device) # compute output output = net(images) loss = criterion(output, labels) # measure accuracy and record loss acc1, acc5 = accuracy(output, labels, topk=(1, 5)) losses.update(loss.item(), images.size(0)) top1.update(acc1[0].item(), images.size(0)) top5.update(acc5[0].item(), images.size(0)) t.set_postfix( { "loss": losses.avg, "top1": top1.avg, "top5": top5.avg, "img_size": images.size(2), } ) t.update(1) print( "Results: loss=%.5f,\t top1=%.1f,\t top5=%.1f" % (losses.avg, top1.avg, top5.avg) ) return top1.avg def evaluate_ofa_specialized(path, data_loader, batch_size=100, device="cuda:0"): def select_platform_name(): valid_platform_name = [ "pixel1", "pixel2", "note10", "note8", "s7edge", "lg-g8", "1080ti", "v100", "tx2", "cpu", "flops", ] print( "Please select a hardware platform from ('pixel1', 'pixel2', 'note10', 'note8', 's7edge', 'lg-g8', '1080ti', 'v100', 'tx2', 'cpu', 'flops')!\n" ) while True: platform_name = input() platform_name = platform_name.lower() if platform_name in valid_platform_name: return platform_name print( "Platform name is invalid! Please select in ('pixel1', 'pixel2', 'note10', 'note8', 's7edge', 'lg-g8', '1080ti', 'v100', 'tx2', 'cpu', 'flops')!\n" ) def select_netid(platform_name): platform_efficiency_map = { "pixel1": { 143: "pixel1_lat@[email protected]_finetune@75", 132: "pixel1_lat@[email protected]_finetune@75", 79: "pixel1_lat@[email protected]_finetune@75", 58: "pixel1_lat@[email protected]_finetune@75", 40: "pixel1_lat@[email protected]_finetune@25", 28: "pixel1_lat@[email protected]_finetune@25", 20: "pixel1_lat@[email protected]_finetune@25", }, "pixel2": { 62: "pixel2_lat@[email protected]_finetune@25", 50: "pixel2_lat@[email protected]_finetune@25", 35: "pixel2_lat@[email protected]_finetune@25", 25: "pixel2_lat@[email protected]_finetune@25", }, "note10": { 64: "note10_lat@[email protected]_finetune@75", 50: "note10_lat@[email protected]_finetune@75", 41: "note10_lat@[email protected]_finetune@75", 30: "note10_lat@[email protected]_finetune@75", 22: "note10_lat@[email protected]_finetune@25", 16: "note10_lat@[email protected]_finetune@25", 11: "note10_lat@[email protected]_finetune@25", 8: "note10_lat@[email protected]_finetune@25", }, "note8": { 65: "note8_lat@[email protected]_finetune@25", 49: "note8_lat@[email protected]_finetune@25", 31: "note8_lat@[email protected]_finetune@25", 22: "note8_lat@[email protected]_finetune@25", }, "s7edge": { 88: "s7edge_lat@[email protected]_finetune@25", 58: "s7edge_lat@[email protected]_finetune@25", 41: "s7edge_lat@[email protected]_finetune@25", 29: "s7edge_lat@[email protected]_finetune@25", }, "lg-g8": { 24: "LG-G8_lat@[email protected]_finetune@25", 16: "LG-G8_lat@[email protected]_finetune@25", 11: "LG-G8_lat@[email protected]_finetune@25", 8: "LG-G8_lat@[email protected]_finetune@25", }, "1080ti": { 27: "1080ti_gpu64@[email protected]_finetune@25", 22: "1080ti_gpu64@[email protected]_finetune@25", 15: "1080ti_gpu64@[email protected]_finetune@25", 12: "1080ti_gpu64@[email protected]_finetune@25", }, "v100": { 11: "v100_gpu64@[email protected]_finetune@25", 9: "v100_gpu64@[email protected]_finetune@25", 6: "v100_gpu64@[email protected]_finetune@25", 5: "v100_gpu64@[email protected]_finetune@25", }, "tx2": { 96: "tx2_gpu16@[email protected]_finetune@25", 80: "tx2_gpu16@[email protected]_finetune@25", 47: "tx2_gpu16@[email protected]_finetune@25", 35: "tx2_gpu16@[email protected]_finetune@25", }, "cpu": { 17: "cpu_lat@[email protected]_finetune@25", 15: "cpu_lat@[email protected]_finetune@25", 11: "cpu_lat@[email protected]_finetune@25", 10: "cpu_lat@[email protected]_finetune@25", }, "flops": { 595: "flops@[email protected]_finetune@75", 482: "flops@[email protected]_finetune@75", 389: "flops@[email protected]_finetune@75", }, } sub_efficiency_map = platform_efficiency_map[platform_name] if not platform_name == "flops": print( "Now, please specify a latency constraint for model specialization among", sorted(list(sub_efficiency_map.keys())), "ms. (Please just input the number.) \n", ) else: print( "Now, please specify a FLOPs constraint for model specialization among", sorted(list(sub_efficiency_map.keys())), "MFLOPs. (Please just input the number.) \n", ) while True: efficiency_constraint = input() if not efficiency_constraint.isdigit(): print("Sorry, please input an integer! \n") continue efficiency_constraint = int(efficiency_constraint) if not efficiency_constraint in sub_efficiency_map.keys(): print( "Sorry, please choose a value from: ", sorted(list(sub_efficiency_map.keys())), ".\n", ) continue return sub_efficiency_map[efficiency_constraint] platform_name = select_platform_name() net_id = select_netid(platform_name) net, image_size = ofa_specialized(net_id=net_id, pretrained=True) validate(net, path, image_size, data_loader, batch_size, device) return net_id
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import os import copy from .latency_lookup_table import * class BaseEfficiencyModel: def __init__(self, ofa_net): self.ofa_net = ofa_net def get_active_subnet_config(self, arch_dict): arch_dict = copy.deepcopy(arch_dict) image_size = arch_dict.pop("image_size") self.ofa_net.set_active_subnet(**arch_dict) active_net_config = self.ofa_net.get_active_net_config() return active_net_config, image_size def get_efficiency(self, arch_dict): raise NotImplementedError class ProxylessNASFLOPsModel(BaseEfficiencyModel): def get_efficiency(self, arch_dict): active_net_config, image_size = self.get_active_subnet_config(arch_dict) return ProxylessNASLatencyTable.count_flops_given_config( active_net_config, image_size ) class Mbv3FLOPsModel(BaseEfficiencyModel): def get_efficiency(self, arch_dict): active_net_config, image_size = self.get_active_subnet_config(arch_dict) return MBv3LatencyTable.count_flops_given_config(active_net_config, image_size) class ResNet50FLOPsModel(BaseEfficiencyModel): def get_efficiency(self, arch_dict): active_net_config, image_size = self.get_active_subnet_config(arch_dict) return ResNet50LatencyTable.count_flops_given_config( active_net_config, image_size ) class ProxylessNASLatencyModel(BaseEfficiencyModel): def __init__(self, ofa_net, lookup_table_path_dict): super(ProxylessNASLatencyModel, self).__init__(ofa_net) self.latency_tables = {} for image_size, path in lookup_table_path_dict.items(): self.latency_tables[image_size] = ProxylessNASLatencyTable( local_dir="/tmp/.ofa_latency_tools/", url=os.path.join(path, "%d_lookup_table.yaml" % image_size), ) def get_efficiency(self, arch_dict): active_net_config, image_size = self.get_active_subnet_config(arch_dict) return self.latency_tables[image_size].predict_network_latency_given_config( active_net_config, image_size ) class Mbv3LatencyModel(BaseEfficiencyModel): def __init__(self, ofa_net, lookup_table_path_dict): super(Mbv3LatencyModel, self).__init__(ofa_net) self.latency_tables = {} for image_size, path in lookup_table_path_dict.items(): self.latency_tables[image_size] = MBv3LatencyTable( local_dir="/tmp/.ofa_latency_tools/", url=os.path.join(path, "%d_lookup_table.yaml" % image_size), ) def get_efficiency(self, arch_dict): active_net_config, image_size = self.get_active_subnet_config(arch_dict) return self.latency_tables[image_size].predict_network_latency_given_config( active_net_config, image_size )
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import yaml from ofa.utils import download_url, make_divisible, MyNetwork __all__ = [ "count_conv_flop", "ProxylessNASLatencyTable", "MBv3LatencyTable", "ResNet50LatencyTable", ] def count_conv_flop(out_size, in_channels, out_channels, kernel_size, groups): out_h = out_w = out_size delta_ops = ( in_channels * out_channels * kernel_size * kernel_size * out_h * out_w / groups ) return delta_ops class LatencyTable(object): def __init__( self, local_dir="~/.ofa/latency_tools/", url="https://hanlab.mit.edu/files/proxylessNAS/LatencyTools/mobile_trim.yaml", ): if url.startswith("http"): fname = download_url(url, local_dir, overwrite=True) else: fname = url with open(fname, "r") as fp: self.lut = yaml.load(fp) @staticmethod def repr_shape(shape): if isinstance(shape, (list, tuple)): return "x".join(str(_) for _ in shape) elif isinstance(shape, str): return shape else: return TypeError def query(self, **kwargs): raise NotImplementedError def predict_network_latency(self, net, image_size): raise NotImplementedError def predict_network_latency_given_config(self, net_config, image_size): raise NotImplementedError @staticmethod def count_flops_given_config(net_config, image_size=224): raise NotImplementedError class ProxylessNASLatencyTable(LatencyTable): def query( self, l_type: str, input_shape, output_shape, expand=None, ks=None, stride=None, id_skip=None, ): """ :param l_type: Layer type must be one of the followings 1. `Conv`: The initial 3x3 conv with stride 2. 2. `Conv_1`: feature_mix_layer 3. `Logits`: All operations after `Conv_1`. 4. `expanded_conv`: MobileInvertedResidual :param input_shape: input shape (h, w, #channels) :param output_shape: output shape (h, w, #channels) :param expand: expansion ratio :param ks: kernel size :param stride: :param id_skip: indicate whether has the residual connection """ infos = [ l_type, "input:%s" % self.repr_shape(input_shape), "output:%s" % self.repr_shape(output_shape), ] if l_type in ("expanded_conv",): assert None not in (expand, ks, stride, id_skip) infos += [ "expand:%d" % expand, "kernel:%d" % ks, "stride:%d" % stride, "idskip:%d" % id_skip, ] key = "-".join(infos) return self.lut[key]["mean"] def predict_network_latency(self, net, image_size=224): predicted_latency = 0 # first conv predicted_latency += self.query( "Conv", [image_size, image_size, 3], [(image_size + 1) // 2, (image_size + 1) // 2, net.first_conv.out_channels], ) # blocks fsize = (image_size + 1) // 2 for block in net.blocks: mb_conv = block.conv shortcut = block.shortcut if mb_conv is None: continue if shortcut is None: idskip = 0 else: idskip = 1 out_fz = int((fsize - 1) / mb_conv.stride + 1) # fsize // mb_conv.stride block_latency = self.query( "expanded_conv", [fsize, fsize, mb_conv.in_channels], [out_fz, out_fz, mb_conv.out_channels], expand=mb_conv.expand_ratio, ks=mb_conv.kernel_size, stride=mb_conv.stride, id_skip=idskip, ) predicted_latency += block_latency fsize = out_fz # feature mix layer predicted_latency += self.query( "Conv_1", [fsize, fsize, net.feature_mix_layer.in_channels], [fsize, fsize, net.feature_mix_layer.out_channels], ) # classifier predicted_latency += self.query( "Logits", [fsize, fsize, net.classifier.in_features], [net.classifier.out_features], # 1000 ) return predicted_latency def predict_network_latency_given_config(self, net_config, image_size=224): predicted_latency = 0 # first conv predicted_latency += self.query( "Conv", [image_size, image_size, 3], [ (image_size + 1) // 2, (image_size + 1) // 2, net_config["first_conv"]["out_channels"], ], ) # blocks fsize = (image_size + 1) // 2 for block in net_config["blocks"]: mb_conv = ( block["mobile_inverted_conv"] if "mobile_inverted_conv" in block else block["conv"] ) shortcut = block["shortcut"] if mb_conv is None: continue if shortcut is None: idskip = 0 else: idskip = 1 out_fz = int((fsize - 1) / mb_conv["stride"] + 1) block_latency = self.query( "expanded_conv", [fsize, fsize, mb_conv["in_channels"]], [out_fz, out_fz, mb_conv["out_channels"]], expand=mb_conv["expand_ratio"], ks=mb_conv["kernel_size"], stride=mb_conv["stride"], id_skip=idskip, ) predicted_latency += block_latency fsize = out_fz # feature mix layer predicted_latency += self.query( "Conv_1", [fsize, fsize, net_config["feature_mix_layer"]["in_channels"]], [fsize, fsize, net_config["feature_mix_layer"]["out_channels"]], ) # classifier predicted_latency += self.query( "Logits", [fsize, fsize, net_config["classifier"]["in_features"]], [net_config["classifier"]["out_features"]], # 1000 ) return predicted_latency @staticmethod def count_flops_given_config(net_config, image_size=224): flops = 0 # first conv flops += count_conv_flop( (image_size + 1) // 2, 3, net_config["first_conv"]["out_channels"], 3, 1 ) # blocks fsize = (image_size + 1) // 2 for block in net_config["blocks"]: mb_conv = ( block["mobile_inverted_conv"] if "mobile_inverted_conv" in block else block["conv"] ) if mb_conv is None: continue out_fz = int((fsize - 1) / mb_conv["stride"] + 1) if mb_conv["mid_channels"] is None: mb_conv["mid_channels"] = round( mb_conv["in_channels"] * mb_conv["expand_ratio"] ) if mb_conv["expand_ratio"] != 1: # inverted bottleneck flops += count_conv_flop( fsize, mb_conv["in_channels"], mb_conv["mid_channels"], 1, 1 ) # depth conv flops += count_conv_flop( out_fz, mb_conv["mid_channels"], mb_conv["mid_channels"], mb_conv["kernel_size"], mb_conv["mid_channels"], ) # point linear flops += count_conv_flop( out_fz, mb_conv["mid_channels"], mb_conv["out_channels"], 1, 1 ) fsize = out_fz # feature mix layer flops += count_conv_flop( fsize, net_config["feature_mix_layer"]["in_channels"], net_config["feature_mix_layer"]["out_channels"], 1, 1, ) # classifier flops += count_conv_flop( 1, net_config["classifier"]["in_features"], net_config["classifier"]["out_features"], 1, 1, ) return flops / 1e6 # MFLOPs class MBv3LatencyTable(LatencyTable): def query( self, l_type: str, input_shape, output_shape, mid=None, ks=None, stride=None, id_skip=None, se=None, h_swish=None, ): infos = [ l_type, "input:%s" % self.repr_shape(input_shape), "output:%s" % self.repr_shape(output_shape), ] if l_type in ("expanded_conv",): assert None not in (mid, ks, stride, id_skip, se, h_swish) infos += [ "expand:%d" % mid, "kernel:%d" % ks, "stride:%d" % stride, "idskip:%d" % id_skip, "se:%d" % se, "hs:%d" % h_swish, ] key = "-".join(infos) return self.lut[key]["mean"] def predict_network_latency(self, net, image_size=224): predicted_latency = 0 # first conv predicted_latency += self.query( "Conv", [image_size, image_size, 3], [(image_size + 1) // 2, (image_size + 1) // 2, net.first_conv.out_channels], ) # blocks fsize = (image_size + 1) // 2 for block in net.blocks: mb_conv = block.conv shortcut = block.shortcut if mb_conv is None: continue if shortcut is None: idskip = 0 else: idskip = 1 out_fz = int((fsize - 1) / mb_conv.stride + 1) block_latency = self.query( "expanded_conv", [fsize, fsize, mb_conv.in_channels], [out_fz, out_fz, mb_conv.out_channels], mid=mb_conv.depth_conv.conv.in_channels, ks=mb_conv.kernel_size, stride=mb_conv.stride, id_skip=idskip, se=1 if mb_conv.use_se else 0, h_swish=1 if mb_conv.act_func == "h_swish" else 0, ) predicted_latency += block_latency fsize = out_fz # final expand layer predicted_latency += self.query( "Conv_1", [fsize, fsize, net.final_expand_layer.in_channels], [fsize, fsize, net.final_expand_layer.out_channels], ) # global average pooling predicted_latency += self.query( "AvgPool2D", [fsize, fsize, net.final_expand_layer.out_channels], [1, 1, net.final_expand_layer.out_channels], ) # feature mix layer predicted_latency += self.query( "Conv_2", [1, 1, net.feature_mix_layer.in_channels], [1, 1, net.feature_mix_layer.out_channels], ) # classifier predicted_latency += self.query( "Logits", [1, 1, net.classifier.in_features], [net.classifier.out_features] ) return predicted_latency def predict_network_latency_given_config(self, net_config, image_size=224): predicted_latency = 0 # first conv predicted_latency += self.query( "Conv", [image_size, image_size, 3], [ (image_size + 1) // 2, (image_size + 1) // 2, net_config["first_conv"]["out_channels"], ], ) # blocks fsize = (image_size + 1) // 2 for block in net_config["blocks"]: mb_conv = ( block["mobile_inverted_conv"] if "mobile_inverted_conv" in block else block["conv"] ) shortcut = block["shortcut"] if mb_conv is None: continue if shortcut is None: idskip = 0 else: idskip = 1 out_fz = int((fsize - 1) / mb_conv["stride"] + 1) if mb_conv["mid_channels"] is None: mb_conv["mid_channels"] = round( mb_conv["in_channels"] * mb_conv["expand_ratio"] ) block_latency = self.query( "expanded_conv", [fsize, fsize, mb_conv["in_channels"]], [out_fz, out_fz, mb_conv["out_channels"]], mid=mb_conv["mid_channels"], ks=mb_conv["kernel_size"], stride=mb_conv["stride"], id_skip=idskip, se=1 if mb_conv["use_se"] else 0, h_swish=1 if mb_conv["act_func"] == "h_swish" else 0, ) predicted_latency += block_latency fsize = out_fz # final expand layer predicted_latency += self.query( "Conv_1", [fsize, fsize, net_config["final_expand_layer"]["in_channels"]], [fsize, fsize, net_config["final_expand_layer"]["out_channels"]], ) # global average pooling predicted_latency += self.query( "AvgPool2D", [fsize, fsize, net_config["final_expand_layer"]["out_channels"]], [1, 1, net_config["final_expand_layer"]["out_channels"]], ) # feature mix layer predicted_latency += self.query( "Conv_2", [1, 1, net_config["feature_mix_layer"]["in_channels"]], [1, 1, net_config["feature_mix_layer"]["out_channels"]], ) # classifier predicted_latency += self.query( "Logits", [1, 1, net_config["classifier"]["in_features"]], [net_config["classifier"]["out_features"]], ) return predicted_latency @staticmethod def count_flops_given_config(net_config, image_size=224): flops = 0 # first conv flops += count_conv_flop( (image_size + 1) // 2, 3, net_config["first_conv"]["out_channels"], 3, 1 ) # blocks fsize = (image_size + 1) // 2 for block in net_config["blocks"]: mb_conv = ( block["mobile_inverted_conv"] if "mobile_inverted_conv" in block else block["conv"] ) if mb_conv is None: continue out_fz = int((fsize - 1) / mb_conv["stride"] + 1) if mb_conv["mid_channels"] is None: mb_conv["mid_channels"] = round( mb_conv["in_channels"] * mb_conv["expand_ratio"] ) if mb_conv["expand_ratio"] != 1: # inverted bottleneck flops += count_conv_flop( fsize, mb_conv["in_channels"], mb_conv["mid_channels"], 1, 1 ) # depth conv flops += count_conv_flop( out_fz, mb_conv["mid_channels"], mb_conv["mid_channels"], mb_conv["kernel_size"], mb_conv["mid_channels"], ) if mb_conv["use_se"]: # SE layer se_mid = make_divisible( mb_conv["mid_channels"] // 4, divisor=MyNetwork.CHANNEL_DIVISIBLE ) flops += count_conv_flop(1, mb_conv["mid_channels"], se_mid, 1, 1) flops += count_conv_flop(1, se_mid, mb_conv["mid_channels"], 1, 1) # point linear flops += count_conv_flop( out_fz, mb_conv["mid_channels"], mb_conv["out_channels"], 1, 1 ) fsize = out_fz # final expand layer flops += count_conv_flop( fsize, net_config["final_expand_layer"]["in_channels"], net_config["final_expand_layer"]["out_channels"], 1, 1, ) # feature mix layer flops += count_conv_flop( 1, net_config["feature_mix_layer"]["in_channels"], net_config["feature_mix_layer"]["out_channels"], 1, 1, ) # classifier flops += count_conv_flop( 1, net_config["classifier"]["in_features"], net_config["classifier"]["out_features"], 1, 1, ) return flops / 1e6 # MFLOPs class ResNet50LatencyTable(LatencyTable): def query(self, **kwargs): raise NotImplementedError def predict_network_latency(self, net, image_size): raise NotImplementedError def predict_network_latency_given_config(self, net_config, image_size): raise NotImplementedError @staticmethod def count_flops_given_config(net_config, image_size=224): flops = 0 # input stem for layer_config in net_config["input_stem"]: if layer_config["name"] != "ConvLayer": layer_config = layer_config["conv"] in_channel = layer_config["in_channels"] out_channel = layer_config["out_channels"] out_image_size = int((image_size - 1) / layer_config["stride"] + 1) flops += count_conv_flop( out_image_size, in_channel, out_channel, layer_config["kernel_size"], layer_config.get("groups", 1), ) image_size = out_image_size # max pooling image_size = int((image_size - 1) / 2 + 1) # ResNetBottleneckBlocks for block_config in net_config["blocks"]: in_channel = block_config["in_channels"] out_channel = block_config["out_channels"] out_image_size = int((image_size - 1) / block_config["stride"] + 1) mid_channel = ( block_config["mid_channels"] if block_config["mid_channels"] is not None else round(out_channel * block_config["expand_ratio"]) ) mid_channel = make_divisible(mid_channel, MyNetwork.CHANNEL_DIVISIBLE) # conv1 flops += count_conv_flop(image_size, in_channel, mid_channel, 1, 1) # conv2 flops += count_conv_flop( out_image_size, mid_channel, mid_channel, block_config["kernel_size"], block_config["groups"], ) # conv3 flops += count_conv_flop(out_image_size, mid_channel, out_channel, 1, 1) # downsample if block_config["stride"] == 1 and in_channel == out_channel: pass else: flops += count_conv_flop(out_image_size, in_channel, out_channel, 1, 1) image_size = out_image_size # final classifier flops += count_conv_flop( 1, net_config["classifier"]["in_features"], net_config["classifier"]["out_features"], 1, 1, ) return flops / 1e6 # MFLOPs
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import copy import random import numpy as np from tqdm import tqdm __all__ = ["EvolutionFinder"] class EvolutionFinder: def __init__(self, efficiency_predictor, accuracy_predictor, **kwargs): self.efficiency_predictor = efficiency_predictor self.accuracy_predictor = accuracy_predictor # evolution hyper-parameters self.arch_mutate_prob = kwargs.get("arch_mutate_prob", 0.1) self.resolution_mutate_prob = kwargs.get("resolution_mutate_prob", 0.5) self.population_size = kwargs.get("population_size", 100) self.max_time_budget = kwargs.get("max_time_budget", 500) self.parent_ratio = kwargs.get("parent_ratio", 0.25) self.mutation_ratio = kwargs.get("mutation_ratio", 0.5) @property def arch_manager(self): return self.accuracy_predictor.arch_encoder def update_hyper_params(self, new_param_dict): self.__dict__.update(new_param_dict) def random_valid_sample(self, constraint): while True: sample = self.arch_manager.random_sample_arch() efficiency = self.efficiency_predictor.get_efficiency(sample) if efficiency <= constraint: return sample, efficiency def mutate_sample(self, sample, constraint): while True: new_sample = copy.deepcopy(sample) self.arch_manager.mutate_resolution(new_sample, self.resolution_mutate_prob) self.arch_manager.mutate_arch(new_sample, self.arch_mutate_prob) efficiency = self.efficiency_predictor.get_efficiency(new_sample) if efficiency <= constraint: return new_sample, efficiency def crossover_sample(self, sample1, sample2, constraint): while True: new_sample = copy.deepcopy(sample1) for key in new_sample.keys(): if not isinstance(new_sample[key], list): new_sample[key] = random.choice([sample1[key], sample2[key]]) else: for i in range(len(new_sample[key])): new_sample[key][i] = random.choice( [sample1[key][i], sample2[key][i]] ) efficiency = self.efficiency_predictor.get_efficiency(new_sample) if efficiency <= constraint: return new_sample, efficiency def run_evolution_search(self, constraint, verbose=False, **kwargs): """Run a single roll-out of regularized evolution to a fixed time budget.""" self.update_hyper_params(kwargs) mutation_numbers = int(round(self.mutation_ratio * self.population_size)) parents_size = int(round(self.parent_ratio * self.population_size)) best_valids = [-100] population = [] # (validation, sample, latency) tuples child_pool = [] efficiency_pool = [] best_info = None if verbose: print("Generate random population...") for _ in range(self.population_size): sample, efficiency = self.random_valid_sample(constraint) child_pool.append(sample) efficiency_pool.append(efficiency) accs = self.accuracy_predictor.predict_acc(child_pool) for i in range(self.population_size): population.append((accs[i].item(), child_pool[i], efficiency_pool[i])) if verbose: print("Start Evolution...") # After the population is seeded, proceed with evolving the population. with tqdm( total=self.max_time_budget, desc="Searching with constraint (%s)" % constraint, disable=(not verbose), ) as t: for i in range(self.max_time_budget): parents = sorted(population, key=lambda x: x[0])[::-1][:parents_size] acc = parents[0][0] t.set_postfix({"acc": parents[0][0]}) if not verbose and (i + 1) % 100 == 0: print("Iter: {} Acc: {}".format(i + 1, parents[0][0])) if acc > best_valids[-1]: best_valids.append(acc) best_info = parents[0] else: best_valids.append(best_valids[-1]) population = parents child_pool = [] efficiency_pool = [] for j in range(mutation_numbers): par_sample = population[np.random.randint(parents_size)][1] # Mutate new_sample, efficiency = self.mutate_sample(par_sample, constraint) child_pool.append(new_sample) efficiency_pool.append(efficiency) for j in range(self.population_size - mutation_numbers): par_sample1 = population[np.random.randint(parents_size)][1] par_sample2 = population[np.random.randint(parents_size)][1] # Crossover new_sample, efficiency = self.crossover_sample( par_sample1, par_sample2, constraint ) child_pool.append(new_sample) efficiency_pool.append(efficiency) accs = self.accuracy_predictor.predict_acc(child_pool) for j in range(self.population_size): population.append( (accs[j].item(), child_pool[j], efficiency_pool[j]) ) t.update(1) return best_valids, best_info
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. from .evolution import *
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. from .acc_dataset import * from .acc_predictor import * from .arch_encoder import *
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import os import numpy as np import torch import torch.nn as nn __all__ = ["AccuracyPredictor"] class AccuracyPredictor(nn.Module): def __init__( self, arch_encoder, hidden_size=400, n_layers=3, checkpoint_path=None, device="cuda:0", ): super(AccuracyPredictor, self).__init__() self.arch_encoder = arch_encoder self.hidden_size = hidden_size self.n_layers = n_layers self.device = device # build layers layers = [] for i in range(self.n_layers): layers.append( nn.Sequential( nn.Linear( self.arch_encoder.n_dim if i == 0 else self.hidden_size, self.hidden_size, ), nn.ReLU(inplace=True), ) ) layers.append(nn.Linear(self.hidden_size, 1, bias=False)) self.layers = nn.Sequential(*layers) self.base_acc = nn.Parameter( torch.zeros(1, device=self.device), requires_grad=False ) if checkpoint_path is not None and os.path.exists(checkpoint_path): checkpoint = torch.load(checkpoint_path, map_location="cpu") if "state_dict" in checkpoint: checkpoint = checkpoint["state_dict"] self.load_state_dict(checkpoint) print("Loaded checkpoint from %s" % checkpoint_path) self.layers = self.layers.to(self.device) def forward(self, x): y = self.layers(x).squeeze() return y + self.base_acc def predict_acc(self, arch_dict_list): X = [self.arch_encoder.arch2feature(arch_dict) for arch_dict in arch_dict_list] X = torch.tensor(np.array(X)).float().to(self.device) return self.forward(X)
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import os import json import numpy as np from tqdm import tqdm import torch import torch.utils.data from ofa.utils import list_mean __all__ = ["net_setting2id", "net_id2setting", "AccuracyDataset"] def net_setting2id(net_setting): return json.dumps(net_setting) def net_id2setting(net_id): return json.loads(net_id) class RegDataset(torch.utils.data.Dataset): def __init__(self, inputs, targets): super(RegDataset, self).__init__() self.inputs = inputs self.targets = targets def __getitem__(self, index): return self.inputs[index], self.targets[index] def __len__(self): return self.inputs.size(0) class AccuracyDataset: def __init__(self, path): self.path = path os.makedirs(self.path, exist_ok=True) @property def net_id_path(self): return os.path.join(self.path, "net_id.dict") @property def acc_src_folder(self): return os.path.join(self.path, "src") @property def acc_dict_path(self): return os.path.join(self.path, "acc.dict") # TODO: support parallel building def build_acc_dataset( self, run_manager, ofa_network, n_arch=1000, image_size_list=None ): # load net_id_list, random sample if not exist if os.path.isfile(self.net_id_path): net_id_list = json.load(open(self.net_id_path)) else: net_id_list = set() while len(net_id_list) < n_arch: net_setting = ofa_network.sample_active_subnet() net_id = net_setting2id(net_setting) net_id_list.add(net_id) net_id_list = list(net_id_list) net_id_list.sort() json.dump(net_id_list, open(self.net_id_path, "w"), indent=4) image_size_list = ( [128, 160, 192, 224] if image_size_list is None else image_size_list ) with tqdm( total=len(net_id_list) * len(image_size_list), desc="Building Acc Dataset" ) as t: for image_size in image_size_list: # load val dataset into memory val_dataset = [] run_manager.run_config.data_provider.assign_active_img_size(image_size) for images, labels in run_manager.run_config.valid_loader: val_dataset.append((images, labels)) # save path os.makedirs(self.acc_src_folder, exist_ok=True) acc_save_path = os.path.join( self.acc_src_folder, "%d.dict" % image_size ) acc_dict = {} # load existing acc dict if os.path.isfile(acc_save_path): existing_acc_dict = json.load(open(acc_save_path, "r")) else: existing_acc_dict = {} for net_id in net_id_list: net_setting = net_id2setting(net_id) key = net_setting2id({**net_setting, "image_size": image_size}) if key in existing_acc_dict: acc_dict[key] = existing_acc_dict[key] t.set_postfix( { "net_id": net_id, "image_size": image_size, "info_val": acc_dict[key], "status": "loading", } ) t.update() continue ofa_network.set_active_subnet(**net_setting) run_manager.reset_running_statistics(ofa_network) net_setting_str = ",".join( [ "%s_%s" % ( key, "%.1f" % list_mean(val) if isinstance(val, list) else val, ) for key, val in net_setting.items() ] ) loss, (top1, top5) = run_manager.validate( run_str=net_setting_str, net=ofa_network, data_loader=val_dataset, no_logs=True, ) info_val = top1 t.set_postfix( { "net_id": net_id, "image_size": image_size, "info_val": info_val, } ) t.update() acc_dict.update({key: info_val}) json.dump(acc_dict, open(acc_save_path, "w"), indent=4) def merge_acc_dataset(self, image_size_list=None): # load existing data merged_acc_dict = {} for fname in os.listdir(self.acc_src_folder): if ".dict" not in fname: continue image_size = int(fname.split(".dict")[0]) if image_size_list is not None and image_size not in image_size_list: print("Skip ", fname) continue full_path = os.path.join(self.acc_src_folder, fname) partial_acc_dict = json.load(open(full_path)) merged_acc_dict.update(partial_acc_dict) print("loaded %s" % full_path) json.dump(merged_acc_dict, open(self.acc_dict_path, "w"), indent=4) return merged_acc_dict def build_acc_data_loader( self, arch_encoder, n_training_sample=None, batch_size=256, n_workers=16 ): # load data acc_dict = json.load(open(self.acc_dict_path)) X_all = [] Y_all = [] with tqdm(total=len(acc_dict), desc="Loading data") as t: for k, v in acc_dict.items(): dic = json.loads(k) X_all.append(arch_encoder.arch2feature(dic)) Y_all.append(v / 100.0) # range: 0 - 1 t.update() base_acc = np.mean(Y_all) # convert to torch tensor X_all = torch.tensor(X_all, dtype=torch.float) Y_all = torch.tensor(Y_all) # random shuffle shuffle_idx = torch.randperm(len(X_all)) X_all = X_all[shuffle_idx] Y_all = Y_all[shuffle_idx] # split data idx = X_all.size(0) // 5 * 4 if n_training_sample is None else n_training_sample val_idx = X_all.size(0) // 5 * 4 X_train, Y_train = X_all[:idx], Y_all[:idx] X_test, Y_test = X_all[val_idx:], Y_all[val_idx:] print("Train Size: %d," % len(X_train), "Valid Size: %d" % len(X_test)) # build data loader train_dataset = RegDataset(X_train, Y_train) val_dataset = RegDataset(X_test, Y_test) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batch_size, shuffle=True, pin_memory=False, num_workers=n_workers, ) valid_loader = torch.utils.data.DataLoader( val_dataset, batch_size=batch_size, shuffle=False, pin_memory=False, num_workers=n_workers, ) return train_loader, valid_loader, base_acc
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import random import numpy as np from ofa.imagenet_classification.networks import ResNets __all__ = ["MobileNetArchEncoder", "ResNetArchEncoder"] class MobileNetArchEncoder: SPACE_TYPE = "mbv3" def __init__( self, image_size_list=None, ks_list=None, expand_list=None, depth_list=None, n_stage=None, ): self.image_size_list = [224] if image_size_list is None else image_size_list self.ks_list = [3, 5, 7] if ks_list is None else ks_list self.expand_list = ( [3, 4, 6] if expand_list is None else [int(expand) for expand in expand_list] ) self.depth_list = [2, 3, 4] if depth_list is None else depth_list if n_stage is not None: self.n_stage = n_stage elif self.SPACE_TYPE == "mbv2": self.n_stage = 6 elif self.SPACE_TYPE == "mbv3": self.n_stage = 5 else: raise NotImplementedError # build info dict self.n_dim = 0 self.r_info = dict(id2val={}, val2id={}, L=[], R=[]) self._build_info_dict(target="r") self.k_info = dict(id2val=[], val2id=[], L=[], R=[]) self.e_info = dict(id2val=[], val2id=[], L=[], R=[]) self._build_info_dict(target="k") self._build_info_dict(target="e") @property def max_n_blocks(self): if self.SPACE_TYPE == "mbv3": return self.n_stage * max(self.depth_list) elif self.SPACE_TYPE == "mbv2": return (self.n_stage - 1) * max(self.depth_list) + 1 else: raise NotImplementedError def _build_info_dict(self, target): if target == "r": target_dict = self.r_info target_dict["L"].append(self.n_dim) for img_size in self.image_size_list: target_dict["val2id"][img_size] = self.n_dim target_dict["id2val"][self.n_dim] = img_size self.n_dim += 1 target_dict["R"].append(self.n_dim) else: if target == "k": target_dict = self.k_info choices = self.ks_list elif target == "e": target_dict = self.e_info choices = self.expand_list else: raise NotImplementedError for i in range(self.max_n_blocks): target_dict["val2id"].append({}) target_dict["id2val"].append({}) target_dict["L"].append(self.n_dim) for k in choices: target_dict["val2id"][i][k] = self.n_dim target_dict["id2val"][i][self.n_dim] = k self.n_dim += 1 target_dict["R"].append(self.n_dim) def arch2feature(self, arch_dict): ks, e, d, r = ( arch_dict["ks"], arch_dict["e"], arch_dict["d"], arch_dict["image_size"], ) feature = np.zeros(self.n_dim) for i in range(self.max_n_blocks): nowd = i % max(self.depth_list) stg = i // max(self.depth_list) if nowd < d[stg]: feature[self.k_info["val2id"][i][ks[i]]] = 1 feature[self.e_info["val2id"][i][e[i]]] = 1 feature[self.r_info["val2id"][r]] = 1 return feature def feature2arch(self, feature): img_sz = self.r_info["id2val"][ int(np.argmax(feature[self.r_info["L"][0] : self.r_info["R"][0]])) + self.r_info["L"][0] ] assert img_sz in self.image_size_list arch_dict = {"ks": [], "e": [], "d": [], "image_size": img_sz} d = 0 for i in range(self.max_n_blocks): skip = True for j in range(self.k_info["L"][i], self.k_info["R"][i]): if feature[j] == 1: arch_dict["ks"].append(self.k_info["id2val"][i][j]) skip = False break for j in range(self.e_info["L"][i], self.e_info["R"][i]): if feature[j] == 1: arch_dict["e"].append(self.e_info["id2val"][i][j]) assert not skip skip = False break if skip: arch_dict["e"].append(0) arch_dict["ks"].append(0) else: d += 1 if (i + 1) % max(self.depth_list) == 0 or (i + 1) == self.max_n_blocks: arch_dict["d"].append(d) d = 0 return arch_dict def random_sample_arch(self): return { "ks": random.choices(self.ks_list, k=self.max_n_blocks), "e": random.choices(self.expand_list, k=self.max_n_blocks), "d": random.choices(self.depth_list, k=self.n_stage), "image_size": random.choice(self.image_size_list), } def mutate_resolution(self, arch_dict, mutate_prob): if random.random() < mutate_prob: arch_dict["image_size"] = random.choice(self.image_size_list) return arch_dict def mutate_arch(self, arch_dict, mutate_prob): for i in range(self.max_n_blocks): if random.random() < mutate_prob: arch_dict["ks"][i] = random.choice(self.ks_list) arch_dict["e"][i] = random.choice(self.expand_list) for i in range(self.n_stage): if random.random() < mutate_prob: arch_dict["d"][i] = random.choice(self.depth_list) return arch_dict class ResNetArchEncoder: def __init__( self, image_size_list=None, depth_list=None, expand_list=None, width_mult_list=None, base_depth_list=None, ): self.image_size_list = [224] if image_size_list is None else image_size_list self.expand_list = [0.2, 0.25, 0.35] if expand_list is None else expand_list self.depth_list = [0, 1, 2] if depth_list is None else depth_list self.width_mult_list = ( [0.65, 0.8, 1.0] if width_mult_list is None else width_mult_list ) self.base_depth_list = ( ResNets.BASE_DEPTH_LIST if base_depth_list is None else base_depth_list ) """" build info dict """ self.n_dim = 0 # resolution self.r_info = dict(id2val={}, val2id={}, L=[], R=[]) self._build_info_dict(target="r") # input stem skip self.input_stem_d_info = dict(id2val={}, val2id={}, L=[], R=[]) self._build_info_dict(target="input_stem_d") # width_mult self.width_mult_info = dict(id2val=[], val2id=[], L=[], R=[]) self._build_info_dict(target="width_mult") # expand ratio self.e_info = dict(id2val=[], val2id=[], L=[], R=[]) self._build_info_dict(target="e") @property def n_stage(self): return len(self.base_depth_list) @property def max_n_blocks(self): return sum(self.base_depth_list) + self.n_stage * max(self.depth_list) def _build_info_dict(self, target): if target == "r": target_dict = self.r_info target_dict["L"].append(self.n_dim) for img_size in self.image_size_list: target_dict["val2id"][img_size] = self.n_dim target_dict["id2val"][self.n_dim] = img_size self.n_dim += 1 target_dict["R"].append(self.n_dim) elif target == "input_stem_d": target_dict = self.input_stem_d_info target_dict["L"].append(self.n_dim) for skip in [0, 1]: target_dict["val2id"][skip] = self.n_dim target_dict["id2val"][self.n_dim] = skip self.n_dim += 1 target_dict["R"].append(self.n_dim) elif target == "e": target_dict = self.e_info choices = self.expand_list for i in range(self.max_n_blocks): target_dict["val2id"].append({}) target_dict["id2val"].append({}) target_dict["L"].append(self.n_dim) for e in choices: target_dict["val2id"][i][e] = self.n_dim target_dict["id2val"][i][self.n_dim] = e self.n_dim += 1 target_dict["R"].append(self.n_dim) elif target == "width_mult": target_dict = self.width_mult_info choices = list(range(len(self.width_mult_list))) for i in range(self.n_stage + 2): target_dict["val2id"].append({}) target_dict["id2val"].append({}) target_dict["L"].append(self.n_dim) for w in choices: target_dict["val2id"][i][w] = self.n_dim target_dict["id2val"][i][self.n_dim] = w self.n_dim += 1 target_dict["R"].append(self.n_dim) def arch2feature(self, arch_dict): d, e, w, r = ( arch_dict["d"], arch_dict["e"], arch_dict["w"], arch_dict["image_size"], ) input_stem_skip = 1 if d[0] > 0 else 0 d = d[1:] feature = np.zeros(self.n_dim) feature[self.r_info["val2id"][r]] = 1 feature[self.input_stem_d_info["val2id"][input_stem_skip]] = 1 for i in range(self.n_stage + 2): feature[self.width_mult_info["val2id"][i][w[i]]] = 1 start_pt = 0 for i, base_depth in enumerate(self.base_depth_list): depth = base_depth + d[i] for j in range(start_pt, start_pt + depth): feature[self.e_info["val2id"][j][e[j]]] = 1 start_pt += max(self.depth_list) + base_depth return feature def feature2arch(self, feature): img_sz = self.r_info["id2val"][ int(np.argmax(feature[self.r_info["L"][0] : self.r_info["R"][0]])) + self.r_info["L"][0] ] input_stem_skip = ( self.input_stem_d_info["id2val"][ int( np.argmax( feature[ self.input_stem_d_info["L"][0] : self.input_stem_d_info[ "R" ][0] ] ) ) + self.input_stem_d_info["L"][0] ] * 2 ) assert img_sz in self.image_size_list arch_dict = {"d": [input_stem_skip], "e": [], "w": [], "image_size": img_sz} for i in range(self.n_stage + 2): arch_dict["w"].append( self.width_mult_info["id2val"][i][ int( np.argmax( feature[ self.width_mult_info["L"][i] : self.width_mult_info[ "R" ][i] ] ) ) + self.width_mult_info["L"][i] ] ) d = 0 skipped = 0 stage_id = 0 for i in range(self.max_n_blocks): skip = True for j in range(self.e_info["L"][i], self.e_info["R"][i]): if feature[j] == 1: arch_dict["e"].append(self.e_info["id2val"][i][j]) skip = False break if skip: arch_dict["e"].append(0) skipped += 1 else: d += 1 if ( i + 1 == self.max_n_blocks or (skipped + d) % (max(self.depth_list) + self.base_depth_list[stage_id]) == 0 ): arch_dict["d"].append(d - self.base_depth_list[stage_id]) d, skipped = 0, 0 stage_id += 1 return arch_dict def random_sample_arch(self): return { "d": [random.choice([0, 2])] + random.choices(self.depth_list, k=self.n_stage), "e": random.choices(self.expand_list, k=self.max_n_blocks), "w": random.choices( list(range(len(self.width_mult_list))), k=self.n_stage + 2 ), "image_size": random.choice(self.image_size_list), } def mutate_resolution(self, arch_dict, mutate_prob): if random.random() < mutate_prob: arch_dict["image_size"] = random.choice(self.image_size_list) return arch_dict def mutate_arch(self, arch_dict, mutate_prob): # input stem skip if random.random() < mutate_prob: arch_dict["d"][0] = random.choice([0, 2]) # depth for i in range(1, len(arch_dict["d"])): if random.random() < mutate_prob: arch_dict["d"][i] = random.choice(self.depth_list) # width_mult for i in range(len(arch_dict["w"])): if random.random() < mutate_prob: arch_dict["w"][i] = random.choice( list(range(len(self.width_mult_list))) ) # expand ratio for i in range(len(arch_dict["e"])): if random.random() < mutate_prob: arch_dict["e"][i] = random.choice(self.expand_list)
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import math import torch.nn as nn import torch.nn.functional as F from .common_tools import min_divisible_value __all__ = [ "MyModule", "MyNetwork", "init_models", "set_bn_param", "get_bn_param", "replace_bn_with_gn", "MyConv2d", "replace_conv2d_with_my_conv2d", ] def set_bn_param(net, momentum, eps, gn_channel_per_group=None, ws_eps=None, **kwargs): replace_bn_with_gn(net, gn_channel_per_group) for m in net.modules(): if type(m) in [nn.BatchNorm1d, nn.BatchNorm2d]: m.momentum = momentum m.eps = eps elif isinstance(m, nn.GroupNorm): m.eps = eps replace_conv2d_with_my_conv2d(net, ws_eps) return def get_bn_param(net): ws_eps = None for m in net.modules(): if isinstance(m, MyConv2d): ws_eps = m.WS_EPS break for m in net.modules(): if isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d): return { "momentum": m.momentum, "eps": m.eps, "ws_eps": ws_eps, } elif isinstance(m, nn.GroupNorm): return { "momentum": None, "eps": m.eps, "gn_channel_per_group": m.num_channels // m.num_groups, "ws_eps": ws_eps, } return None def replace_bn_with_gn(model, gn_channel_per_group): if gn_channel_per_group is None: return for m in model.modules(): to_replace_dict = {} for name, sub_m in m.named_children(): if isinstance(sub_m, nn.BatchNorm2d): num_groups = sub_m.num_features // min_divisible_value( sub_m.num_features, gn_channel_per_group ) gn_m = nn.GroupNorm( num_groups=num_groups, num_channels=sub_m.num_features, eps=sub_m.eps, affine=True, ) # load weight gn_m.weight.data.copy_(sub_m.weight.data) gn_m.bias.data.copy_(sub_m.bias.data) # load requires_grad gn_m.weight.requires_grad = sub_m.weight.requires_grad gn_m.bias.requires_grad = sub_m.bias.requires_grad to_replace_dict[name] = gn_m m._modules.update(to_replace_dict) def replace_conv2d_with_my_conv2d(net, ws_eps=None): if ws_eps is None: return for m in net.modules(): to_update_dict = {} for name, sub_module in m.named_children(): if isinstance(sub_module, nn.Conv2d) and not sub_module.bias: # only replace conv2d layers that are followed by normalization layers (i.e., no bias) to_update_dict[name] = sub_module for name, sub_module in to_update_dict.items(): m._modules[name] = MyConv2d( sub_module.in_channels, sub_module.out_channels, sub_module.kernel_size, sub_module.stride, sub_module.padding, sub_module.dilation, sub_module.groups, sub_module.bias, ) # load weight m._modules[name].load_state_dict(sub_module.state_dict()) # load requires_grad m._modules[name].weight.requires_grad = sub_module.weight.requires_grad if sub_module.bias is not None: m._modules[name].bias.requires_grad = sub_module.bias.requires_grad # set ws_eps for m in net.modules(): if isinstance(m, MyConv2d): m.WS_EPS = ws_eps def init_models(net, model_init="he_fout"): """ Conv2d, BatchNorm2d, BatchNorm1d, GroupNorm Linear, """ if isinstance(net, list): for sub_net in net: init_models(sub_net, model_init) return for m in net.modules(): if isinstance(m, nn.Conv2d): if model_init == "he_fout": n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2.0 / n)) elif model_init == "he_fin": n = m.kernel_size[0] * m.kernel_size[1] * m.in_channels m.weight.data.normal_(0, math.sqrt(2.0 / n)) else: raise NotImplementedError if m.bias is not None: m.bias.data.zero_() elif type(m) in [nn.BatchNorm2d, nn.BatchNorm1d, nn.GroupNorm]: m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): stdv = 1.0 / math.sqrt(m.weight.size(1)) m.weight.data.uniform_(-stdv, stdv) if m.bias is not None: m.bias.data.zero_() class MyConv2d(nn.Conv2d): """ Conv2d with Weight Standardization https://github.com/joe-siyuan-qiao/WeightStandardization """ def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, ): super(MyConv2d, self).__init__( in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, ) self.WS_EPS = None def weight_standardization(self, weight): if self.WS_EPS is not None: weight_mean = ( weight.mean(dim=1, keepdim=True) .mean(dim=2, keepdim=True) .mean(dim=3, keepdim=True) ) weight = weight - weight_mean std = ( weight.view(weight.size(0), -1).std(dim=1).view(-1, 1, 1, 1) + self.WS_EPS ) weight = weight / std.expand_as(weight) return weight def forward(self, x): if self.WS_EPS is None: return super(MyConv2d, self).forward(x) else: return F.conv2d( x, self.weight_standardization(self.weight), self.bias, self.stride, self.padding, self.dilation, self.groups, ) def __repr__(self): return super(MyConv2d, self).__repr__()[:-1] + ", ws_eps=%s)" % self.WS_EPS class MyModule(nn.Module): def forward(self, x): raise NotImplementedError @property def module_str(self): raise NotImplementedError @property def config(self): raise NotImplementedError @staticmethod def build_from_config(config): raise NotImplementedError class MyNetwork(MyModule): CHANNEL_DIVISIBLE = 8 def forward(self, x): raise NotImplementedError @property def module_str(self): raise NotImplementedError @property def config(self): raise NotImplementedError @staticmethod def build_from_config(config): raise NotImplementedError def zero_last_gamma(self): raise NotImplementedError @property def grouped_block_index(self): raise NotImplementedError """ implemented methods """ def set_bn_param(self, momentum, eps, gn_channel_per_group=None, **kwargs): set_bn_param(self, momentum, eps, gn_channel_per_group, **kwargs) def get_bn_param(self): return get_bn_param(self) def get_parameters(self, keys=None, mode="include"): if keys is None: for name, param in self.named_parameters(): if param.requires_grad: yield param elif mode == "include": for name, param in self.named_parameters(): flag = False for key in keys: if key in name: flag = True break if flag and param.requires_grad: yield param elif mode == "exclude": for name, param in self.named_parameters(): flag = True for key in keys: if key in name: flag = False break if flag and param.requires_grad: yield param else: raise ValueError("do not support: %s" % mode) def weight_parameters(self): return self.get_parameters()
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import numpy as np import os import sys import torch try: from urllib import urlretrieve except ImportError: from urllib.request import urlretrieve __all__ = [ "sort_dict", "get_same_padding", "get_split_list", "list_sum", "list_mean", "list_join", "subset_mean", "sub_filter_start_end", "min_divisible_value", "val2list", "download_url", "write_log", "pairwise_accuracy", "accuracy", "AverageMeter", "MultiClassAverageMeter", "DistributedMetric", "DistributedTensor", ] def sort_dict(src_dict, reverse=False, return_dict=True): output = sorted(src_dict.items(), key=lambda x: x[1], reverse=reverse) if return_dict: return dict(output) else: return output def get_same_padding(kernel_size): if isinstance(kernel_size, tuple): assert len(kernel_size) == 2, "invalid kernel size: %s" % kernel_size p1 = get_same_padding(kernel_size[0]) p2 = get_same_padding(kernel_size[1]) return p1, p2 assert isinstance(kernel_size, int), "kernel size should be either `int` or `tuple`" assert kernel_size % 2 > 0, "kernel size should be odd number" return kernel_size // 2 def get_split_list(in_dim, child_num, accumulate=False): in_dim_list = [in_dim // child_num] * child_num for _i in range(in_dim % child_num): in_dim_list[_i] += 1 if accumulate: for i in range(1, child_num): in_dim_list[i] += in_dim_list[i - 1] return in_dim_list def list_sum(x): return x[0] if len(x) == 1 else x[0] + list_sum(x[1:]) def list_mean(x): return list_sum(x) / len(x) def list_join(val_list, sep="\t"): return sep.join([str(val) for val in val_list]) def subset_mean(val_list, sub_indexes): sub_indexes = val2list(sub_indexes, 1) return list_mean([val_list[idx] for idx in sub_indexes]) def sub_filter_start_end(kernel_size, sub_kernel_size): center = kernel_size // 2 dev = sub_kernel_size // 2 start, end = center - dev, center + dev + 1 assert end - start == sub_kernel_size return start, end def min_divisible_value(n1, v1): """make sure v1 is divisible by n1, otherwise decrease v1""" if v1 >= n1: return n1 while n1 % v1 != 0: v1 -= 1 return v1 def val2list(val, repeat_time=1): if isinstance(val, list) or isinstance(val, np.ndarray): return val elif isinstance(val, tuple): return list(val) else: return [val for _ in range(repeat_time)] def download_url(url, model_dir="~/.torch/", overwrite=False): target_dir = url.split("/")[-1] model_dir = os.path.expanduser(model_dir) try: if not os.path.exists(model_dir): os.makedirs(model_dir) model_dir = os.path.join(model_dir, target_dir) cached_file = model_dir if not os.path.exists(cached_file) or overwrite: sys.stderr.write('Downloading: "{}" to {}\n'.format(url, cached_file)) urlretrieve(url, cached_file) return cached_file except Exception as e: # remove lock file so download can be executed next time. os.remove(os.path.join(model_dir, "download.lock")) sys.stderr.write("Failed to download from url %s" % url + "\n" + str(e) + "\n") return None def write_log(logs_path, log_str, prefix="valid", should_print=True, mode="a"): if not os.path.exists(logs_path): os.makedirs(logs_path, exist_ok=True) """ prefix: valid, train, test """ if prefix in ["valid", "test"]: with open(os.path.join(logs_path, "valid_console.txt"), mode) as fout: fout.write(log_str + "\n") fout.flush() if prefix in ["valid", "test", "train"]: with open(os.path.join(logs_path, "train_console.txt"), mode) as fout: if prefix in ["valid", "test"]: fout.write("=" * 10) fout.write(log_str + "\n") fout.flush() else: with open(os.path.join(logs_path, "%s.txt" % prefix), mode) as fout: fout.write(log_str + "\n") fout.flush() if should_print: print(log_str) def pairwise_accuracy(la, lb, n_samples=200000): n = len(la) assert n == len(lb) total = 0 count = 0 for _ in range(n_samples): i = np.random.randint(n) j = np.random.randint(n) while i == j: j = np.random.randint(n) if la[i] >= la[j] and lb[i] >= lb[j]: count += 1 if la[i] < la[j] and lb[i] < lb[j]: count += 1 total += 1 return float(count) / total def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res class AverageMeter(object): """ Computes and stores the average and current value Copied from: https://github.com/pytorch/examples/blob/master/imagenet/main.py """ def __init__(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count class MultiClassAverageMeter: """Multi Binary Classification Tasks""" def __init__(self, num_classes, balanced=False, **kwargs): super(MultiClassAverageMeter, self).__init__() self.num_classes = num_classes self.balanced = balanced self.counts = [] for k in range(self.num_classes): self.counts.append(np.ndarray((2, 2), dtype=np.float32)) self.reset() def reset(self): for k in range(self.num_classes): self.counts[k].fill(0) def add(self, outputs, targets): outputs = outputs.data.cpu().numpy() targets = targets.data.cpu().numpy() for k in range(self.num_classes): output = np.argmax(outputs[:, k, :], axis=1) target = targets[:, k] x = output + 2 * target bincount = np.bincount(x.astype(np.int32), minlength=2 ** 2) self.counts[k] += bincount.reshape((2, 2)) def value(self): mean = 0 for k in range(self.num_classes): if self.balanced: value = np.mean( ( self.counts[k] / np.maximum(np.sum(self.counts[k], axis=1), 1)[:, None] ).diagonal() ) else: value = np.sum(self.counts[k].diagonal()) / np.maximum( np.sum(self.counts[k]), 1 ) mean += value / self.num_classes * 100.0 return mean class DistributedMetric(object): """ Horovod: average metrics from distributed training. """ def __init__(self, name): self.name = name self.sum = torch.zeros(1)[0] self.count = torch.zeros(1)[0] def update(self, val, delta_n=1): import horovod.torch as hvd val *= delta_n self.sum += hvd.allreduce(val.detach().cpu(), name=self.name) self.count += delta_n @property def avg(self): return self.sum / self.count class DistributedTensor(object): def __init__(self, name): self.name = name self.sum = None self.count = torch.zeros(1)[0] self.synced = False def update(self, val, delta_n=1): val *= delta_n if self.sum is None: self.sum = val.detach() else: self.sum += val.detach() self.count += delta_n @property def avg(self): import horovod.torch as hvd if not self.synced: self.sum = hvd.allreduce(self.sum, name=self.name) self.synced = True return self.sum / self.count
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import math import copy import time import torch import torch.nn as nn __all__ = [ "mix_images", "mix_labels", "label_smooth", "cross_entropy_loss_with_soft_target", "cross_entropy_with_label_smoothing", "clean_num_batch_tracked", "rm_bn_from_net", "get_net_device", "count_parameters", "count_net_flops", "measure_net_latency", "get_net_info", "build_optimizer", "calc_learning_rate", ] """ Mixup """ def mix_images(images, lam): flipped_images = torch.flip(images, dims=[0]) # flip along the batch dimension return lam * images + (1 - lam) * flipped_images def mix_labels(target, lam, n_classes, label_smoothing=0.1): onehot_target = label_smooth(target, n_classes, label_smoothing) flipped_target = torch.flip(onehot_target, dims=[0]) return lam * onehot_target + (1 - lam) * flipped_target """ Label smooth """ def label_smooth(target, n_classes: int, label_smoothing=0.1): # convert to one-hot batch_size = target.size(0) target = torch.unsqueeze(target, 1) soft_target = torch.zeros((batch_size, n_classes), device=target.device) soft_target.scatter_(1, target, 1) # label smoothing soft_target = soft_target * (1 - label_smoothing) + label_smoothing / n_classes return soft_target def cross_entropy_loss_with_soft_target(pred, soft_target): logsoftmax = nn.LogSoftmax() return torch.mean(torch.sum(-soft_target * logsoftmax(pred), 1)) def cross_entropy_with_label_smoothing(pred, target, label_smoothing=0.1): soft_target = label_smooth(target, pred.size(1), label_smoothing) return cross_entropy_loss_with_soft_target(pred, soft_target) """ BN related """ def clean_num_batch_tracked(net): for m in net.modules(): if isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d): if m.num_batches_tracked is not None: m.num_batches_tracked.zero_() def rm_bn_from_net(net): for m in net.modules(): if isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d): m.forward = lambda x: x """ Network profiling """ def get_net_device(net): return net.parameters().__next__().device def count_parameters(net): total_params = sum(p.numel() for p in net.parameters() if p.requires_grad) return total_params def count_net_flops(net, data_shape=(1, 3, 224, 224)): from .flops_counter import profile if isinstance(net, nn.DataParallel): net = net.module flop, _ = profile(copy.deepcopy(net), data_shape) return flop def measure_net_latency( net, l_type="gpu8", fast=True, input_shape=(3, 224, 224), clean=False ): if isinstance(net, nn.DataParallel): net = net.module # remove bn from graph rm_bn_from_net(net) # return `ms` if "gpu" in l_type: l_type, batch_size = l_type[:3], int(l_type[3:]) else: batch_size = 1 data_shape = [batch_size] + list(input_shape) if l_type == "cpu": if fast: n_warmup = 5 n_sample = 10 else: n_warmup = 50 n_sample = 50 if get_net_device(net) != torch.device("cpu"): if not clean: print("move net to cpu for measuring cpu latency") net = copy.deepcopy(net).cpu() elif l_type == "gpu": if fast: n_warmup = 5 n_sample = 10 else: n_warmup = 50 n_sample = 50 else: raise NotImplementedError images = torch.zeros(data_shape, device=get_net_device(net)) measured_latency = {"warmup": [], "sample": []} net.eval() with torch.no_grad(): for i in range(n_warmup): inner_start_time = time.time() net(images) used_time = (time.time() - inner_start_time) * 1e3 # ms measured_latency["warmup"].append(used_time) if not clean: print("Warmup %d: %.3f" % (i, used_time)) outer_start_time = time.time() for i in range(n_sample): net(images) total_time = (time.time() - outer_start_time) * 1e3 # ms measured_latency["sample"].append((total_time, n_sample)) return total_time / n_sample, measured_latency def get_net_info(net, input_shape=(3, 224, 224), measure_latency=None, print_info=True): net_info = {} if isinstance(net, nn.DataParallel): net = net.module # parameters net_info["params"] = count_parameters(net) / 1e6 # flops net_info["flops"] = count_net_flops(net, [1] + list(input_shape)) / 1e6 # latencies latency_types = [] if measure_latency is None else measure_latency.split("#") for l_type in latency_types: latency, measured_latency = measure_net_latency( net, l_type, fast=False, input_shape=input_shape ) net_info["%s latency" % l_type] = {"val": latency, "hist": measured_latency} if print_info: print(net) print("Total training params: %.2fM" % (net_info["params"])) print("Total FLOPs: %.2fM" % (net_info["flops"])) for l_type in latency_types: print( "Estimated %s latency: %.3fms" % (l_type, net_info["%s latency" % l_type]["val"]) ) return net_info """ optimizer """ def build_optimizer( net_params, opt_type, opt_param, init_lr, weight_decay, no_decay_keys ): if no_decay_keys is not None: assert isinstance(net_params, list) and len(net_params) == 2 net_params = [ {"params": net_params[0], "weight_decay": weight_decay}, {"params": net_params[1], "weight_decay": 0}, ] else: net_params = [{"params": net_params, "weight_decay": weight_decay}] if opt_type == "sgd": opt_param = {} if opt_param is None else opt_param momentum, nesterov = opt_param.get("momentum", 0.9), opt_param.get( "nesterov", True ) optimizer = torch.optim.SGD( net_params, init_lr, momentum=momentum, nesterov=nesterov ) elif opt_type == "adam": optimizer = torch.optim.Adam(net_params, init_lr) else: raise NotImplementedError return optimizer """ learning rate schedule """ def calc_learning_rate( epoch, init_lr, n_epochs, batch=0, nBatch=None, lr_schedule_type="cosine" ): if lr_schedule_type == "cosine": t_total = n_epochs * nBatch t_cur = epoch * nBatch + batch lr = 0.5 * init_lr * (1 + math.cos(math.pi * t_cur / t_total)) elif lr_schedule_type is None: lr = init_lr else: raise ValueError("do not support: %s" % lr_schedule_type) return lr
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. from .pytorch_modules import * from .pytorch_utils import * from .my_modules import * from .flops_counter import * from .common_tools import * from .my_dataloader import *
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import torch import torch.nn as nn from .my_modules import MyConv2d __all__ = ["profile"] def count_convNd(m, _, y): cin = m.in_channels kernel_ops = m.weight.size()[2] * m.weight.size()[3] ops_per_element = kernel_ops output_elements = y.nelement() # cout x oW x oH total_ops = cin * output_elements * ops_per_element // m.groups m.total_ops = torch.zeros(1).fill_(total_ops) def count_linear(m, _, __): total_ops = m.in_features * m.out_features m.total_ops = torch.zeros(1).fill_(total_ops) register_hooks = { nn.Conv1d: count_convNd, nn.Conv2d: count_convNd, nn.Conv3d: count_convNd, MyConv2d: count_convNd, ###################################### nn.Linear: count_linear, ###################################### nn.Dropout: None, nn.Dropout2d: None, nn.Dropout3d: None, nn.BatchNorm2d: None, } def profile(model, input_size, custom_ops=None): handler_collection = [] custom_ops = {} if custom_ops is None else custom_ops def add_hooks(m_): if len(list(m_.children())) > 0: return m_.register_buffer("total_ops", torch.zeros(1)) m_.register_buffer("total_params", torch.zeros(1)) for p in m_.parameters(): m_.total_params += torch.zeros(1).fill_(p.numel()) m_type = type(m_) fn = None if m_type in custom_ops: fn = custom_ops[m_type] elif m_type in register_hooks: fn = register_hooks[m_type] if fn is not None: _handler = m_.register_forward_hook(fn) handler_collection.append(_handler) original_device = model.parameters().__next__().device training = model.training model.eval() model.apply(add_hooks) x = torch.zeros(input_size).to(original_device) with torch.no_grad(): model(x) total_ops = 0 total_params = 0 for m in model.modules(): if len(list(m.children())) > 0: # skip for non-leaf module continue total_ops += m.total_ops total_params += m.total_params total_ops = total_ops.item() total_params = total_params.item() model.train(training).to(original_device) for handler in handler_collection: handler.remove() return total_ops, total_params
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from .my_modules import MyNetwork __all__ = [ "make_divisible", "build_activation", "ShuffleLayer", "MyGlobalAvgPool2d", "Hswish", "Hsigmoid", "SEModule", "MultiHeadCrossEntropyLoss", ] def make_divisible(v, divisor, min_val=None): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: :param divisor: :param min_val: :return: """ if min_val is None: min_val = divisor new_v = max(min_val, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v def build_activation(act_func, inplace=True): if act_func == "relu": return nn.ReLU(inplace=inplace) elif act_func == "relu6": return nn.ReLU6(inplace=inplace) elif act_func == "tanh": return nn.Tanh() elif act_func == "sigmoid": return nn.Sigmoid() elif act_func == "h_swish": return Hswish(inplace=inplace) elif act_func == "h_sigmoid": return Hsigmoid(inplace=inplace) elif act_func is None or act_func == "none": return None else: raise ValueError("do not support: %s" % act_func) class ShuffleLayer(nn.Module): def __init__(self, groups): super(ShuffleLayer, self).__init__() self.groups = groups def forward(self, x): batch_size, num_channels, height, width = x.size() channels_per_group = num_channels // self.groups # reshape x = x.view(batch_size, self.groups, channels_per_group, height, width) x = torch.transpose(x, 1, 2).contiguous() # flatten x = x.view(batch_size, -1, height, width) return x def __repr__(self): return "ShuffleLayer(groups=%d)" % self.groups class MyGlobalAvgPool2d(nn.Module): def __init__(self, keep_dim=True): super(MyGlobalAvgPool2d, self).__init__() self.keep_dim = keep_dim def forward(self, x): return x.mean(3, keepdim=self.keep_dim).mean(2, keepdim=self.keep_dim) def __repr__(self): return "MyGlobalAvgPool2d(keep_dim=%s)" % self.keep_dim class Hswish(nn.Module): def __init__(self, inplace=True): super(Hswish, self).__init__() self.inplace = inplace def forward(self, x): return x * F.relu6(x + 3.0, inplace=self.inplace) / 6.0 def __repr__(self): return "Hswish()" class Hsigmoid(nn.Module): def __init__(self, inplace=True): super(Hsigmoid, self).__init__() self.inplace = inplace def forward(self, x): return F.relu6(x + 3.0, inplace=self.inplace) / 6.0 def __repr__(self): return "Hsigmoid()" class SEModule(nn.Module): REDUCTION = 4 def __init__(self, channel, reduction=None): super(SEModule, self).__init__() self.channel = channel self.reduction = SEModule.REDUCTION if reduction is None else reduction num_mid = make_divisible( self.channel // self.reduction, divisor=MyNetwork.CHANNEL_DIVISIBLE ) self.fc = nn.Sequential( OrderedDict( [ ("reduce", nn.Conv2d(self.channel, num_mid, 1, 1, 0, bias=True)), ("relu", nn.ReLU(inplace=True)), ("expand", nn.Conv2d(num_mid, self.channel, 1, 1, 0, bias=True)), ("h_sigmoid", Hsigmoid(inplace=True)), ] ) ) def forward(self, x): y = x.mean(3, keepdim=True).mean(2, keepdim=True) y = self.fc(y) return x * y def __repr__(self): return "SE(channel=%d, reduction=%d)" % (self.channel, self.reduction) class MultiHeadCrossEntropyLoss(nn.Module): def forward(self, outputs, targets): assert outputs.dim() == 3, outputs assert targets.dim() == 2, targets assert outputs.size(1) == targets.size(1), (outputs, targets) num_heads = targets.size(1) loss = 0 for k in range(num_heads): loss += F.cross_entropy(outputs[:, k, :], targets[:, k]) / num_heads return loss
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import torch import torch.nn as nn from collections import OrderedDict from ofa.utils import get_same_padding, min_divisible_value, SEModule, ShuffleLayer from ofa.utils import MyNetwork, MyModule from ofa.utils import build_activation, make_divisible __all__ = [ "set_layer_from_config", "ConvLayer", "IdentityLayer", "LinearLayer", "MultiHeadLinearLayer", "ZeroLayer", "MBConvLayer", "ResidualBlock", "ResNetBottleneckBlock", ] def set_layer_from_config(layer_config): if layer_config is None: return None name2layer = { ConvLayer.__name__: ConvLayer, IdentityLayer.__name__: IdentityLayer, LinearLayer.__name__: LinearLayer, MultiHeadLinearLayer.__name__: MultiHeadLinearLayer, ZeroLayer.__name__: ZeroLayer, MBConvLayer.__name__: MBConvLayer, "MBInvertedConvLayer": MBConvLayer, ########################################################## ResidualBlock.__name__: ResidualBlock, ResNetBottleneckBlock.__name__: ResNetBottleneckBlock, } layer_name = layer_config.pop("name") layer = name2layer[layer_name] return layer.build_from_config(layer_config) class My2DLayer(MyModule): def __init__( self, in_channels, out_channels, use_bn=True, act_func="relu", dropout_rate=0, ops_order="weight_bn_act", ): super(My2DLayer, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.use_bn = use_bn self.act_func = act_func self.dropout_rate = dropout_rate self.ops_order = ops_order """ modules """ modules = {} # batch norm if self.use_bn: if self.bn_before_weight: modules["bn"] = nn.BatchNorm2d(in_channels) else: modules["bn"] = nn.BatchNorm2d(out_channels) else: modules["bn"] = None # activation modules["act"] = build_activation( self.act_func, self.ops_list[0] != "act" and self.use_bn ) # dropout if self.dropout_rate > 0: modules["dropout"] = nn.Dropout2d(self.dropout_rate, inplace=True) else: modules["dropout"] = None # weight modules["weight"] = self.weight_op() # add modules for op in self.ops_list: if modules[op] is None: continue elif op == "weight": # dropout before weight operation if modules["dropout"] is not None: self.add_module("dropout", modules["dropout"]) for key in modules["weight"]: self.add_module(key, modules["weight"][key]) else: self.add_module(op, modules[op]) @property def ops_list(self): return self.ops_order.split("_") @property def bn_before_weight(self): for op in self.ops_list: if op == "bn": return True elif op == "weight": return False raise ValueError("Invalid ops_order: %s" % self.ops_order) def weight_op(self): raise NotImplementedError """ Methods defined in MyModule """ def forward(self, x): # similar to nn.Sequential for module in self._modules.values(): x = module(x) return x @property def module_str(self): raise NotImplementedError @property def config(self): return { "in_channels": self.in_channels, "out_channels": self.out_channels, "use_bn": self.use_bn, "act_func": self.act_func, "dropout_rate": self.dropout_rate, "ops_order": self.ops_order, } @staticmethod def build_from_config(config): raise NotImplementedError class ConvLayer(My2DLayer): def __init__( self, in_channels, out_channels, kernel_size=3, stride=1, dilation=1, groups=1, bias=False, has_shuffle=False, use_se=False, use_bn=True, act_func="relu", dropout_rate=0, ops_order="weight_bn_act", ): # default normal 3x3_Conv with bn and relu self.kernel_size = kernel_size self.stride = stride self.dilation = dilation self.groups = groups self.bias = bias self.has_shuffle = has_shuffle self.use_se = use_se super(ConvLayer, self).__init__( in_channels, out_channels, use_bn, act_func, dropout_rate, ops_order ) if self.use_se: self.add_module("se", SEModule(self.out_channels)) def weight_op(self): padding = get_same_padding(self.kernel_size) if isinstance(padding, int): padding *= self.dilation else: padding[0] *= self.dilation padding[1] *= self.dilation weight_dict = OrderedDict( { "conv": nn.Conv2d( self.in_channels, self.out_channels, kernel_size=self.kernel_size, stride=self.stride, padding=padding, dilation=self.dilation, groups=min_divisible_value(self.in_channels, self.groups), bias=self.bias, ) } ) if self.has_shuffle and self.groups > 1: weight_dict["shuffle"] = ShuffleLayer(self.groups) return weight_dict @property def module_str(self): if isinstance(self.kernel_size, int): kernel_size = (self.kernel_size, self.kernel_size) else: kernel_size = self.kernel_size if self.groups == 1: if self.dilation > 1: conv_str = "%dx%d_DilatedConv" % (kernel_size[0], kernel_size[1]) else: conv_str = "%dx%d_Conv" % (kernel_size[0], kernel_size[1]) else: if self.dilation > 1: conv_str = "%dx%d_DilatedGroupConv" % (kernel_size[0], kernel_size[1]) else: conv_str = "%dx%d_GroupConv" % (kernel_size[0], kernel_size[1]) conv_str += "_O%d" % self.out_channels if self.use_se: conv_str = "SE_" + conv_str conv_str += "_" + self.act_func.upper() if self.use_bn: if isinstance(self.bn, nn.GroupNorm): conv_str += "_GN%d" % self.bn.num_groups elif isinstance(self.bn, nn.BatchNorm2d): conv_str += "_BN" return conv_str @property def config(self): return { "name": ConvLayer.__name__, "kernel_size": self.kernel_size, "stride": self.stride, "dilation": self.dilation, "groups": self.groups, "bias": self.bias, "has_shuffle": self.has_shuffle, "use_se": self.use_se, **super(ConvLayer, self).config, } @staticmethod def build_from_config(config): return ConvLayer(**config) class IdentityLayer(My2DLayer): def __init__( self, in_channels, out_channels, use_bn=False, act_func=None, dropout_rate=0, ops_order="weight_bn_act", ): super(IdentityLayer, self).__init__( in_channels, out_channels, use_bn, act_func, dropout_rate, ops_order ) def weight_op(self): return None @property def module_str(self): return "Identity" @property def config(self): return { "name": IdentityLayer.__name__, **super(IdentityLayer, self).config, } @staticmethod def build_from_config(config): return IdentityLayer(**config) class LinearLayer(MyModule): def __init__( self, in_features, out_features, bias=True, use_bn=False, act_func=None, dropout_rate=0, ops_order="weight_bn_act", ): super(LinearLayer, self).__init__() self.in_features = in_features self.out_features = out_features self.bias = bias self.use_bn = use_bn self.act_func = act_func self.dropout_rate = dropout_rate self.ops_order = ops_order """ modules """ modules = {} # batch norm if self.use_bn: if self.bn_before_weight: modules["bn"] = nn.BatchNorm1d(in_features) else: modules["bn"] = nn.BatchNorm1d(out_features) else: modules["bn"] = None # activation modules["act"] = build_activation(self.act_func, self.ops_list[0] != "act") # dropout if self.dropout_rate > 0: modules["dropout"] = nn.Dropout(self.dropout_rate, inplace=True) else: modules["dropout"] = None # linear modules["weight"] = { "linear": nn.Linear(self.in_features, self.out_features, self.bias) } # add modules for op in self.ops_list: if modules[op] is None: continue elif op == "weight": if modules["dropout"] is not None: self.add_module("dropout", modules["dropout"]) for key in modules["weight"]: self.add_module(key, modules["weight"][key]) else: self.add_module(op, modules[op]) @property def ops_list(self): return self.ops_order.split("_") @property def bn_before_weight(self): for op in self.ops_list: if op == "bn": return True elif op == "weight": return False raise ValueError("Invalid ops_order: %s" % self.ops_order) def forward(self, x): for module in self._modules.values(): x = module(x) return x @property def module_str(self): return "%dx%d_Linear" % (self.in_features, self.out_features) @property def config(self): return { "name": LinearLayer.__name__, "in_features": self.in_features, "out_features": self.out_features, "bias": self.bias, "use_bn": self.use_bn, "act_func": self.act_func, "dropout_rate": self.dropout_rate, "ops_order": self.ops_order, } @staticmethod def build_from_config(config): return LinearLayer(**config) class MultiHeadLinearLayer(MyModule): def __init__( self, in_features, out_features, num_heads=1, bias=True, dropout_rate=0 ): super(MultiHeadLinearLayer, self).__init__() self.in_features = in_features self.out_features = out_features self.num_heads = num_heads self.bias = bias self.dropout_rate = dropout_rate if self.dropout_rate > 0: self.dropout = nn.Dropout(self.dropout_rate, inplace=True) else: self.dropout = None self.layers = nn.ModuleList() for k in range(num_heads): layer = nn.Linear(in_features, out_features, self.bias) self.layers.append(layer) def forward(self, inputs): if self.dropout is not None: inputs = self.dropout(inputs) outputs = [] for layer in self.layers: output = layer.forward(inputs) outputs.append(output) outputs = torch.stack(outputs, dim=1) return outputs @property def module_str(self): return self.__repr__() @property def config(self): return { "name": MultiHeadLinearLayer.__name__, "in_features": self.in_features, "out_features": self.out_features, "num_heads": self.num_heads, "bias": self.bias, "dropout_rate": self.dropout_rate, } @staticmethod def build_from_config(config): return MultiHeadLinearLayer(**config) def __repr__(self): return ( "MultiHeadLinear(in_features=%d, out_features=%d, num_heads=%d, bias=%s, dropout_rate=%s)" % ( self.in_features, self.out_features, self.num_heads, self.bias, self.dropout_rate, ) ) class ZeroLayer(MyModule): def __init__(self): super(ZeroLayer, self).__init__() def forward(self, x): raise ValueError @property def module_str(self): return "Zero" @property def config(self): return { "name": ZeroLayer.__name__, } @staticmethod def build_from_config(config): return ZeroLayer() class MBConvLayer(MyModule): def __init__( self, in_channels, out_channels, kernel_size=3, stride=1, expand_ratio=6, mid_channels=None, act_func="relu6", use_se=False, groups=None, ): super(MBConvLayer, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.stride = stride self.expand_ratio = expand_ratio self.mid_channels = mid_channels self.act_func = act_func self.use_se = use_se self.groups = groups if self.mid_channels is None: feature_dim = round(self.in_channels * self.expand_ratio) else: feature_dim = self.mid_channels if self.expand_ratio == 1: self.inverted_bottleneck = None else: self.inverted_bottleneck = nn.Sequential( OrderedDict( [ ( "conv", nn.Conv2d( self.in_channels, feature_dim, 1, 1, 0, bias=False ), ), ("bn", nn.BatchNorm2d(feature_dim)), ("act", build_activation(self.act_func, inplace=True)), ] ) ) pad = get_same_padding(self.kernel_size) groups = ( feature_dim if self.groups is None else min_divisible_value(feature_dim, self.groups) ) depth_conv_modules = [ ( "conv", nn.Conv2d( feature_dim, feature_dim, kernel_size, stride, pad, groups=groups, bias=False, ), ), ("bn", nn.BatchNorm2d(feature_dim)), ("act", build_activation(self.act_func, inplace=True)), ] if self.use_se: depth_conv_modules.append(("se", SEModule(feature_dim))) self.depth_conv = nn.Sequential(OrderedDict(depth_conv_modules)) self.point_linear = nn.Sequential( OrderedDict( [ ("conv", nn.Conv2d(feature_dim, out_channels, 1, 1, 0, bias=False)), ("bn", nn.BatchNorm2d(out_channels)), ] ) ) def forward(self, x): if self.inverted_bottleneck: x = self.inverted_bottleneck(x) x = self.depth_conv(x) x = self.point_linear(x) return x @property def module_str(self): if self.mid_channels is None: expand_ratio = self.expand_ratio else: expand_ratio = self.mid_channels // self.in_channels layer_str = "%dx%d_MBConv%d_%s" % ( self.kernel_size, self.kernel_size, expand_ratio, self.act_func.upper(), ) if self.use_se: layer_str = "SE_" + layer_str layer_str += "_O%d" % self.out_channels if self.groups is not None: layer_str += "_G%d" % self.groups if isinstance(self.point_linear.bn, nn.GroupNorm): layer_str += "_GN%d" % self.point_linear.bn.num_groups elif isinstance(self.point_linear.bn, nn.BatchNorm2d): layer_str += "_BN" return layer_str @property def config(self): return { "name": MBConvLayer.__name__, "in_channels": self.in_channels, "out_channels": self.out_channels, "kernel_size": self.kernel_size, "stride": self.stride, "expand_ratio": self.expand_ratio, "mid_channels": self.mid_channels, "act_func": self.act_func, "use_se": self.use_se, "groups": self.groups, } @staticmethod def build_from_config(config): return MBConvLayer(**config) class ResidualBlock(MyModule): def __init__(self, conv, shortcut): super(ResidualBlock, self).__init__() self.conv = conv self.shortcut = shortcut def forward(self, x): if self.conv is None or isinstance(self.conv, ZeroLayer): res = x elif self.shortcut is None or isinstance(self.shortcut, ZeroLayer): res = self.conv(x) else: res = self.conv(x) + self.shortcut(x) return res @property def module_str(self): return "(%s, %s)" % ( self.conv.module_str if self.conv is not None else None, self.shortcut.module_str if self.shortcut is not None else None, ) @property def config(self): return { "name": ResidualBlock.__name__, "conv": self.conv.config if self.conv is not None else None, "shortcut": self.shortcut.config if self.shortcut is not None else None, } @staticmethod def build_from_config(config): conv_config = ( config["conv"] if "conv" in config else config["mobile_inverted_conv"] ) conv = set_layer_from_config(conv_config) shortcut = set_layer_from_config(config["shortcut"]) return ResidualBlock(conv, shortcut) @property def mobile_inverted_conv(self): return self.conv class ResNetBottleneckBlock(MyModule): def __init__( self, in_channels, out_channels, kernel_size=3, stride=1, expand_ratio=0.25, mid_channels=None, act_func="relu", groups=1, downsample_mode="avgpool_conv", ): super(ResNetBottleneckBlock, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.stride = stride self.expand_ratio = expand_ratio self.mid_channels = mid_channels self.act_func = act_func self.groups = groups self.downsample_mode = downsample_mode if self.mid_channels is None: feature_dim = round(self.out_channels * self.expand_ratio) else: feature_dim = self.mid_channels feature_dim = make_divisible(feature_dim, MyNetwork.CHANNEL_DIVISIBLE) self.mid_channels = feature_dim # build modules self.conv1 = nn.Sequential( OrderedDict( [ ( "conv", nn.Conv2d(self.in_channels, feature_dim, 1, 1, 0, bias=False), ), ("bn", nn.BatchNorm2d(feature_dim)), ("act", build_activation(self.act_func, inplace=True)), ] ) ) pad = get_same_padding(self.kernel_size) self.conv2 = nn.Sequential( OrderedDict( [ ( "conv", nn.Conv2d( feature_dim, feature_dim, kernel_size, stride, pad, groups=groups, bias=False, ), ), ("bn", nn.BatchNorm2d(feature_dim)), ("act", build_activation(self.act_func, inplace=True)), ] ) ) self.conv3 = nn.Sequential( OrderedDict( [ ( "conv", nn.Conv2d(feature_dim, self.out_channels, 1, 1, 0, bias=False), ), ("bn", nn.BatchNorm2d(self.out_channels)), ] ) ) if stride == 1 and in_channels == out_channels: self.downsample = IdentityLayer(in_channels, out_channels) elif self.downsample_mode == "conv": self.downsample = nn.Sequential( OrderedDict( [ ( "conv", nn.Conv2d( in_channels, out_channels, 1, stride, 0, bias=False ), ), ("bn", nn.BatchNorm2d(out_channels)), ] ) ) elif self.downsample_mode == "avgpool_conv": self.downsample = nn.Sequential( OrderedDict( [ ( "avg_pool", nn.AvgPool2d( kernel_size=stride, stride=stride, padding=0, ceil_mode=True, ), ), ( "conv", nn.Conv2d(in_channels, out_channels, 1, 1, 0, bias=False), ), ("bn", nn.BatchNorm2d(out_channels)), ] ) ) else: raise NotImplementedError self.final_act = build_activation(self.act_func, inplace=True) def forward(self, x): residual = self.downsample(x) x = self.conv1(x) x = self.conv2(x) x = self.conv3(x) x = x + residual x = self.final_act(x) return x @property def module_str(self): return "(%s, %s)" % ( "%dx%d_BottleneckConv_%d->%d->%d_S%d_G%d" % ( self.kernel_size, self.kernel_size, self.in_channels, self.mid_channels, self.out_channels, self.stride, self.groups, ), "Identity" if isinstance(self.downsample, IdentityLayer) else self.downsample_mode, ) @property def config(self): return { "name": ResNetBottleneckBlock.__name__, "in_channels": self.in_channels, "out_channels": self.out_channels, "kernel_size": self.kernel_size, "stride": self.stride, "expand_ratio": self.expand_ratio, "mid_channels": self.mid_channels, "act_func": self.act_func, "groups": self.groups, "downsample_mode": self.downsample_mode, } @staticmethod def build_from_config(config): return ResNetBottleneckBlock(**config)
r"""Definition of the DataLoader and associated iterators that subclass _BaseDataLoaderIter To support these two classes, in `./_utils` we define many utility methods and functions to be run in multiprocessing. E.g., the data loading worker loop is in `./_utils/worker.py`. """ import threading import itertools import warnings import multiprocessing as python_multiprocessing import torch import torch.multiprocessing as multiprocessing from torch._utils import ExceptionWrapper from torch.multiprocessing import Queue as queue from torch._six import string_classes from torch.utils.data.dataset import IterableDataset from torch.utils.data import Sampler, SequentialSampler, RandomSampler, BatchSampler from torch.utils.data import _utils from .my_data_worker import worker_loop __all__ = ["MyDataLoader"] get_worker_info = _utils.worker.get_worker_info # This function used to be defined in this file. However, it was moved to # _utils/collate.py. Although it is rather hard to access this from user land # (one has to explicitly directly `import torch.utils.data.dataloader`), there # probably is user code out there using it. This aliasing maintains BC in this # aspect. default_collate = _utils.collate.default_collate class _DatasetKind(object): Map = 0 Iterable = 1 @staticmethod def create_fetcher(kind, dataset, auto_collation, collate_fn, drop_last): if kind == _DatasetKind.Map: return _utils.fetch._MapDatasetFetcher( dataset, auto_collation, collate_fn, drop_last ) else: return _utils.fetch._IterableDatasetFetcher( dataset, auto_collation, collate_fn, drop_last ) class _InfiniteConstantSampler(Sampler): r"""Analogous to ``itertools.repeat(None, None)``. Used as sampler for :class:`~torch.utils.data.IterableDataset`. Arguments: data_source (Dataset): dataset to sample from """ def __init__(self): super(_InfiniteConstantSampler, self).__init__(None) def __iter__(self): while True: yield None class MyDataLoader(object): r""" Data loader. Combines a dataset and a sampler, and provides an iterable over the given dataset. The :class:`~torch.utils.data.DataLoader` supports both map-style and iterable-style datasets with single- or multi-process loading, customizing loading order and optional automatic batching (collation) and memory pinning. See :py:mod:`torch.utils.data` documentation page for more details. Arguments: dataset (Dataset): dataset from which to load the data. batch_size (int, optional): how many samples per batch to load (default: ``1``). shuffle (bool, optional): set to ``True`` to have the data reshuffled at every epoch (default: ``False``). sampler (Sampler, optional): defines the strategy to draw samples from the dataset. If specified, :attr:`shuffle` must be ``False``. batch_sampler (Sampler, optional): like :attr:`sampler`, but returns a batch of indices at a time. Mutually exclusive with :attr:`batch_size`, :attr:`shuffle`, :attr:`sampler`, and :attr:`drop_last`. num_workers (int, optional): how many subprocesses to use for data loading. ``0`` means that the data will be loaded in the main process. (default: ``0``) collate_fn (callable, optional): merges a list of samples to form a mini-batch of Tensor(s). Used when using batched loading from a map-style dataset. pin_memory (bool, optional): If ``True``, the data loader will copy Tensors into CUDA pinned memory before returning them. If your data elements are a custom type, or your :attr:`collate_fn` returns a batch that is a custom type, see the example below. drop_last (bool, optional): set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then the last batch will be smaller. (default: ``False``) timeout (numeric, optional): if positive, the timeout value for collecting a batch from workers. Should always be non-negative. (default: ``0``) worker_init_fn (callable, optional): If not ``None``, this will be called on each worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as input, after seeding and before data loading. (default: ``None``) .. warning:: If the ``spawn`` start method is used, :attr:`worker_init_fn` cannot be an unpicklable object, e.g., a lambda function. See :ref:`multiprocessing-best-practices` on more details related to multiprocessing in PyTorch. .. note:: ``len(dataloader)`` heuristic is based on the length of the sampler used. When :attr:`dataset` is an :class:`~torch.utils.data.IterableDataset`, ``len(dataset)`` (if implemented) is returned instead, regardless of multi-process loading configurations, because PyTorch trust user :attr:`dataset` code in correctly handling multi-process loading to avoid duplicate data. See `Dataset Types`_ for more details on these two types of datasets and how :class:`~torch.utils.data.IterableDataset` interacts with `Multi-process data loading`_. """ __initialized = False def __init__( self, dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, num_workers=0, collate_fn=None, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, multiprocessing_context=None, ): torch._C._log_api_usage_once("python.data_loader") if num_workers < 0: raise ValueError( "num_workers option should be non-negative; " "use num_workers=0 to disable multiprocessing." ) if timeout < 0: raise ValueError("timeout option should be non-negative") self.dataset = dataset self.num_workers = num_workers self.pin_memory = pin_memory self.timeout = timeout self.worker_init_fn = worker_init_fn self.multiprocessing_context = multiprocessing_context # Arg-check dataset related before checking samplers because we want to # tell users that iterable-style datasets are incompatible with custom # samplers first, so that they don't learn that this combo doesn't work # after spending time fixing the custom sampler errors. if isinstance(dataset, IterableDataset): self._dataset_kind = _DatasetKind.Iterable # NOTE [ Custom Samplers and `IterableDataset` ] # # `IterableDataset` does not support custom `batch_sampler` or # `sampler` since the key is irrelevant (unless we support # generator-style dataset one day...). # # For `sampler`, we always create a dummy sampler. This is an # infinite sampler even when the dataset may have an implemented # finite `__len__` because in multi-process data loading, naive # settings will return duplicated data (which may be desired), and # thus using a sampler with length matching that of dataset will # cause data lost (you may have duplicates of the first couple # batches, but never see anything afterwards). Therefore, # `Iterabledataset` always uses an infinite sampler, an instance of # `_InfiniteConstantSampler` defined above. # # A custom `batch_sampler` essentially only controls the batch size. # However, it is unclear how useful it would be since an iterable-style # dataset can handle that within itself. Moreover, it is pointless # in multi-process data loading as the assignment order of batches # to workers is an implementation detail so users can not control # how to batchify each worker's iterable. Thus, we disable this # option. If this turns out to be useful in future, we can re-enable # this, and support custom samplers that specify the assignments to # specific workers. if shuffle is not False: raise ValueError( "DataLoader with IterableDataset: expected unspecified " "shuffle option, but got shuffle={}".format(shuffle) ) elif sampler is not None: # See NOTE [ Custom Samplers and IterableDataset ] raise ValueError( "DataLoader with IterableDataset: expected unspecified " "sampler option, but got sampler={}".format(sampler) ) elif batch_sampler is not None: # See NOTE [ Custom Samplers and IterableDataset ] raise ValueError( "DataLoader with IterableDataset: expected unspecified " "batch_sampler option, but got batch_sampler={}".format( batch_sampler ) ) else: self._dataset_kind = _DatasetKind.Map if sampler is not None and shuffle: raise ValueError("sampler option is mutually exclusive with " "shuffle") if batch_sampler is not None: # auto_collation with custom batch_sampler if batch_size != 1 or shuffle or sampler is not None or drop_last: raise ValueError( "batch_sampler option is mutually exclusive " "with batch_size, shuffle, sampler, and " "drop_last" ) batch_size = None drop_last = False elif batch_size is None: # no auto_collation if shuffle or drop_last: raise ValueError( "batch_size=None option disables auto-batching " "and is mutually exclusive with " "shuffle, and drop_last" ) if sampler is None: # give default samplers if self._dataset_kind == _DatasetKind.Iterable: # See NOTE [ Custom Samplers and IterableDataset ] sampler = _InfiniteConstantSampler() else: # map-style if shuffle: sampler = RandomSampler(dataset) else: sampler = SequentialSampler(dataset) if batch_size is not None and batch_sampler is None: # auto_collation without custom batch_sampler batch_sampler = BatchSampler(sampler, batch_size, drop_last) self.batch_size = batch_size self.drop_last = drop_last self.sampler = sampler self.batch_sampler = batch_sampler if collate_fn is None: if self._auto_collation: collate_fn = _utils.collate.default_collate else: collate_fn = _utils.collate.default_convert self.collate_fn = collate_fn self.__initialized = True self._IterableDataset_len_called = ( None # See NOTE [ IterableDataset and __len__ ] ) @property def multiprocessing_context(self): return self.__multiprocessing_context @multiprocessing_context.setter def multiprocessing_context(self, multiprocessing_context): if multiprocessing_context is not None: if self.num_workers > 0: if not multiprocessing._supports_context: raise ValueError( "multiprocessing_context relies on Python >= 3.4, with " "support for different start methods" ) if isinstance(multiprocessing_context, string_classes): valid_start_methods = multiprocessing.get_all_start_methods() if multiprocessing_context not in valid_start_methods: raise ValueError( ( "multiprocessing_context option " "should specify a valid start method in {}, but got " "multiprocessing_context={}" ).format(valid_start_methods, multiprocessing_context) ) multiprocessing_context = multiprocessing.get_context( multiprocessing_context ) if not isinstance( multiprocessing_context, python_multiprocessing.context.BaseContext ): raise ValueError( ( "multiprocessing_context option should be a valid context " "object or a string specifying the start method, but got " "multiprocessing_context={}" ).format(multiprocessing_context) ) else: raise ValueError( ( "multiprocessing_context can only be used with " "multi-process loading (num_workers > 0), but got " "num_workers={}" ).format(self.num_workers) ) self.__multiprocessing_context = multiprocessing_context def __setattr__(self, attr, val): if self.__initialized and attr in ( "batch_size", "batch_sampler", "sampler", "drop_last", "dataset", ): raise ValueError( "{} attribute should not be set after {} is " "initialized".format(attr, self.__class__.__name__) ) super(MyDataLoader, self).__setattr__(attr, val) def __iter__(self): if self.num_workers == 0: return _SingleProcessDataLoaderIter(self) else: return _MultiProcessingDataLoaderIter(self) @property def _auto_collation(self): return self.batch_sampler is not None @property def _index_sampler(self): # The actual sampler used for generating indices for `_DatasetFetcher` # (see _utils/fetch.py) to read data at each time. This would be # `.batch_sampler` if in auto-collation mode, and `.sampler` otherwise. # We can't change `.sampler` and `.batch_sampler` attributes for BC # reasons. if self._auto_collation: return self.batch_sampler else: return self.sampler def __len__(self): if self._dataset_kind == _DatasetKind.Iterable: # NOTE [ IterableDataset and __len__ ] # # For `IterableDataset`, `__len__` could be inaccurate when one naively # does multi-processing data loading, since the samples will be duplicated. # However, no real use case should be actually using that behavior, so # it should count as a user error. We should generally trust user # code to do the proper thing (e.g., configure each replica differently # in `__iter__`), and give us the correct `__len__` if they choose to # implement it (this will still throw if the dataset does not implement # a `__len__`). # # To provide a further warning, we track if `__len__` was called on the # `DataLoader`, save the returned value in `self._len_called`, and warn # if the iterator ends up yielding more than this number of samples. length = self._IterableDataset_len_called = len(self.dataset) return length else: return len(self._index_sampler) class _BaseDataLoaderIter(object): def __init__(self, loader): self._dataset = loader.dataset self._dataset_kind = loader._dataset_kind self._IterableDataset_len_called = loader._IterableDataset_len_called self._auto_collation = loader._auto_collation self._drop_last = loader.drop_last self._index_sampler = loader._index_sampler self._num_workers = loader.num_workers self._pin_memory = loader.pin_memory and torch.cuda.is_available() self._timeout = loader.timeout self._collate_fn = loader.collate_fn self._sampler_iter = iter(self._index_sampler) self._base_seed = torch.empty((), dtype=torch.int64).random_().item() self._num_yielded = 0 def __iter__(self): return self def _next_index(self): return next(self._sampler_iter) # may raise StopIteration def _next_data(self): raise NotImplementedError def __next__(self): data = self._next_data() self._num_yielded += 1 if ( self._dataset_kind == _DatasetKind.Iterable and self._IterableDataset_len_called is not None and self._num_yielded > self._IterableDataset_len_called ): warn_msg = ( "Length of IterableDataset {} was reported to be {} (when accessing len(dataloader)), but {} " "samples have been fetched. " ).format(self._dataset, self._IterableDataset_len_called, self._num_yielded) if self._num_workers > 0: warn_msg += ( "For multiprocessing data-loading, this could be caused by not properly configuring the " "IterableDataset replica at each worker. Please see " "https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset for examples." ) warnings.warn(warn_msg) return data next = __next__ # Python 2 compatibility def __len__(self): return len(self._index_sampler) def __getstate__(self): # across multiple threads for HOGWILD. # Probably the best way to do this is by moving the sample pushing # to a separate thread and then just sharing the data queue # but signalling the end is tricky without a non-blocking API raise NotImplementedError("{} cannot be pickled", self.__class__.__name__) class _SingleProcessDataLoaderIter(_BaseDataLoaderIter): def __init__(self, loader): super(_SingleProcessDataLoaderIter, self).__init__(loader) assert self._timeout == 0 assert self._num_workers == 0 self._dataset_fetcher = _DatasetKind.create_fetcher( self._dataset_kind, self._dataset, self._auto_collation, self._collate_fn, self._drop_last, ) def _next_data(self): index = self._next_index() # may raise StopIteration data = self._dataset_fetcher.fetch(index) # may raise StopIteration if self._pin_memory: data = _utils.pin_memory.pin_memory(data) return data class _MultiProcessingDataLoaderIter(_BaseDataLoaderIter): r"""Iterates once over the DataLoader's dataset, as specified by the sampler""" # NOTE [ Data Loader Multiprocessing Shutdown Logic ] # # Preliminary: # # Our data model looks like this (queues are indicated with curly brackets): # # main process || # | || # {index_queue} || # | || # worker processes || DATA # | || # {worker_result_queue} || FLOW # | || # pin_memory_thread of main process || DIRECTION # | || # {data_queue} || # | || # data output \/ # # P.S. `worker_result_queue` and `pin_memory_thread` part may be omitted if # `pin_memory=False`. # # # Terminating multiprocessing logic requires very careful design. In # particular, we need to make sure that # # 1. The iterator gracefully exits the workers when its last reference is # gone or it is depleted. # # In this case, the workers should be gracefully exited because the # main process may still need to continue to run, and we want cleaning # up code in the workers to be executed (e.g., releasing GPU memory). # Naturally, we implement the shutdown logic in `__del__` of # DataLoaderIterator. # # We delay the discussion on the logic in this case until later. # # 2. The iterator exits the workers when the loader process and/or worker # processes exits normally or with error. # # We set all workers and `pin_memory_thread` to have `daemon=True`. # # You may ask, why can't we make the workers non-daemonic, and # gracefully exit using the same logic as we have in `__del__` when the # iterator gets deleted (see 1 above)? # # First of all, `__del__` is **not** guaranteed to be called when # interpreter exits. Even if it is called, by the time it executes, # many Python core library resources may alreay be freed, and even # simple things like acquiring an internal lock of a queue may hang. # Therefore, in this case, we actually need to prevent `__del__` from # being executed, and rely on the automatic termination of daemonic # children. Thus, we register an `atexit` hook that sets a global flag # `_utils.python_exit_status`. Since `atexit` hooks are executed in the # reverse order of registration, we are guaranteed that this flag is # set before library resources we use are freed. (Hooks freeing those # resources are registered at importing the Python core libraries at # the top of this file.) So in `__del__`, we check if # `_utils.python_exit_status` is set or `None` (freed), and perform # no-op if so. # # Another problem with `__del__` is also related to the library cleanup # calls. When a process ends, it shuts the all its daemonic children # down with a SIGTERM (instead of joining them without a timeout). # Simiarly for threads, but by a different mechanism. This fact, # together with a few implementation details of multiprocessing, forces # us to make workers daemonic. All of our problems arise when a # DataLoader is used in a subprocess, and are caused by multiprocessing # code which looks more or less like this: # # try: # your_function_using_a_dataloader() # finally: # multiprocessing.util._exit_function() # # The joining/termination mentioned above happens inside # `_exit_function()`. Now, if `your_function_using_a_dataloader()` # throws, the stack trace stored in the exception will prevent the # frame which uses `DataLoaderIter` to be freed. If the frame has any # reference to the `DataLoaderIter` (e.g., in a method of the iter), # its `__del__`, which starts the shutdown procedure, will not be # called. That, in turn, means that workers aren't notified. Attempting # to join in `_exit_function` will then result in a hang. # # For context, `_exit_function` is also registered as an `atexit` call. # So it is unclear to me (@ssnl) why this is needed in a finally block. # The code dates back to 2008 and there is no comment on the original # PEP 371 or patch https://bugs.python.org/issue3050 (containing both # the finally block and the `atexit` registration) that explains this. # # Another choice is to just shutdown workers with logic in 1 above # whenever we see an error in `next`. This isn't ideal because # a. It prevents users from using try-catch to resume data loading. # b. It doesn't prevent hanging if users have references to the # iterator. # # 3. All processes exit if any of them die unexpectedly by fatal signals. # # As shown above, the workers are set as daemonic children of the main # process. However, automatic cleaning-up of such child processes only # happens if the parent process exits gracefully (e.g., not via fatal # signals like SIGKILL). So we must ensure that each process will exit # even the process that should send/receive data to/from it were # killed, i.e., # # a. A process won't hang when getting from a queue. # # Even with carefully designed data dependencies (i.e., a `put()` # always corresponding to a `get()`), hanging on `get()` can still # happen when data in queue is corrupted (e.g., due to # `cancel_join_thread` or unexpected exit). # # For child exit, we set a timeout whenever we try to get data # from `data_queue`, and check the workers' status on each timeout # and error. # See `_DataLoaderiter._get_batch()` and # `_DataLoaderiter._try_get_data()` for details. # # Additionally, for child exit on non-Windows platforms, we also # register a SIGCHLD handler (which is supported on Windows) on # the main process, which checks if any of the workers fail in the # (Python) handler. This is more efficient and faster in detecting # worker failures, compared to only using the above mechanism. # See `DataLoader.cpp` and `_utils/signal_handling.py` for details. # # For `.get()` calls where the sender(s) is not the workers, we # guard them with timeouts, and check the status of the sender # when timeout happens: # + in the workers, the `_utils.worker.ManagerWatchdog` class # checks the status of the main process. # + if `pin_memory=True`, when getting from `pin_memory_thread`, # check `pin_memory_thread` status periodically until `.get()` # returns or see that `pin_memory_thread` died. # # b. A process won't hang when putting into a queue; # # We use `mp.Queue` which has a separate background thread to put # objects from an unbounded buffer array. The background thread is # daemonic and usually automatically joined when the process # exits. # # However, in case that the receiver has ended abruptly while # reading from the pipe, the join will hang forever. Therefore, # for both `worker_result_queue` (worker -> main process/pin_memory_thread) # and each `index_queue` (main process -> worker), we use # `q.cancel_join_thread()` in sender process before any `q.put` to # prevent this automatic join. # # Moreover, having all queues called `cancel_join_thread` makes # implementing graceful shutdown logic in `__del__` much easier. # It won't need to get from any queue, which would also need to be # guarded by periodic status checks. # # Nonetheless, `cancel_join_thread` must only be called when the # queue is **not** going to be read from or write into by another # process, because it may hold onto a lock or leave corrupted data # in the queue, leading other readers/writers to hang. # # `pin_memory_thread`'s `data_queue` is a `queue.Queue` that does # a blocking `put` if the queue is full. So there is no above # problem, but we do need to wrap the `put` in a loop that breaks # not only upon success, but also when the main process stops # reading, i.e., is shutting down. # # # Now let's get back to 1: # how we gracefully exit the workers when the last reference to the # iterator is gone. # # To achieve this, we implement the following logic along with the design # choices mentioned above: # # `workers_done_event`: # A `multiprocessing.Event` shared among the main process and all worker # processes. This is used to signal the workers that the iterator is # shutting down. After it is set, they will not send processed data to # queues anymore, and only wait for the final `None` before exiting. # `done_event` isn't strictly needed. I.e., we can just check for `None` # from the input queue, but it allows us to skip wasting resources # processing data if we are already shutting down. # # `pin_memory_thread_done_event`: # A `threading.Event` for a similar purpose to that of # `workers_done_event`, but is for the `pin_memory_thread`. The reason # that separate events are needed is that `pin_memory_thread` reads from # the output queue of the workers. But the workers, upon seeing that # `workers_done_event` is set, only wants to see the final `None`, and is # not required to flush all data in the output queue (e.g., it may call # `cancel_join_thread` on that queue if its `IterableDataset` iterator # happens to exhaust coincidentally, which is out of the control of the # main process). Thus, since we will exit `pin_memory_thread` before the # workers (see below), two separete events are used. # # NOTE: In short, the protocol is that the main process will set these # `done_event`s and then the corresponding processes/threads a `None`, # and that they may exit at any time after receiving the `None`. # # NOTE: Using `None` as the final signal is valid, since normal data will # always be a 2-tuple with the 1st element being the index of the data # transferred (different from dataset index/key), and the 2nd being # either the dataset key or the data sample (depending on which part # of the data model the queue is at). # # [ worker processes ] # While loader process is alive: # Get from `index_queue`. # If get anything else, # Check `workers_done_event`. # If set, continue to next iteration # i.e., keep getting until see the `None`, then exit. # Otherwise, process data: # If is fetching from an `IterableDataset` and the iterator # is exhausted, send an `_IterableDatasetStopIteration` # object to signal iteration end. The main process, upon # receiving such an object, will send `None` to this # worker and not use the corresponding `index_queue` # anymore. # If timed out, # No matter `workers_done_event` is set (still need to see `None`) # or not, must continue to next iteration. # (outside loop) # If `workers_done_event` is set, (this can be False with `IterableDataset`) # `data_queue.cancel_join_thread()`. (Everything is ending here: # main process won't read from it; # other workers will also call # `cancel_join_thread`.) # # [ pin_memory_thread ] # # No need to check main thread. If this thread is alive, the main loader # # thread must be alive, because this thread is set as daemonic. # While `pin_memory_thread_done_event` is not set: # Get from `index_queue`. # If timed out, continue to get in the next iteration. # Otherwise, process data. # While `pin_memory_thread_done_event` is not set: # Put processed data to `data_queue` (a `queue.Queue` with blocking put) # If timed out, continue to put in the next iteration. # Otherwise, break, i.e., continuing to the out loop. # # NOTE: we don't check the status of the main thread because # 1. if the process is killed by fatal signal, `pin_memory_thread` # ends. # 2. in other cases, either the cleaning-up in __del__ or the # automatic exit of daemonic thread will take care of it. # This won't busy-wait either because `.get(timeout)` does not # busy-wait. # # [ main process ] # In the DataLoader Iter's `__del__` # b. Exit `pin_memory_thread` # i. Set `pin_memory_thread_done_event`. # ii Put `None` in `worker_result_queue`. # iii. Join the `pin_memory_thread`. # iv. `worker_result_queue.cancel_join_thread()`. # # c. Exit the workers. # i. Set `workers_done_event`. # ii. Put `None` in each worker's `index_queue`. # iii. Join the workers. # iv. Call `.cancel_join_thread()` on each worker's `index_queue`. # # NOTE: (c) is better placed after (b) because it may leave corrupted # data in `worker_result_queue`, which `pin_memory_thread` # reads from, in which case the `pin_memory_thread` can only # happen at timeing out, which is slow. Nonetheless, same thing # happens if a worker is killed by signal at unfortunate times, # but in other cases, we are better off having a non-corrupted # `worker_result_queue` for `pin_memory_thread`. # # NOTE: If `pin_memory=False`, there is no `pin_memory_thread` and (b) # can be omitted # # NB: `done_event`s isn't strictly needed. E.g., we can just check for # `None` from `index_queue`, but it allows us to skip wasting resources # processing indices already in `index_queue` if we are already shutting # down. def __init__(self, loader): super(_MultiProcessingDataLoaderIter, self).__init__(loader) assert self._num_workers > 0 if loader.multiprocessing_context is None: multiprocessing_context = multiprocessing else: multiprocessing_context = loader.multiprocessing_context self._worker_init_fn = loader.worker_init_fn self._worker_queue_idx_cycle = itertools.cycle(range(self._num_workers)) self._worker_result_queue = multiprocessing_context.Queue() self._worker_pids_set = False self._shutdown = False self._send_idx = 0 # idx of the next task to be sent to workers self._rcvd_idx = 0 # idx of the next task to be returned in __next__ # information about data not yet yielded, i.e., tasks w/ indices in range [rcvd_idx, send_idx). # map: task idx => - (worker_id,) if data isn't fetched (outstanding) # \ (worker_id, data) if data is already fetched (out-of-order) self._task_info = {} self._tasks_outstanding = ( 0 # always equal to count(v for v in task_info.values() if len(v) == 1) ) self._workers_done_event = multiprocessing_context.Event() self._index_queues = [] self._workers = [] # A list of booleans representing whether each worker still has work to # do, i.e., not having exhausted its iterable dataset object. It always # contains all `True`s if not using an iterable-style dataset # (i.e., if kind != Iterable). self._workers_status = [] for i in range(self._num_workers): index_queue = multiprocessing_context.Queue() # index_queue.cancel_join_thread() w = multiprocessing_context.Process( target=worker_loop, args=( self._dataset_kind, self._dataset, index_queue, self._worker_result_queue, self._workers_done_event, self._auto_collation, self._collate_fn, self._drop_last, self._base_seed + i, self._worker_init_fn, i, self._num_workers, ), ) w.daemon = True # NB: Process.start() actually take some time as it needs to # start a process and pass the arguments over via a pipe. # Therefore, we only add a worker to self._workers list after # it started, so that we do not call .join() if program dies # before it starts, and __del__ tries to join but will get: # AssertionError: can only join a started process. w.start() self._index_queues.append(index_queue) self._workers.append(w) self._workers_status.append(True) if self._pin_memory: self._pin_memory_thread_done_event = threading.Event() self._data_queue = queue.Queue() pin_memory_thread = threading.Thread( target=_utils.pin_memory._pin_memory_loop, args=( self._worker_result_queue, self._data_queue, torch.cuda.current_device(), self._pin_memory_thread_done_event, ), ) pin_memory_thread.daemon = True pin_memory_thread.start() # Similar to workers (see comment above), we only register # pin_memory_thread once it is started. self._pin_memory_thread = pin_memory_thread else: self._data_queue = self._worker_result_queue _utils.signal_handling._set_worker_pids( id(self), tuple(w.pid for w in self._workers) ) _utils.signal_handling._set_SIGCHLD_handler() self._worker_pids_set = True # prime the prefetch loop for _ in range(2 * self._num_workers): self._try_put_index() def _try_get_data(self, timeout=_utils.MP_STATUS_CHECK_INTERVAL): # Tries to fetch data from `self._data_queue` once for a given timeout. # This can also be used as inner loop of fetching without timeout, with # the sender status as the loop condition. # # This raises a `RuntimeError` if any worker died expectedly. This error # can come from either the SIGCHLD handler in `_utils/signal_handling.py` # (only for non-Windows platforms), or the manual check below on errors # and timeouts. # # Returns a 2-tuple: # (bool: whether successfully get data, any: data if successful else None) try: data = self._data_queue.get(timeout=timeout) return (True, data) except Exception as e: # At timeout and error, we manually check whether any worker has # failed. Note that this is the only mechanism for Windows to detect # worker failures. failed_workers = [] for worker_id, w in enumerate(self._workers): if self._workers_status[worker_id] and not w.is_alive(): failed_workers.append(w) self._shutdown_worker(worker_id) if len(failed_workers) > 0: pids_str = ", ".join(str(w.pid) for w in failed_workers) raise RuntimeError( "DataLoader worker (pid(s) {}) exited unexpectedly".format(pids_str) ) if isinstance(e, queue.Empty): return (False, None) raise def _get_data(self): # Fetches data from `self._data_queue`. # # We check workers' status every `MP_STATUS_CHECK_INTERVAL` seconds, # which we achieve by running `self._try_get_data(timeout=MP_STATUS_CHECK_INTERVAL)` # in a loop. This is the only mechanism to detect worker failures for # Windows. For other platforms, a SIGCHLD handler is also used for # worker failure detection. # # If `pin_memory=True`, we also need check if `pin_memory_thread` had # died at timeouts. if self._timeout > 0: success, data = self._try_get_data(self._timeout) if success: return data else: raise RuntimeError( "DataLoader timed out after {} seconds".format(self._timeout) ) elif self._pin_memory: while self._pin_memory_thread.is_alive(): success, data = self._try_get_data() if success: return data else: # while condition is false, i.e., pin_memory_thread died. raise RuntimeError("Pin memory thread exited unexpectedly") # In this case, `self._data_queue` is a `queue.Queue`,. But we don't # need to call `.task_done()` because we don't use `.join()`. else: while True: success, data = self._try_get_data() if success: return data def _next_data(self): while True: # If the worker responsible for `self._rcvd_idx` has already ended # and was unable to fulfill this task (due to exhausting an `IterableDataset`), # we try to advance `self._rcvd_idx` to find the next valid index. # # This part needs to run in the loop because both the `self._get_data()` # call and `_IterableDatasetStopIteration` check below can mark # extra worker(s) as dead. while self._rcvd_idx < self._send_idx: info = self._task_info[self._rcvd_idx] worker_id = info[0] if ( len(info) == 2 or self._workers_status[worker_id] ): # has data or is still active break del self._task_info[self._rcvd_idx] self._rcvd_idx += 1 else: # no valid `self._rcvd_idx` is found (i.e., didn't break) self._shutdown_workers() raise StopIteration # Now `self._rcvd_idx` is the batch index we want to fetch # Check if the next sample has already been generated if len(self._task_info[self._rcvd_idx]) == 2: data = self._task_info.pop(self._rcvd_idx)[1] return self._process_data(data) assert not self._shutdown and self._tasks_outstanding > 0 idx, data = self._get_data() self._tasks_outstanding -= 1 if self._dataset_kind == _DatasetKind.Iterable: # Check for _IterableDatasetStopIteration if isinstance(data, _utils.worker._IterableDatasetStopIteration): self._shutdown_worker(data.worker_id) self._try_put_index() continue if idx != self._rcvd_idx: # store out-of-order samples self._task_info[idx] += (data,) else: del self._task_info[idx] return self._process_data(data) def _try_put_index(self): assert self._tasks_outstanding < 2 * self._num_workers try: index = self._next_index() except StopIteration: return for _ in range(self._num_workers): # find the next active worker, if any worker_queue_idx = next(self._worker_queue_idx_cycle) if self._workers_status[worker_queue_idx]: break else: # not found (i.e., didn't break) return self._index_queues[worker_queue_idx].put((self._send_idx, index)) self._task_info[self._send_idx] = (worker_queue_idx,) self._tasks_outstanding += 1 self._send_idx += 1 def _process_data(self, data): self._rcvd_idx += 1 self._try_put_index() if isinstance(data, ExceptionWrapper): data.reraise() return data def _shutdown_worker(self, worker_id): # Mark a worker as having finished its work and dead, e.g., due to # exhausting an `IterableDataset`. This should be used only when this # `_MultiProcessingDataLoaderIter` is going to continue running. assert self._workers_status[worker_id] # Signal termination to that specific worker. q = self._index_queues[worker_id] # Indicate that no more data will be put on this queue by the current # process. q.put(None) # Note that we don't actually join the worker here, nor do we remove the # worker's pid from C side struct because (1) joining may be slow, and # (2) since we don't join, the worker may still raise error, and we # prefer capturing those, rather than ignoring them, even though they # are raised after the worker has finished its job. # Joinning is deferred to `_shutdown_workers`, which it is called when # all workers finish their jobs (e.g., `IterableDataset` replicas) or # when this iterator is garbage collected. self._workers_status[worker_id] = False def _shutdown_workers(self): # Called when shutting down this `_MultiProcessingDataLoaderIter`. # See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on # the logic of this function. python_exit_status = _utils.python_exit_status if python_exit_status is True or python_exit_status is None: # See (2) of the note. If Python is shutting down, do no-op. return # Normal exit when last reference is gone / iterator is depleted. # See (1) and the second half of the note. if not self._shutdown: self._shutdown = True try: # Exit `pin_memory_thread` first because exiting workers may leave # corrupted data in `worker_result_queue` which `pin_memory_thread` # reads from. if hasattr(self, "_pin_memory_thread"): # Use hasattr in case error happens before we set the attribute. self._pin_memory_thread_done_event.set() # Send something to pin_memory_thread in case it is waiting # so that it can wake up and check `pin_memory_thread_done_event` self._worker_result_queue.put((None, None)) self._pin_memory_thread.join() self._worker_result_queue.close() # Exit workers now. self._workers_done_event.set() for worker_id in range(len(self._workers)): # Get number of workers from `len(self._workers)` instead of # `self._num_workers` in case we error before starting all # workers. if self._workers_status[worker_id]: self._shutdown_worker(worker_id) for w in self._workers: w.join() for q in self._index_queues: q.cancel_join_thread() q.close() finally: # Even though all this function does is putting into queues that # we have called `cancel_join_thread` on, weird things can # happen when a worker is killed by a signal, e.g., hanging in # `Event.set()`. So we need to guard this with SIGCHLD handler, # and remove pids from the C side data structure only at the # end. # # FIXME: Unfortunately, for Windows, we are missing a worker # error detection mechanism here in this function, as it # doesn't provide a SIGCHLD handler. if self._worker_pids_set: _utils.signal_handling._remove_worker_pids(id(self)) self._worker_pids_set = False def __del__(self): self._shutdown_workers()
from .my_data_loader import * from .my_data_worker import * from .my_distributed_sampler import * from .my_random_resize_crop import *
r""""Contains definitions of the methods used by the _BaseDataLoaderIter workers. These **needs** to be in global scope since Py2 doesn't support serializing static methods. """ import torch import random import os from collections import namedtuple # from torch._six import queue from torch.multiprocessing import Queue as queue from torch._utils import ExceptionWrapper from torch.utils.data._utils import ( signal_handling, MP_STATUS_CHECK_INTERVAL, IS_WINDOWS, ) from .my_random_resize_crop import MyRandomResizedCrop __all__ = ["worker_loop"] if IS_WINDOWS: import ctypes from ctypes.wintypes import DWORD, BOOL, HANDLE # On Windows, the parent ID of the worker process remains unchanged when the manager process # is gone, and the only way to check it through OS is to let the worker have a process handle # of the manager and ask if the process status has changed. class ManagerWatchdog(object): def __init__(self): self.manager_pid = os.getppid() self.kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) self.kernel32.OpenProcess.argtypes = (DWORD, BOOL, DWORD) self.kernel32.OpenProcess.restype = HANDLE self.kernel32.WaitForSingleObject.argtypes = (HANDLE, DWORD) self.kernel32.WaitForSingleObject.restype = DWORD # Value obtained from https://msdn.microsoft.com/en-us/library/ms684880.aspx SYNCHRONIZE = 0x00100000 self.manager_handle = self.kernel32.OpenProcess( SYNCHRONIZE, 0, self.manager_pid ) if not self.manager_handle: raise ctypes.WinError(ctypes.get_last_error()) self.manager_dead = False def is_alive(self): if not self.manager_dead: # Value obtained from https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032.aspx self.manager_dead = ( self.kernel32.WaitForSingleObject(self.manager_handle, 0) == 0 ) return not self.manager_dead else: class ManagerWatchdog(object): def __init__(self): self.manager_pid = os.getppid() self.manager_dead = False def is_alive(self): if not self.manager_dead: self.manager_dead = os.getppid() != self.manager_pid return not self.manager_dead _worker_info = None class WorkerInfo(object): __initialized = False def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) self.__initialized = True def __setattr__(self, key, val): if self.__initialized: raise RuntimeError( "Cannot assign attributes to {} objects".format(self.__class__.__name__) ) return super(WorkerInfo, self).__setattr__(key, val) def get_worker_info(): r"""Returns the information about the current :class:`~torch.utils.data.DataLoader` iterator worker process. When called in a worker, this returns an object guaranteed to have the following attributes: * :attr:`id`: the current worker id. * :attr:`num_workers`: the total number of workers. * :attr:`seed`: the random seed set for the current worker. This value is determined by main process RNG and the worker id. See :class:`~torch.utils.data.DataLoader`'s documentation for more details. * :attr:`dataset`: the copy of the dataset object in **this** process. Note that this will be a different object in a different process than the one in the main process. When called in the main process, this returns ``None``. .. note:: When used in a :attr:`worker_init_fn` passed over to :class:`~torch.utils.data.DataLoader`, this method can be useful to set up each worker process differently, for instance, using ``worker_id`` to configure the ``dataset`` object to only read a specific fraction of a sharded dataset, or use ``seed`` to seed other libraries used in dataset code (e.g., NumPy). """ return _worker_info r"""Dummy class used to signal the end of an IterableDataset""" _IterableDatasetStopIteration = namedtuple( "_IterableDatasetStopIteration", ["worker_id"] ) def worker_loop( dataset_kind, dataset, index_queue, data_queue, done_event, auto_collation, collate_fn, drop_last, seed, init_fn, worker_id, num_workers, ): # See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on the # logic of this function. try: # Intialize C side signal handlers for SIGBUS and SIGSEGV. Python signal # module's handlers are executed after Python returns from C low-level # handlers, likely when the same fatal signal had already happened # again. # https://docs.python.org/3/library/signal.html#execution-of-python-signal-handlers signal_handling._set_worker_signal_handlers() torch.set_num_threads(1) random.seed(seed) torch.manual_seed(seed) global _worker_info _worker_info = WorkerInfo( id=worker_id, num_workers=num_workers, seed=seed, dataset=dataset ) from torch.utils.data import _DatasetKind init_exception = None try: if init_fn is not None: init_fn(worker_id) fetcher = _DatasetKind.create_fetcher( dataset_kind, dataset, auto_collation, collate_fn, drop_last ) except Exception: init_exception = ExceptionWrapper( where="in DataLoader worker process {}".format(worker_id) ) # When using Iterable mode, some worker can exit earlier than others due # to the IterableDataset behaving differently for different workers. # When such things happen, an `_IterableDatasetStopIteration` object is # sent over to the main process with the ID of this worker, so that the # main process won't send more tasks to this worker, and will send # `None` to this worker to properly exit it. # # Note that we cannot set `done_event` from a worker as it is shared # among all processes. Instead, we set the `iteration_end` flag to # signify that the iterator is exhausted. When either `done_event` or # `iteration_end` is set, we skip all processing step and just wait for # `None`. iteration_end = False watchdog = ManagerWatchdog() while watchdog.is_alive(): try: r = index_queue.get(timeout=MP_STATUS_CHECK_INTERVAL) except queue.Empty: continue if r is None: # Received the final signal assert done_event.is_set() or iteration_end break elif done_event.is_set() or iteration_end: # `done_event` is set. But I haven't received the final signal # (None) yet. I will keep continuing until get it, and skip the # processing steps. continue idx, index = r """ Added """ MyRandomResizedCrop.sample_image_size(idx) """ Added """ if init_exception is not None: data = init_exception init_exception = None else: try: data = fetcher.fetch(index) except Exception as e: if ( isinstance(e, StopIteration) and dataset_kind == _DatasetKind.Iterable ): data = _IterableDatasetStopIteration(worker_id) # Set `iteration_end` # (1) to save future `next(...)` calls, and # (2) to avoid sending multiple `_IterableDatasetStopIteration`s. iteration_end = True else: # It is important that we don't store exc_info in a variable. # `ExceptionWrapper` does the correct thing. # See NOTE [ Python Traceback Reference Cycle Problem ] data = ExceptionWrapper( where="in DataLoader worker process {}".format(worker_id) ) data_queue.put((idx, data)) del data, idx, index, r # save memory except KeyboardInterrupt: # Main process will raise KeyboardInterrupt anyways. pass if done_event.is_set(): data_queue.cancel_join_thread() data_queue.close()
import time import random import math import os from PIL import Image import torchvision.transforms.functional as F import torchvision.transforms as transforms __all__ = ["MyRandomResizedCrop", "MyResizeRandomCrop", "MyResize"] _pil_interpolation_to_str = { Image.NEAREST: "PIL.Image.NEAREST", Image.BILINEAR: "PIL.Image.BILINEAR", Image.BICUBIC: "PIL.Image.BICUBIC", Image.LANCZOS: "PIL.Image.LANCZOS", Image.HAMMING: "PIL.Image.HAMMING", Image.BOX: "PIL.Image.BOX", } class MyRandomResizedCrop(transforms.RandomResizedCrop): ACTIVE_SIZE = 224 IMAGE_SIZE_LIST = [224] IMAGE_SIZE_SEG = 4 CONTINUOUS = False SYNC_DISTRIBUTED = True EPOCH = 0 BATCH = 0 def __init__( self, size, scale=(0.08, 1.0), ratio=(3.0 / 4.0, 4.0 / 3.0), interpolation=Image.BILINEAR, ): if not isinstance(size, int): size = size[0] super(MyRandomResizedCrop, self).__init__(size, scale, ratio, interpolation) def __call__(self, img): i, j, h, w = self.get_params(img, self.scale, self.ratio) return F.resized_crop( img, i, j, h, w, (MyRandomResizedCrop.ACTIVE_SIZE, MyRandomResizedCrop.ACTIVE_SIZE), self.interpolation, ) @staticmethod def get_candidate_image_size(): if MyRandomResizedCrop.CONTINUOUS: min_size = min(MyRandomResizedCrop.IMAGE_SIZE_LIST) max_size = max(MyRandomResizedCrop.IMAGE_SIZE_LIST) candidate_sizes = [] for i in range(min_size, max_size + 1): if i % MyRandomResizedCrop.IMAGE_SIZE_SEG == 0: candidate_sizes.append(i) else: candidate_sizes = MyRandomResizedCrop.IMAGE_SIZE_LIST relative_probs = None return candidate_sizes, relative_probs @staticmethod def sample_image_size(batch_id=None): if batch_id is None: batch_id = MyRandomResizedCrop.BATCH if MyRandomResizedCrop.SYNC_DISTRIBUTED: _seed = int("%d%.3d" % (batch_id, MyRandomResizedCrop.EPOCH)) else: _seed = os.getpid() + time.time() random.seed(_seed) candidate_sizes, relative_probs = MyRandomResizedCrop.get_candidate_image_size() MyRandomResizedCrop.ACTIVE_SIZE = random.choices( candidate_sizes, weights=relative_probs )[0] def __repr__(self): interpolate_str = _pil_interpolation_to_str[self.interpolation] format_string = self.__class__.__name__ + "(size={0}".format( MyRandomResizedCrop.IMAGE_SIZE_LIST ) if MyRandomResizedCrop.CONTINUOUS: format_string += "@continuous" format_string += ", scale={0}".format(tuple(round(s, 4) for s in self.scale)) format_string += ", ratio={0}".format(tuple(round(r, 4) for r in self.ratio)) format_string += ", interpolation={0})".format(interpolate_str) return format_string class MyResizeRandomCrop(object): def __init__( self, interpolation=Image.BILINEAR, use_padding=False, pad_if_needed=False, fill=0, padding_mode="constant", ): # resize self.interpolation = interpolation # random crop self.use_padding = use_padding self.pad_if_needed = pad_if_needed self.fill = fill self.padding_mode = padding_mode def __call__(self, img): crop_size = MyRandomResizedCrop.ACTIVE_SIZE if not self.use_padding: resize_size = int(math.ceil(crop_size / 0.875)) img = F.resize(img, resize_size, self.interpolation) else: img = F.resize(img, crop_size, self.interpolation) padding_size = crop_size // 8 img = F.pad(img, padding_size, self.fill, self.padding_mode) # pad the width if needed if self.pad_if_needed and img.size[0] < crop_size: img = F.pad(img, (crop_size - img.size[0], 0), self.fill, self.padding_mode) # pad the height if needed if self.pad_if_needed and img.size[1] < crop_size: img = F.pad(img, (0, crop_size - img.size[1]), self.fill, self.padding_mode) i, j, h, w = transforms.RandomCrop.get_params(img, (crop_size, crop_size)) return F.crop(img, i, j, h, w) def __repr__(self): return ( "MyResizeRandomCrop(size=%s%s, interpolation=%s, use_padding=%s, fill=%s)" % ( MyRandomResizedCrop.IMAGE_SIZE_LIST, "@continuous" if MyRandomResizedCrop.CONTINUOUS else "", _pil_interpolation_to_str[self.interpolation], self.use_padding, self.fill, ) ) class MyResize(object): def __init__(self, interpolation=Image.BILINEAR): self.interpolation = interpolation def __call__(self, img): target_size = MyRandomResizedCrop.ACTIVE_SIZE img = F.resize(img, target_size, self.interpolation) return img def __repr__(self): return "MyResize(size=%s%s, interpolation=%s)" % ( MyRandomResizedCrop.IMAGE_SIZE_LIST, "@continuous" if MyRandomResizedCrop.CONTINUOUS else "", _pil_interpolation_to_str[self.interpolation], )
import math import torch from torch.utils.data.distributed import DistributedSampler __all__ = ["MyDistributedSampler", "WeightedDistributedSampler"] class MyDistributedSampler(DistributedSampler): """Allow Subset Sampler in Distributed Training""" def __init__( self, dataset, num_replicas=None, rank=None, shuffle=True, sub_index_list=None ): super(MyDistributedSampler, self).__init__(dataset, num_replicas, rank, shuffle) self.sub_index_list = sub_index_list # numpy self.num_samples = int( math.ceil(len(self.sub_index_list) * 1.0 / self.num_replicas) ) self.total_size = self.num_samples * self.num_replicas print("Use MyDistributedSampler: %d, %d" % (self.num_samples, self.total_size)) def __iter__(self): # deterministically shuffle based on epoch g = torch.Generator() g.manual_seed(self.epoch) indices = torch.randperm(len(self.sub_index_list), generator=g).tolist() # add extra samples to make it evenly divisible indices += indices[: (self.total_size - len(indices))] indices = self.sub_index_list[indices].tolist() assert len(indices) == self.total_size # subsample indices = indices[self.rank : self.total_size : self.num_replicas] assert len(indices) == self.num_samples return iter(indices) class WeightedDistributedSampler(DistributedSampler): """Allow Weighted Random Sampling in Distributed Training""" def __init__( self, dataset, num_replicas=None, rank=None, shuffle=True, weights=None, replacement=True, ): super(WeightedDistributedSampler, self).__init__( dataset, num_replicas, rank, shuffle ) self.weights = ( torch.as_tensor(weights, dtype=torch.double) if weights is not None else None ) self.replacement = replacement print("Use WeightedDistributedSampler") def __iter__(self): if self.weights is None: return super(WeightedDistributedSampler, self).__iter__() else: g = torch.Generator() g.manual_seed(self.epoch) if self.shuffle: # original: indices = torch.randperm(len(self.dataset), generator=g).tolist() indices = torch.multinomial( self.weights, len(self.dataset), self.replacement, generator=g ).tolist() else: indices = list(range(len(self.dataset))) # add extra samples to make it evenly divisible indices += indices[: (self.total_size - len(indices))] assert len(indices) == self.total_size # subsample indices = indices[self.rank : self.total_size : self.num_replicas] assert len(indices) == self.num_samples return iter(indices)
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import copy import torch.nn.functional as F import torch.nn as nn import torch from ofa.utils import AverageMeter, get_net_device, DistributedTensor from ofa.imagenet_classification.elastic_nn.modules.dynamic_op import DynamicBatchNorm2d __all__ = ["set_running_statistics"] def set_running_statistics(model, data_loader, distributed=False): bn_mean = {} bn_var = {} forward_model = copy.deepcopy(model) for name, m in forward_model.named_modules(): if isinstance(m, nn.BatchNorm2d): if distributed: bn_mean[name] = DistributedTensor(name + "#mean") bn_var[name] = DistributedTensor(name + "#var") else: bn_mean[name] = AverageMeter() bn_var[name] = AverageMeter() def new_forward(bn, mean_est, var_est): def lambda_forward(x): batch_mean = ( x.mean(0, keepdim=True) .mean(2, keepdim=True) .mean(3, keepdim=True) ) # 1, C, 1, 1 batch_var = (x - batch_mean) * (x - batch_mean) batch_var = ( batch_var.mean(0, keepdim=True) .mean(2, keepdim=True) .mean(3, keepdim=True) ) batch_mean = torch.squeeze(batch_mean) batch_var = torch.squeeze(batch_var) mean_est.update(batch_mean.data, x.size(0)) var_est.update(batch_var.data, x.size(0)) # bn forward using calculated mean & var _feature_dim = batch_mean.size(0) return F.batch_norm( x, batch_mean, batch_var, bn.weight[:_feature_dim], bn.bias[:_feature_dim], False, 0.0, bn.eps, ) return lambda_forward m.forward = new_forward(m, bn_mean[name], bn_var[name]) if len(bn_mean) == 0: # skip if there is no batch normalization layers in the network return with torch.no_grad(): DynamicBatchNorm2d.SET_RUNNING_STATISTICS = True for images, labels in data_loader: images = images.to(get_net_device(forward_model)) forward_model(images) DynamicBatchNorm2d.SET_RUNNING_STATISTICS = False for name, m in model.named_modules(): if name in bn_mean and bn_mean[name].count > 0: feature_dim = bn_mean[name].avg.size(0) assert isinstance(m, nn.BatchNorm2d) m.running_mean.data[:feature_dim].copy_(bn_mean[name].avg) m.running_var.data[:feature_dim].copy_(bn_var[name].avg)
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. from .progressive_shrinking import *
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import torch.nn as nn import random import time import torch import torch.nn.functional as F from tqdm import tqdm from ofa.utils import AverageMeter, cross_entropy_loss_with_soft_target from ofa.utils import ( DistributedMetric, list_mean, subset_mean, val2list, MyRandomResizedCrop, ) from ofa.imagenet_classification.run_manager import DistributedRunManager __all__ = [ "validate", "train_one_epoch", "train", "load_models", "train_elastic_depth", "train_elastic_expand", "train_elastic_width_mult", ] def validate( run_manager, epoch=0, is_test=False, image_size_list=None, ks_list=None, expand_ratio_list=None, depth_list=None, width_mult_list=None, additional_setting=None, ): dynamic_net = run_manager.net if isinstance(dynamic_net, nn.DataParallel): dynamic_net = dynamic_net.module dynamic_net.eval() if image_size_list is None: image_size_list = val2list(run_manager.run_config.data_provider.image_size, 1) if ks_list is None: ks_list = dynamic_net.ks_list if expand_ratio_list is None: expand_ratio_list = dynamic_net.expand_ratio_list if depth_list is None: depth_list = dynamic_net.depth_list if width_mult_list is None: if "width_mult_list" in dynamic_net.__dict__: width_mult_list = list(range(len(dynamic_net.width_mult_list))) else: width_mult_list = [0] subnet_settings = [] for d in depth_list: for e in expand_ratio_list: for k in ks_list: for w in width_mult_list: for img_size in image_size_list: subnet_settings.append( [ { "image_size": img_size, "d": d, "e": e, "ks": k, "w": w, }, "R%s-D%s-E%s-K%s-W%s" % (img_size, d, e, k, w), ] ) if additional_setting is not None: subnet_settings += additional_setting losses_of_subnets, top1_of_subnets, top5_of_subnets = [], [], [] valid_log = "" for setting, name in subnet_settings: run_manager.write_log( "-" * 30 + " Validate %s " % name + "-" * 30, "train", should_print=False ) run_manager.run_config.data_provider.assign_active_img_size( setting.pop("image_size") ) dynamic_net.set_active_subnet(**setting) run_manager.write_log(dynamic_net.module_str, "train", should_print=False) run_manager.reset_running_statistics(dynamic_net) loss, (top1, top5) = run_manager.validate( epoch=epoch, is_test=is_test, run_str=name, net=dynamic_net ) losses_of_subnets.append(loss) top1_of_subnets.append(top1) top5_of_subnets.append(top5) valid_log += "%s (%.3f), " % (name, top1) return ( list_mean(losses_of_subnets), list_mean(top1_of_subnets), list_mean(top5_of_subnets), valid_log, ) def train_one_epoch(run_manager, args, epoch, warmup_epochs=0, warmup_lr=0): dynamic_net = run_manager.network distributed = isinstance(run_manager, DistributedRunManager) # switch to train mode dynamic_net.train() if distributed: run_manager.run_config.train_loader.sampler.set_epoch(epoch) MyRandomResizedCrop.EPOCH = epoch nBatch = len(run_manager.run_config.train_loader) data_time = AverageMeter() losses = DistributedMetric("train_loss") if distributed else AverageMeter() metric_dict = run_manager.get_metric_dict() with tqdm( total=nBatch, desc="Train Epoch #{}".format(epoch + 1), disable=distributed and not run_manager.is_root, ) as t: end = time.time() for i, (images, labels) in enumerate(run_manager.run_config.train_loader): MyRandomResizedCrop.BATCH = i data_time.update(time.time() - end) if epoch < warmup_epochs: new_lr = run_manager.run_config.warmup_adjust_learning_rate( run_manager.optimizer, warmup_epochs * nBatch, nBatch, epoch, i, warmup_lr, ) else: new_lr = run_manager.run_config.adjust_learning_rate( run_manager.optimizer, epoch - warmup_epochs, i, nBatch ) images, labels = images.cuda(), labels.cuda() target = labels # soft target if args.kd_ratio > 0: args.teacher_model.train() with torch.no_grad(): soft_logits = args.teacher_model(images).detach() soft_label = F.softmax(soft_logits, dim=1) # clean gradients dynamic_net.zero_grad() loss_of_subnets = [] # compute output subnet_str = "" for _ in range(args.dynamic_batch_size): # set random seed before sampling subnet_seed = int("%d%.3d%.3d" % (epoch * nBatch + i, _, 0)) random.seed(subnet_seed) subnet_settings = dynamic_net.sample_active_subnet() subnet_str += ( "%d: " % _ + ",".join( [ "%s_%s" % ( key, "%.1f" % subset_mean(val, 0) if isinstance(val, list) else val, ) for key, val in subnet_settings.items() ] ) + " || " ) output = run_manager.net(images) if args.kd_ratio == 0: loss = run_manager.train_criterion(output, labels) loss_type = "ce" else: if args.kd_type == "ce": kd_loss = cross_entropy_loss_with_soft_target( output, soft_label ) else: kd_loss = F.mse_loss(output, soft_logits) loss = args.kd_ratio * kd_loss + run_manager.train_criterion( output, labels ) loss_type = "%.1fkd-%s & ce" % (args.kd_ratio, args.kd_type) # measure accuracy and record loss loss_of_subnets.append(loss) run_manager.update_metric(metric_dict, output, target) loss.backward() run_manager.optimizer.step() losses.update(list_mean(loss_of_subnets), images.size(0)) t.set_postfix( { "loss": losses.avg.item(), **run_manager.get_metric_vals(metric_dict, return_dict=True), "R": images.size(2), "lr": new_lr, "loss_type": loss_type, "seed": str(subnet_seed), "str": subnet_str, "data_time": data_time.avg, } ) t.update(1) end = time.time() return losses.avg.item(), run_manager.get_metric_vals(metric_dict) def train(run_manager, args, validate_func=None): distributed = isinstance(run_manager, DistributedRunManager) if validate_func is None: validate_func = validate for epoch in range( run_manager.start_epoch, run_manager.run_config.n_epochs + args.warmup_epochs ): train_loss, (train_top1, train_top5) = train_one_epoch( run_manager, args, epoch, args.warmup_epochs, args.warmup_lr ) if (epoch + 1) % args.validation_frequency == 0: val_loss, val_acc, val_acc5, _val_log = validate_func( run_manager, epoch=epoch, is_test=False ) # best_acc is_best = val_acc > run_manager.best_acc run_manager.best_acc = max(run_manager.best_acc, val_acc) if not distributed or run_manager.is_root: val_log = ( "Valid [{0}/{1}] loss={2:.3f}, top-1={3:.3f} ({4:.3f})".format( epoch + 1 - args.warmup_epochs, run_manager.run_config.n_epochs, val_loss, val_acc, run_manager.best_acc, ) ) val_log += ", Train top-1 {top1:.3f}, Train loss {loss:.3f}\t".format( top1=train_top1, loss=train_loss ) val_log += _val_log run_manager.write_log(val_log, "valid", should_print=False) run_manager.save_model( { "epoch": epoch, "best_acc": run_manager.best_acc, "optimizer": run_manager.optimizer.state_dict(), "state_dict": run_manager.network.state_dict(), }, is_best=is_best, ) def load_models(run_manager, dynamic_net, model_path=None): # specify init path init = torch.load(model_path, map_location="cpu")["state_dict"] dynamic_net.load_state_dict(init) run_manager.write_log("Loaded init from %s" % model_path, "valid") def train_elastic_depth(train_func, run_manager, args, validate_func_dict): dynamic_net = run_manager.net if isinstance(dynamic_net, nn.DataParallel): dynamic_net = dynamic_net.module depth_stage_list = dynamic_net.depth_list.copy() depth_stage_list.sort(reverse=True) n_stages = len(depth_stage_list) - 1 current_stage = n_stages - 1 # load pretrained models if run_manager.start_epoch == 0 and not args.resume: validate_func_dict["depth_list"] = sorted(dynamic_net.depth_list) load_models(run_manager, dynamic_net, model_path=args.ofa_checkpoint_path) # validate after loading weights run_manager.write_log( "%.3f\t%.3f\t%.3f\t%s" % validate(run_manager, is_test=True, **validate_func_dict), "valid", ) else: assert args.resume run_manager.write_log( "-" * 30 + "Supporting Elastic Depth: %s -> %s" % (depth_stage_list[: current_stage + 1], depth_stage_list[: current_stage + 2]) + "-" * 30, "valid", ) # add depth list constraints if ( len(set(dynamic_net.ks_list)) == 1 and len(set(dynamic_net.expand_ratio_list)) == 1 ): validate_func_dict["depth_list"] = depth_stage_list else: validate_func_dict["depth_list"] = sorted( {min(depth_stage_list), max(depth_stage_list)} ) # train train_func( run_manager, args, lambda _run_manager, epoch, is_test: validate( _run_manager, epoch, is_test, **validate_func_dict ), ) def train_elastic_expand(train_func, run_manager, args, validate_func_dict): dynamic_net = run_manager.net if isinstance(dynamic_net, nn.DataParallel): dynamic_net = dynamic_net.module expand_stage_list = dynamic_net.expand_ratio_list.copy() expand_stage_list.sort(reverse=True) n_stages = len(expand_stage_list) - 1 current_stage = n_stages - 1 # load pretrained models if run_manager.start_epoch == 0 and not args.resume: validate_func_dict["expand_ratio_list"] = sorted(dynamic_net.expand_ratio_list) load_models(run_manager, dynamic_net, model_path=args.ofa_checkpoint_path) dynamic_net.re_organize_middle_weights(expand_ratio_stage=current_stage) run_manager.write_log( "%.3f\t%.3f\t%.3f\t%s" % validate(run_manager, is_test=True, **validate_func_dict), "valid", ) else: assert args.resume run_manager.write_log( "-" * 30 + "Supporting Elastic Expand Ratio: %s -> %s" % ( expand_stage_list[: current_stage + 1], expand_stage_list[: current_stage + 2], ) + "-" * 30, "valid", ) if len(set(dynamic_net.ks_list)) == 1 and len(set(dynamic_net.depth_list)) == 1: validate_func_dict["expand_ratio_list"] = expand_stage_list else: validate_func_dict["expand_ratio_list"] = sorted( {min(expand_stage_list), max(expand_stage_list)} ) # train train_func( run_manager, args, lambda _run_manager, epoch, is_test: validate( _run_manager, epoch, is_test, **validate_func_dict ), ) def train_elastic_width_mult(train_func, run_manager, args, validate_func_dict): dynamic_net = run_manager.net if isinstance(dynamic_net, nn.DataParallel): dynamic_net = dynamic_net.module width_stage_list = dynamic_net.width_mult_list.copy() width_stage_list.sort(reverse=True) n_stages = len(width_stage_list) - 1 current_stage = n_stages - 1 if run_manager.start_epoch == 0 and not args.resume: load_models(run_manager, dynamic_net, model_path=args.ofa_checkpoint_path) if current_stage == 0: dynamic_net.re_organize_middle_weights( expand_ratio_stage=len(dynamic_net.expand_ratio_list) - 1 ) run_manager.write_log( "reorganize_middle_weights (expand_ratio_stage=%d)" % (len(dynamic_net.expand_ratio_list) - 1), "valid", ) try: dynamic_net.re_organize_outer_weights() run_manager.write_log("reorganize_outer_weights", "valid") except Exception: pass run_manager.write_log( "%.3f\t%.3f\t%.3f\t%s" % validate(run_manager, is_test=True, **validate_func_dict), "valid", ) else: assert args.resume run_manager.write_log( "-" * 30 + "Supporting Elastic Width Mult: %s -> %s" % (width_stage_list[: current_stage + 1], width_stage_list[: current_stage + 2]) + "-" * 30, "valid", ) validate_func_dict["width_mult_list"] = sorted({0, len(width_stage_list) - 1}) # train train_func( run_manager, args, lambda _run_manager, epoch, is_test: validate( _run_manager, epoch, is_test, **validate_func_dict ), )
import random from ofa.imagenet_classification.elastic_nn.modules.dynamic_layers import ( DynamicConvLayer, DynamicLinearLayer, ) from ofa.imagenet_classification.elastic_nn.modules.dynamic_layers import ( DynamicResNetBottleneckBlock, ) from ofa.utils.layers import IdentityLayer, ResidualBlock from ofa.imagenet_classification.networks import ResNets from ofa.utils import make_divisible, val2list, MyNetwork __all__ = ["OFAResNets"] class OFAResNets(ResNets): def __init__( self, n_classes=1000, bn_param=(0.1, 1e-5), dropout_rate=0, depth_list=2, expand_ratio_list=0.25, width_mult_list=1.0, ): self.depth_list = val2list(depth_list) self.expand_ratio_list = val2list(expand_ratio_list) self.width_mult_list = val2list(width_mult_list) # sort self.depth_list.sort() self.expand_ratio_list.sort() self.width_mult_list.sort() input_channel = [ make_divisible(64 * width_mult, MyNetwork.CHANNEL_DIVISIBLE) for width_mult in self.width_mult_list ] mid_input_channel = [ make_divisible(channel // 2, MyNetwork.CHANNEL_DIVISIBLE) for channel in input_channel ] stage_width_list = ResNets.STAGE_WIDTH_LIST.copy() for i, width in enumerate(stage_width_list): stage_width_list[i] = [ make_divisible(width * width_mult, MyNetwork.CHANNEL_DIVISIBLE) for width_mult in self.width_mult_list ] n_block_list = [ base_depth + max(self.depth_list) for base_depth in ResNets.BASE_DEPTH_LIST ] stride_list = [1, 2, 2, 2] # build input stem input_stem = [ DynamicConvLayer( val2list(3), mid_input_channel, 3, stride=2, use_bn=True, act_func="relu", ), ResidualBlock( DynamicConvLayer( mid_input_channel, mid_input_channel, 3, stride=1, use_bn=True, act_func="relu", ), IdentityLayer(mid_input_channel, mid_input_channel), ), DynamicConvLayer( mid_input_channel, input_channel, 3, stride=1, use_bn=True, act_func="relu", ), ] # blocks blocks = [] for d, width, s in zip(n_block_list, stage_width_list, stride_list): for i in range(d): stride = s if i == 0 else 1 bottleneck_block = DynamicResNetBottleneckBlock( input_channel, width, expand_ratio_list=self.expand_ratio_list, kernel_size=3, stride=stride, act_func="relu", downsample_mode="avgpool_conv", ) blocks.append(bottleneck_block) input_channel = width # classifier classifier = DynamicLinearLayer( input_channel, n_classes, dropout_rate=dropout_rate ) super(OFAResNets, self).__init__(input_stem, blocks, classifier) # set bn param self.set_bn_param(*bn_param) # runtime_depth self.input_stem_skipping = 0 self.runtime_depth = [0] * len(n_block_list) @property def ks_list(self): return [3] @staticmethod def name(): return "OFAResNets" def forward(self, x): for layer in self.input_stem: if ( self.input_stem_skipping > 0 and isinstance(layer, ResidualBlock) and isinstance(layer.shortcut, IdentityLayer) ): pass else: x = layer(x) x = self.max_pooling(x) for stage_id, block_idx in enumerate(self.grouped_block_index): depth_param = self.runtime_depth[stage_id] active_idx = block_idx[: len(block_idx) - depth_param] for idx in active_idx: x = self.blocks[idx](x) x = self.global_avg_pool(x) x = self.classifier(x) return x @property def module_str(self): _str = "" for layer in self.input_stem: if ( self.input_stem_skipping > 0 and isinstance(layer, ResidualBlock) and isinstance(layer.shortcut, IdentityLayer) ): pass else: _str += layer.module_str + "\n" _str += "max_pooling(ks=3, stride=2)\n" for stage_id, block_idx in enumerate(self.grouped_block_index): depth_param = self.runtime_depth[stage_id] active_idx = block_idx[: len(block_idx) - depth_param] for idx in active_idx: _str += self.blocks[idx].module_str + "\n" _str += self.global_avg_pool.__repr__() + "\n" _str += self.classifier.module_str return _str @property def config(self): return { "name": OFAResNets.__name__, "bn": self.get_bn_param(), "input_stem": [layer.config for layer in self.input_stem], "blocks": [block.config for block in self.blocks], "classifier": self.classifier.config, } @staticmethod def build_from_config(config): raise ValueError("do not support this function") def load_state_dict(self, state_dict, **kwargs): model_dict = self.state_dict() for key in state_dict: new_key = key if new_key in model_dict: pass elif ".linear." in new_key: new_key = new_key.replace(".linear.", ".linear.linear.") elif "bn." in new_key: new_key = new_key.replace("bn.", "bn.bn.") elif "conv.weight" in new_key: new_key = new_key.replace("conv.weight", "conv.conv.weight") else: raise ValueError(new_key) assert new_key in model_dict, "%s" % new_key model_dict[new_key] = state_dict[key] super(OFAResNets, self).load_state_dict(model_dict) """ set, sample and get active sub-networks """ def set_max_net(self): self.set_active_subnet( d=max(self.depth_list), e=max(self.expand_ratio_list), w=len(self.width_mult_list) - 1, ) def set_active_subnet(self, d=None, e=None, w=None, **kwargs): depth = val2list(d, len(ResNets.BASE_DEPTH_LIST) + 1) expand_ratio = val2list(e, len(self.blocks)) width_mult = val2list(w, len(ResNets.BASE_DEPTH_LIST) + 2) for block, e in zip(self.blocks, expand_ratio): if e is not None: block.active_expand_ratio = e if width_mult[0] is not None: self.input_stem[1].conv.active_out_channel = self.input_stem[ 0 ].active_out_channel = self.input_stem[0].out_channel_list[width_mult[0]] if width_mult[1] is not None: self.input_stem[2].active_out_channel = self.input_stem[2].out_channel_list[ width_mult[1] ] if depth[0] is not None: self.input_stem_skipping = depth[0] != max(self.depth_list) for stage_id, (block_idx, d, w) in enumerate( zip(self.grouped_block_index, depth[1:], width_mult[2:]) ): if d is not None: self.runtime_depth[stage_id] = max(self.depth_list) - d if w is not None: for idx in block_idx: self.blocks[idx].active_out_channel = self.blocks[ idx ].out_channel_list[w] def sample_active_subnet(self): # sample expand ratio expand_setting = [] for block in self.blocks: expand_setting.append(random.choice(block.expand_ratio_list)) # sample depth depth_setting = [random.choice([max(self.depth_list), min(self.depth_list)])] for stage_id in range(len(ResNets.BASE_DEPTH_LIST)): depth_setting.append(random.choice(self.depth_list)) # sample width_mult width_mult_setting = [ random.choice(list(range(len(self.input_stem[0].out_channel_list)))), random.choice(list(range(len(self.input_stem[2].out_channel_list)))), ] for stage_id, block_idx in enumerate(self.grouped_block_index): stage_first_block = self.blocks[block_idx[0]] width_mult_setting.append( random.choice(list(range(len(stage_first_block.out_channel_list)))) ) arch_config = {"d": depth_setting, "e": expand_setting, "w": width_mult_setting} self.set_active_subnet(**arch_config) return arch_config def get_active_subnet(self, preserve_weight=True): input_stem = [self.input_stem[0].get_active_subnet(3, preserve_weight)] if self.input_stem_skipping <= 0: input_stem.append( ResidualBlock( self.input_stem[1].conv.get_active_subnet( self.input_stem[0].active_out_channel, preserve_weight ), IdentityLayer( self.input_stem[0].active_out_channel, self.input_stem[0].active_out_channel, ), ) ) input_stem.append( self.input_stem[2].get_active_subnet( self.input_stem[0].active_out_channel, preserve_weight ) ) input_channel = self.input_stem[2].active_out_channel blocks = [] for stage_id, block_idx in enumerate(self.grouped_block_index): depth_param = self.runtime_depth[stage_id] active_idx = block_idx[: len(block_idx) - depth_param] for idx in active_idx: blocks.append( self.blocks[idx].get_active_subnet(input_channel, preserve_weight) ) input_channel = self.blocks[idx].active_out_channel classifier = self.classifier.get_active_subnet(input_channel, preserve_weight) subnet = ResNets(input_stem, blocks, classifier) subnet.set_bn_param(**self.get_bn_param()) return subnet def get_active_net_config(self): input_stem_config = [self.input_stem[0].get_active_subnet_config(3)] if self.input_stem_skipping <= 0: input_stem_config.append( { "name": ResidualBlock.__name__, "conv": self.input_stem[1].conv.get_active_subnet_config( self.input_stem[0].active_out_channel ), "shortcut": IdentityLayer( self.input_stem[0].active_out_channel, self.input_stem[0].active_out_channel, ), } ) input_stem_config.append( self.input_stem[2].get_active_subnet_config( self.input_stem[0].active_out_channel ) ) input_channel = self.input_stem[2].active_out_channel blocks_config = [] for stage_id, block_idx in enumerate(self.grouped_block_index): depth_param = self.runtime_depth[stage_id] active_idx = block_idx[: len(block_idx) - depth_param] for idx in active_idx: blocks_config.append( self.blocks[idx].get_active_subnet_config(input_channel) ) input_channel = self.blocks[idx].active_out_channel classifier_config = self.classifier.get_active_subnet_config(input_channel) return { "name": ResNets.__name__, "bn": self.get_bn_param(), "input_stem": input_stem_config, "blocks": blocks_config, "classifier": classifier_config, } """ Width Related Methods """ def re_organize_middle_weights(self, expand_ratio_stage=0): for block in self.blocks: block.re_organize_middle_weights(expand_ratio_stage)
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import copy import random from ofa.utils import make_divisible, val2list, MyNetwork from ofa.imagenet_classification.elastic_nn.modules import DynamicMBConvLayer from ofa.utils.layers import ( ConvLayer, IdentityLayer, LinearLayer, MBConvLayer, ResidualBlock, ) from ofa.imagenet_classification.networks.proxyless_nets import ProxylessNASNets __all__ = ["OFAProxylessNASNets"] class OFAProxylessNASNets(ProxylessNASNets): def __init__( self, n_classes=1000, bn_param=(0.1, 1e-3), dropout_rate=0.1, base_stage_width=None, width_mult=1.0, ks_list=3, expand_ratio_list=6, depth_list=4, ): self.width_mult = width_mult self.ks_list = val2list(ks_list, 1) self.expand_ratio_list = val2list(expand_ratio_list, 1) self.depth_list = val2list(depth_list, 1) self.ks_list.sort() self.expand_ratio_list.sort() self.depth_list.sort() if base_stage_width == "google": # MobileNetV2 Stage Width base_stage_width = [32, 16, 24, 32, 64, 96, 160, 320, 1280] else: # ProxylessNAS Stage Width base_stage_width = [32, 16, 24, 40, 80, 96, 192, 320, 1280] input_channel = make_divisible( base_stage_width[0] * self.width_mult, MyNetwork.CHANNEL_DIVISIBLE ) first_block_width = make_divisible( base_stage_width[1] * self.width_mult, MyNetwork.CHANNEL_DIVISIBLE ) last_channel = make_divisible( base_stage_width[-1] * self.width_mult, MyNetwork.CHANNEL_DIVISIBLE ) # first conv layer first_conv = ConvLayer( 3, input_channel, kernel_size=3, stride=2, use_bn=True, act_func="relu6", ops_order="weight_bn_act", ) # first block first_block_conv = MBConvLayer( in_channels=input_channel, out_channels=first_block_width, kernel_size=3, stride=1, expand_ratio=1, act_func="relu6", ) first_block = ResidualBlock(first_block_conv, None) input_channel = first_block_width # inverted residual blocks self.block_group_info = [] blocks = [first_block] _block_index = 1 stride_stages = [2, 2, 2, 1, 2, 1] n_block_list = [max(self.depth_list)] * 5 + [1] width_list = [] for base_width in base_stage_width[2:-1]: width = make_divisible( base_width * self.width_mult, MyNetwork.CHANNEL_DIVISIBLE ) width_list.append(width) for width, n_block, s in zip(width_list, n_block_list, stride_stages): self.block_group_info.append([_block_index + i for i in range(n_block)]) _block_index += n_block output_channel = width for i in range(n_block): if i == 0: stride = s else: stride = 1 mobile_inverted_conv = DynamicMBConvLayer( in_channel_list=val2list(input_channel, 1), out_channel_list=val2list(output_channel, 1), kernel_size_list=ks_list, expand_ratio_list=expand_ratio_list, stride=stride, act_func="relu6", ) if stride == 1 and input_channel == output_channel: shortcut = IdentityLayer(input_channel, input_channel) else: shortcut = None mb_inverted_block = ResidualBlock(mobile_inverted_conv, shortcut) blocks.append(mb_inverted_block) input_channel = output_channel # 1x1_conv before global average pooling feature_mix_layer = ConvLayer( input_channel, last_channel, kernel_size=1, use_bn=True, act_func="relu6", ) classifier = LinearLayer(last_channel, n_classes, dropout_rate=dropout_rate) super(OFAProxylessNASNets, self).__init__( first_conv, blocks, feature_mix_layer, classifier ) # set bn param self.set_bn_param(momentum=bn_param[0], eps=bn_param[1]) # runtime_depth self.runtime_depth = [len(block_idx) for block_idx in self.block_group_info] """ MyNetwork required methods """ @staticmethod def name(): return "OFAProxylessNASNets" def forward(self, x): # first conv x = self.first_conv(x) # first block x = self.blocks[0](x) # blocks for stage_id, block_idx in enumerate(self.block_group_info): depth = self.runtime_depth[stage_id] active_idx = block_idx[:depth] for idx in active_idx: x = self.blocks[idx](x) # feature_mix_layer x = self.feature_mix_layer(x) x = x.mean(3).mean(2) x = self.classifier(x) return x @property def module_str(self): _str = self.first_conv.module_str + "\n" _str += self.blocks[0].module_str + "\n" for stage_id, block_idx in enumerate(self.block_group_info): depth = self.runtime_depth[stage_id] active_idx = block_idx[:depth] for idx in active_idx: _str += self.blocks[idx].module_str + "\n" _str += self.feature_mix_layer.module_str + "\n" _str += self.classifier.module_str + "\n" return _str @property def config(self): return { "name": OFAProxylessNASNets.__name__, "bn": self.get_bn_param(), "first_conv": self.first_conv.config, "blocks": [block.config for block in self.blocks], "feature_mix_layer": None if self.feature_mix_layer is None else self.feature_mix_layer.config, "classifier": self.classifier.config, } @staticmethod def build_from_config(config): raise ValueError("do not support this function") @property def grouped_block_index(self): return self.block_group_info def load_state_dict(self, state_dict, **kwargs): model_dict = self.state_dict() for key in state_dict: if ".mobile_inverted_conv." in key: new_key = key.replace(".mobile_inverted_conv.", ".conv.") else: new_key = key if new_key in model_dict: pass elif ".bn.bn." in new_key: new_key = new_key.replace(".bn.bn.", ".bn.") elif ".conv.conv.weight" in new_key: new_key = new_key.replace(".conv.conv.weight", ".conv.weight") elif ".linear.linear." in new_key: new_key = new_key.replace(".linear.linear.", ".linear.") ############################################################################## elif ".linear." in new_key: new_key = new_key.replace(".linear.", ".linear.linear.") elif "bn." in new_key: new_key = new_key.replace("bn.", "bn.bn.") elif "conv.weight" in new_key: new_key = new_key.replace("conv.weight", "conv.conv.weight") else: raise ValueError(new_key) assert new_key in model_dict, "%s" % new_key model_dict[new_key] = state_dict[key] super(OFAProxylessNASNets, self).load_state_dict(model_dict) """ set, sample and get active sub-networks """ def set_max_net(self): self.set_active_subnet( ks=max(self.ks_list), e=max(self.expand_ratio_list), d=max(self.depth_list) ) def set_active_subnet(self, ks=None, e=None, d=None, **kwargs): ks = val2list(ks, len(self.blocks) - 1) expand_ratio = val2list(e, len(self.blocks) - 1) depth = val2list(d, len(self.block_group_info)) for block, k, e in zip(self.blocks[1:], ks, expand_ratio): if k is not None: block.conv.active_kernel_size = k if e is not None: block.conv.active_expand_ratio = e for i, d in enumerate(depth): if d is not None: self.runtime_depth[i] = min(len(self.block_group_info[i]), d) def set_constraint(self, include_list, constraint_type="depth"): if constraint_type == "depth": self.__dict__["_depth_include_list"] = include_list.copy() elif constraint_type == "expand_ratio": self.__dict__["_expand_include_list"] = include_list.copy() elif constraint_type == "kernel_size": self.__dict__["_ks_include_list"] = include_list.copy() else: raise NotImplementedError def clear_constraint(self): self.__dict__["_depth_include_list"] = None self.__dict__["_expand_include_list"] = None self.__dict__["_ks_include_list"] = None def sample_active_subnet(self): ks_candidates = ( self.ks_list if self.__dict__.get("_ks_include_list", None) is None else self.__dict__["_ks_include_list"] ) expand_candidates = ( self.expand_ratio_list if self.__dict__.get("_expand_include_list", None) is None else self.__dict__["_expand_include_list"] ) depth_candidates = ( self.depth_list if self.__dict__.get("_depth_include_list", None) is None else self.__dict__["_depth_include_list"] ) # sample kernel size ks_setting = [] if not isinstance(ks_candidates[0], list): ks_candidates = [ks_candidates for _ in range(len(self.blocks) - 1)] for k_set in ks_candidates: k = random.choice(k_set) ks_setting.append(k) # sample expand ratio expand_setting = [] if not isinstance(expand_candidates[0], list): expand_candidates = [expand_candidates for _ in range(len(self.blocks) - 1)] for e_set in expand_candidates: e = random.choice(e_set) expand_setting.append(e) # sample depth depth_setting = [] if not isinstance(depth_candidates[0], list): depth_candidates = [ depth_candidates for _ in range(len(self.block_group_info)) ] for d_set in depth_candidates: d = random.choice(d_set) depth_setting.append(d) depth_setting[-1] = 1 self.set_active_subnet(ks_setting, expand_setting, depth_setting) return { "ks": ks_setting, "e": expand_setting, "d": depth_setting, } def get_active_subnet(self, preserve_weight=True): first_conv = copy.deepcopy(self.first_conv) blocks = [copy.deepcopy(self.blocks[0])] feature_mix_layer = copy.deepcopy(self.feature_mix_layer) classifier = copy.deepcopy(self.classifier) input_channel = blocks[0].conv.out_channels # blocks for stage_id, block_idx in enumerate(self.block_group_info): depth = self.runtime_depth[stage_id] active_idx = block_idx[:depth] stage_blocks = [] for idx in active_idx: stage_blocks.append( ResidualBlock( self.blocks[idx].conv.get_active_subnet( input_channel, preserve_weight ), copy.deepcopy(self.blocks[idx].shortcut), ) ) input_channel = stage_blocks[-1].conv.out_channels blocks += stage_blocks _subnet = ProxylessNASNets(first_conv, blocks, feature_mix_layer, classifier) _subnet.set_bn_param(**self.get_bn_param()) return _subnet def get_active_net_config(self): first_conv_config = self.first_conv.config first_block_config = self.blocks[0].config feature_mix_layer_config = self.feature_mix_layer.config classifier_config = self.classifier.config block_config_list = [first_block_config] input_channel = first_block_config["conv"]["out_channels"] for stage_id, block_idx in enumerate(self.block_group_info): depth = self.runtime_depth[stage_id] active_idx = block_idx[:depth] stage_blocks = [] for idx in active_idx: stage_blocks.append( { "name": ResidualBlock.__name__, "conv": self.blocks[idx].conv.get_active_subnet_config( input_channel ), "shortcut": self.blocks[idx].shortcut.config if self.blocks[idx].shortcut is not None else None, } ) try: input_channel = self.blocks[idx].conv.active_out_channel except Exception: input_channel = self.blocks[idx].conv.out_channels block_config_list += stage_blocks return { "name": ProxylessNASNets.__name__, "bn": self.get_bn_param(), "first_conv": first_conv_config, "blocks": block_config_list, "feature_mix_layer": feature_mix_layer_config, "classifier": classifier_config, } """ Width Related Methods """ def re_organize_middle_weights(self, expand_ratio_stage=0): for block in self.blocks[1:]: block.conv.re_organize_middle_weights(expand_ratio_stage)
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. from .ofa_proxyless import OFAProxylessNASNets from .ofa_mbv3 import OFAMobileNetV3 from .ofa_resnets import OFAResNets
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import copy import random from ofa.imagenet_classification.elastic_nn.modules.dynamic_layers import ( DynamicMBConvLayer, ) from ofa.utils.layers import ( ConvLayer, IdentityLayer, LinearLayer, MBConvLayer, ResidualBlock, ) from ofa.imagenet_classification.networks import MobileNetV3 from ofa.utils import make_divisible, val2list, MyNetwork __all__ = ["OFAMobileNetV3"] class OFAMobileNetV3(MobileNetV3): def __init__( self, n_classes=1000, bn_param=(0.1, 1e-5), dropout_rate=0.1, base_stage_width=None, width_mult=1.0, ks_list=3, expand_ratio_list=6, depth_list=4, ): self.width_mult = width_mult self.ks_list = val2list(ks_list, 1) self.expand_ratio_list = val2list(expand_ratio_list, 1) self.depth_list = val2list(depth_list, 1) self.ks_list.sort() self.expand_ratio_list.sort() self.depth_list.sort() base_stage_width = [16, 16, 24, 40, 80, 112, 160, 960, 1280] final_expand_width = make_divisible( base_stage_width[-2] * self.width_mult, MyNetwork.CHANNEL_DIVISIBLE ) last_channel = make_divisible( base_stage_width[-1] * self.width_mult, MyNetwork.CHANNEL_DIVISIBLE ) stride_stages = [1, 2, 2, 2, 1, 2] act_stages = ["relu", "relu", "relu", "h_swish", "h_swish", "h_swish"] se_stages = [False, False, True, False, True, True] n_block_list = [1] + [max(self.depth_list)] * 5 width_list = [] for base_width in base_stage_width[:-2]: width = make_divisible( base_width * self.width_mult, MyNetwork.CHANNEL_DIVISIBLE ) width_list.append(width) input_channel, first_block_dim = width_list[0], width_list[1] # first conv layer first_conv = ConvLayer( 3, input_channel, kernel_size=3, stride=2, act_func="h_swish" ) first_block_conv = MBConvLayer( in_channels=input_channel, out_channels=first_block_dim, kernel_size=3, stride=stride_stages[0], expand_ratio=1, act_func=act_stages[0], use_se=se_stages[0], ) first_block = ResidualBlock( first_block_conv, IdentityLayer(first_block_dim, first_block_dim) if input_channel == first_block_dim else None, ) # inverted residual blocks self.block_group_info = [] blocks = [first_block] _block_index = 1 feature_dim = first_block_dim for width, n_block, s, act_func, use_se in zip( width_list[2:], n_block_list[1:], stride_stages[1:], act_stages[1:], se_stages[1:], ): self.block_group_info.append([_block_index + i for i in range(n_block)]) _block_index += n_block output_channel = width for i in range(n_block): if i == 0: stride = s else: stride = 1 mobile_inverted_conv = DynamicMBConvLayer( in_channel_list=val2list(feature_dim), out_channel_list=val2list(output_channel), kernel_size_list=ks_list, expand_ratio_list=expand_ratio_list, stride=stride, act_func=act_func, use_se=use_se, ) if stride == 1 and feature_dim == output_channel: shortcut = IdentityLayer(feature_dim, feature_dim) else: shortcut = None blocks.append(ResidualBlock(mobile_inverted_conv, shortcut)) feature_dim = output_channel # final expand layer, feature mix layer & classifier final_expand_layer = ConvLayer( feature_dim, final_expand_width, kernel_size=1, act_func="h_swish" ) feature_mix_layer = ConvLayer( final_expand_width, last_channel, kernel_size=1, bias=False, use_bn=False, act_func="h_swish", ) classifier = LinearLayer(last_channel, n_classes, dropout_rate=dropout_rate) super(OFAMobileNetV3, self).__init__( first_conv, blocks, final_expand_layer, feature_mix_layer, classifier ) # set bn param self.set_bn_param(momentum=bn_param[0], eps=bn_param[1]) # runtime_depth self.runtime_depth = [len(block_idx) for block_idx in self.block_group_info] """ MyNetwork required methods """ @staticmethod def name(): return "OFAMobileNetV3" def forward(self, x): # first conv x = self.first_conv(x) # first block x = self.blocks[0](x) # blocks for stage_id, block_idx in enumerate(self.block_group_info): depth = self.runtime_depth[stage_id] active_idx = block_idx[:depth] for idx in active_idx: x = self.blocks[idx](x) x = self.final_expand_layer(x) x = x.mean(3, keepdim=True).mean(2, keepdim=True) # global average pooling x = self.feature_mix_layer(x) x = x.view(x.size(0), -1) x = self.classifier(x) return x @property def module_str(self): _str = self.first_conv.module_str + "\n" _str += self.blocks[0].module_str + "\n" for stage_id, block_idx in enumerate(self.block_group_info): depth = self.runtime_depth[stage_id] active_idx = block_idx[:depth] for idx in active_idx: _str += self.blocks[idx].module_str + "\n" _str += self.final_expand_layer.module_str + "\n" _str += self.feature_mix_layer.module_str + "\n" _str += self.classifier.module_str + "\n" return _str @property def config(self): return { "name": OFAMobileNetV3.__name__, "bn": self.get_bn_param(), "first_conv": self.first_conv.config, "blocks": [block.config for block in self.blocks], "final_expand_layer": self.final_expand_layer.config, "feature_mix_layer": self.feature_mix_layer.config, "classifier": self.classifier.config, } @staticmethod def build_from_config(config): raise ValueError("do not support this function") @property def grouped_block_index(self): return self.block_group_info def load_state_dict(self, state_dict, **kwargs): model_dict = self.state_dict() for key in state_dict: if ".mobile_inverted_conv." in key: new_key = key.replace(".mobile_inverted_conv.", ".conv.") else: new_key = key if new_key in model_dict: pass elif ".bn.bn." in new_key: new_key = new_key.replace(".bn.bn.", ".bn.") elif ".conv.conv.weight" in new_key: new_key = new_key.replace(".conv.conv.weight", ".conv.weight") elif ".linear.linear." in new_key: new_key = new_key.replace(".linear.linear.", ".linear.") ############################################################################## elif ".linear." in new_key: new_key = new_key.replace(".linear.", ".linear.linear.") elif "bn." in new_key: new_key = new_key.replace("bn.", "bn.bn.") elif "conv.weight" in new_key: new_key = new_key.replace("conv.weight", "conv.conv.weight") else: raise ValueError(new_key) assert new_key in model_dict, "%s" % new_key model_dict[new_key] = state_dict[key] super(OFAMobileNetV3, self).load_state_dict(model_dict) """ set, sample and get active sub-networks """ def set_max_net(self): self.set_active_subnet( ks=max(self.ks_list), e=max(self.expand_ratio_list), d=max(self.depth_list) ) def set_active_subnet(self, ks=None, e=None, d=None, **kwargs): ks = val2list(ks, len(self.blocks) - 1) expand_ratio = val2list(e, len(self.blocks) - 1) depth = val2list(d, len(self.block_group_info)) for block, k, e in zip(self.blocks[1:], ks, expand_ratio): if k is not None: block.conv.active_kernel_size = k if e is not None: block.conv.active_expand_ratio = e for i, d in enumerate(depth): if d is not None: self.runtime_depth[i] = min(len(self.block_group_info[i]), d) def set_constraint(self, include_list, constraint_type="depth"): if constraint_type == "depth": self.__dict__["_depth_include_list"] = include_list.copy() elif constraint_type == "expand_ratio": self.__dict__["_expand_include_list"] = include_list.copy() elif constraint_type == "kernel_size": self.__dict__["_ks_include_list"] = include_list.copy() else: raise NotImplementedError def clear_constraint(self): self.__dict__["_depth_include_list"] = None self.__dict__["_expand_include_list"] = None self.__dict__["_ks_include_list"] = None def sample_active_subnet(self): ks_candidates = ( self.ks_list if self.__dict__.get("_ks_include_list", None) is None else self.__dict__["_ks_include_list"] ) expand_candidates = ( self.expand_ratio_list if self.__dict__.get("_expand_include_list", None) is None else self.__dict__["_expand_include_list"] ) depth_candidates = ( self.depth_list if self.__dict__.get("_depth_include_list", None) is None else self.__dict__["_depth_include_list"] ) # sample kernel size ks_setting = [] if not isinstance(ks_candidates[0], list): ks_candidates = [ks_candidates for _ in range(len(self.blocks) - 1)] for k_set in ks_candidates: k = random.choice(k_set) ks_setting.append(k) # sample expand ratio expand_setting = [] if not isinstance(expand_candidates[0], list): expand_candidates = [expand_candidates for _ in range(len(self.blocks) - 1)] for e_set in expand_candidates: e = random.choice(e_set) expand_setting.append(e) # sample depth depth_setting = [] if not isinstance(depth_candidates[0], list): depth_candidates = [ depth_candidates for _ in range(len(self.block_group_info)) ] for d_set in depth_candidates: d = random.choice(d_set) depth_setting.append(d) self.set_active_subnet(ks_setting, expand_setting, depth_setting) return { "ks": ks_setting, "e": expand_setting, "d": depth_setting, } def get_active_subnet(self, preserve_weight=True): first_conv = copy.deepcopy(self.first_conv) blocks = [copy.deepcopy(self.blocks[0])] final_expand_layer = copy.deepcopy(self.final_expand_layer) feature_mix_layer = copy.deepcopy(self.feature_mix_layer) classifier = copy.deepcopy(self.classifier) input_channel = blocks[0].conv.out_channels # blocks for stage_id, block_idx in enumerate(self.block_group_info): depth = self.runtime_depth[stage_id] active_idx = block_idx[:depth] stage_blocks = [] for idx in active_idx: stage_blocks.append( ResidualBlock( self.blocks[idx].conv.get_active_subnet( input_channel, preserve_weight ), copy.deepcopy(self.blocks[idx].shortcut), ) ) input_channel = stage_blocks[-1].conv.out_channels blocks += stage_blocks _subnet = MobileNetV3( first_conv, blocks, final_expand_layer, feature_mix_layer, classifier ) _subnet.set_bn_param(**self.get_bn_param()) return _subnet def get_active_net_config(self): # first conv first_conv_config = self.first_conv.config first_block_config = self.blocks[0].config final_expand_config = self.final_expand_layer.config feature_mix_layer_config = self.feature_mix_layer.config classifier_config = self.classifier.config block_config_list = [first_block_config] input_channel = first_block_config["conv"]["out_channels"] for stage_id, block_idx in enumerate(self.block_group_info): depth = self.runtime_depth[stage_id] active_idx = block_idx[:depth] stage_blocks = [] for idx in active_idx: stage_blocks.append( { "name": ResidualBlock.__name__, "conv": self.blocks[idx].conv.get_active_subnet_config( input_channel ), "shortcut": self.blocks[idx].shortcut.config if self.blocks[idx].shortcut is not None else None, } ) input_channel = self.blocks[idx].conv.active_out_channel block_config_list += stage_blocks return { "name": MobileNetV3.__name__, "bn": self.get_bn_param(), "first_conv": first_conv_config, "blocks": block_config_list, "final_expand_layer": final_expand_config, "feature_mix_layer": feature_mix_layer_config, "classifier": classifier_config, } """ Width Related Methods """ def re_organize_middle_weights(self, expand_ratio_stage=0): for block in self.blocks[1:]: block.conv.re_organize_middle_weights(expand_ratio_stage)
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import copy import torch import torch.nn as nn from collections import OrderedDict from ofa.utils.layers import ( MBConvLayer, ConvLayer, IdentityLayer, set_layer_from_config, ) from ofa.utils.layers import ResNetBottleneckBlock, LinearLayer from ofa.utils import ( MyModule, val2list, get_net_device, build_activation, make_divisible, SEModule, MyNetwork, ) from .dynamic_op import ( DynamicSeparableConv2d, DynamicConv2d, DynamicBatchNorm2d, DynamicSE, DynamicGroupNorm, ) from .dynamic_op import DynamicLinear __all__ = [ "adjust_bn_according_to_idx", "copy_bn", "DynamicMBConvLayer", "DynamicConvLayer", "DynamicLinearLayer", "DynamicResNetBottleneckBlock", ] def adjust_bn_according_to_idx(bn, idx): bn.weight.data = torch.index_select(bn.weight.data, 0, idx) bn.bias.data = torch.index_select(bn.bias.data, 0, idx) if type(bn) in [nn.BatchNorm1d, nn.BatchNorm2d]: bn.running_mean.data = torch.index_select(bn.running_mean.data, 0, idx) bn.running_var.data = torch.index_select(bn.running_var.data, 0, idx) def copy_bn(target_bn, src_bn): feature_dim = ( target_bn.num_channels if isinstance(target_bn, nn.GroupNorm) else target_bn.num_features ) target_bn.weight.data.copy_(src_bn.weight.data[:feature_dim]) target_bn.bias.data.copy_(src_bn.bias.data[:feature_dim]) if type(src_bn) in [nn.BatchNorm1d, nn.BatchNorm2d]: target_bn.running_mean.data.copy_(src_bn.running_mean.data[:feature_dim]) target_bn.running_var.data.copy_(src_bn.running_var.data[:feature_dim]) class DynamicLinearLayer(MyModule): def __init__(self, in_features_list, out_features, bias=True, dropout_rate=0): super(DynamicLinearLayer, self).__init__() self.in_features_list = in_features_list self.out_features = out_features self.bias = bias self.dropout_rate = dropout_rate if self.dropout_rate > 0: self.dropout = nn.Dropout(self.dropout_rate, inplace=True) else: self.dropout = None self.linear = DynamicLinear( max_in_features=max(self.in_features_list), max_out_features=self.out_features, bias=self.bias, ) def forward(self, x): if self.dropout is not None: x = self.dropout(x) return self.linear(x) @property def module_str(self): return "DyLinear(%d, %d)" % (max(self.in_features_list), self.out_features) @property def config(self): return { "name": DynamicLinear.__name__, "in_features_list": self.in_features_list, "out_features": self.out_features, "bias": self.bias, "dropout_rate": self.dropout_rate, } @staticmethod def build_from_config(config): return DynamicLinearLayer(**config) def get_active_subnet(self, in_features, preserve_weight=True): sub_layer = LinearLayer( in_features, self.out_features, self.bias, dropout_rate=self.dropout_rate ) sub_layer = sub_layer.to(get_net_device(self)) if not preserve_weight: return sub_layer sub_layer.linear.weight.data.copy_( self.linear.get_active_weight(self.out_features, in_features).data ) if self.bias: sub_layer.linear.bias.data.copy_( self.linear.get_active_bias(self.out_features).data ) return sub_layer def get_active_subnet_config(self, in_features): return { "name": LinearLayer.__name__, "in_features": in_features, "out_features": self.out_features, "bias": self.bias, "dropout_rate": self.dropout_rate, } class DynamicMBConvLayer(MyModule): def __init__( self, in_channel_list, out_channel_list, kernel_size_list=3, expand_ratio_list=6, stride=1, act_func="relu6", use_se=False, ): super(DynamicMBConvLayer, self).__init__() self.in_channel_list = in_channel_list self.out_channel_list = out_channel_list self.kernel_size_list = val2list(kernel_size_list) self.expand_ratio_list = val2list(expand_ratio_list) self.stride = stride self.act_func = act_func self.use_se = use_se # build modules max_middle_channel = make_divisible( round(max(self.in_channel_list) * max(self.expand_ratio_list)), MyNetwork.CHANNEL_DIVISIBLE, ) if max(self.expand_ratio_list) == 1: self.inverted_bottleneck = None else: self.inverted_bottleneck = nn.Sequential( OrderedDict( [ ( "conv", DynamicConv2d( max(self.in_channel_list), max_middle_channel ), ), ("bn", DynamicBatchNorm2d(max_middle_channel)), ("act", build_activation(self.act_func)), ] ) ) self.depth_conv = nn.Sequential( OrderedDict( [ ( "conv", DynamicSeparableConv2d( max_middle_channel, self.kernel_size_list, self.stride ), ), ("bn", DynamicBatchNorm2d(max_middle_channel)), ("act", build_activation(self.act_func)), ] ) ) if self.use_se: self.depth_conv.add_module("se", DynamicSE(max_middle_channel)) self.point_linear = nn.Sequential( OrderedDict( [ ( "conv", DynamicConv2d(max_middle_channel, max(self.out_channel_list)), ), ("bn", DynamicBatchNorm2d(max(self.out_channel_list))), ] ) ) self.active_kernel_size = max(self.kernel_size_list) self.active_expand_ratio = max(self.expand_ratio_list) self.active_out_channel = max(self.out_channel_list) def forward(self, x): in_channel = x.size(1) if self.inverted_bottleneck is not None: self.inverted_bottleneck.conv.active_out_channel = make_divisible( round(in_channel * self.active_expand_ratio), MyNetwork.CHANNEL_DIVISIBLE, ) self.depth_conv.conv.active_kernel_size = self.active_kernel_size self.point_linear.conv.active_out_channel = self.active_out_channel if self.inverted_bottleneck is not None: x = self.inverted_bottleneck(x) x = self.depth_conv(x) x = self.point_linear(x) return x @property def module_str(self): if self.use_se: return "SE(O%d, E%.1f, K%d)" % ( self.active_out_channel, self.active_expand_ratio, self.active_kernel_size, ) else: return "(O%d, E%.1f, K%d)" % ( self.active_out_channel, self.active_expand_ratio, self.active_kernel_size, ) @property def config(self): return { "name": DynamicMBConvLayer.__name__, "in_channel_list": self.in_channel_list, "out_channel_list": self.out_channel_list, "kernel_size_list": self.kernel_size_list, "expand_ratio_list": self.expand_ratio_list, "stride": self.stride, "act_func": self.act_func, "use_se": self.use_se, } @staticmethod def build_from_config(config): return DynamicMBConvLayer(**config) ############################################################################################ @property def in_channels(self): return max(self.in_channel_list) @property def out_channels(self): return max(self.out_channel_list) def active_middle_channel(self, in_channel): return make_divisible( round(in_channel * self.active_expand_ratio), MyNetwork.CHANNEL_DIVISIBLE ) ############################################################################################ def get_active_subnet(self, in_channel, preserve_weight=True): # build the new layer sub_layer = set_layer_from_config(self.get_active_subnet_config(in_channel)) sub_layer = sub_layer.to(get_net_device(self)) if not preserve_weight: return sub_layer middle_channel = self.active_middle_channel(in_channel) # copy weight from current layer if sub_layer.inverted_bottleneck is not None: sub_layer.inverted_bottleneck.conv.weight.data.copy_( self.inverted_bottleneck.conv.get_active_filter( middle_channel, in_channel ).data, ) copy_bn(sub_layer.inverted_bottleneck.bn, self.inverted_bottleneck.bn.bn) sub_layer.depth_conv.conv.weight.data.copy_( self.depth_conv.conv.get_active_filter( middle_channel, self.active_kernel_size ).data ) copy_bn(sub_layer.depth_conv.bn, self.depth_conv.bn.bn) if self.use_se: se_mid = make_divisible( middle_channel // SEModule.REDUCTION, divisor=MyNetwork.CHANNEL_DIVISIBLE, ) sub_layer.depth_conv.se.fc.reduce.weight.data.copy_( self.depth_conv.se.get_active_reduce_weight(se_mid, middle_channel).data ) sub_layer.depth_conv.se.fc.reduce.bias.data.copy_( self.depth_conv.se.get_active_reduce_bias(se_mid).data ) sub_layer.depth_conv.se.fc.expand.weight.data.copy_( self.depth_conv.se.get_active_expand_weight(se_mid, middle_channel).data ) sub_layer.depth_conv.se.fc.expand.bias.data.copy_( self.depth_conv.se.get_active_expand_bias(middle_channel).data ) sub_layer.point_linear.conv.weight.data.copy_( self.point_linear.conv.get_active_filter( self.active_out_channel, middle_channel ).data ) copy_bn(sub_layer.point_linear.bn, self.point_linear.bn.bn) return sub_layer def get_active_subnet_config(self, in_channel): return { "name": MBConvLayer.__name__, "in_channels": in_channel, "out_channels": self.active_out_channel, "kernel_size": self.active_kernel_size, "stride": self.stride, "expand_ratio": self.active_expand_ratio, "mid_channels": self.active_middle_channel(in_channel), "act_func": self.act_func, "use_se": self.use_se, } def re_organize_middle_weights(self, expand_ratio_stage=0): importance = torch.sum( torch.abs(self.point_linear.conv.conv.weight.data), dim=(0, 2, 3) ) if isinstance(self.depth_conv.bn, DynamicGroupNorm): channel_per_group = self.depth_conv.bn.channel_per_group importance_chunks = torch.split(importance, channel_per_group) for chunk in importance_chunks: chunk.data.fill_(torch.mean(chunk)) importance = torch.cat(importance_chunks, dim=0) if expand_ratio_stage > 0: sorted_expand_list = copy.deepcopy(self.expand_ratio_list) sorted_expand_list.sort(reverse=True) target_width_list = [ make_divisible( round(max(self.in_channel_list) * expand), MyNetwork.CHANNEL_DIVISIBLE, ) for expand in sorted_expand_list ] right = len(importance) base = -len(target_width_list) * 1e5 for i in range(expand_ratio_stage + 1): left = target_width_list[i] importance[left:right] += base base += 1e5 right = left sorted_importance, sorted_idx = torch.sort(importance, dim=0, descending=True) self.point_linear.conv.conv.weight.data = torch.index_select( self.point_linear.conv.conv.weight.data, 1, sorted_idx ) adjust_bn_according_to_idx(self.depth_conv.bn.bn, sorted_idx) self.depth_conv.conv.conv.weight.data = torch.index_select( self.depth_conv.conv.conv.weight.data, 0, sorted_idx ) if self.use_se: # se expand: output dim 0 reorganize se_expand = self.depth_conv.se.fc.expand se_expand.weight.data = torch.index_select( se_expand.weight.data, 0, sorted_idx ) se_expand.bias.data = torch.index_select(se_expand.bias.data, 0, sorted_idx) # se reduce: input dim 1 reorganize se_reduce = self.depth_conv.se.fc.reduce se_reduce.weight.data = torch.index_select( se_reduce.weight.data, 1, sorted_idx ) # middle weight reorganize se_importance = torch.sum(torch.abs(se_expand.weight.data), dim=(0, 2, 3)) se_importance, se_idx = torch.sort(se_importance, dim=0, descending=True) se_expand.weight.data = torch.index_select(se_expand.weight.data, 1, se_idx) se_reduce.weight.data = torch.index_select(se_reduce.weight.data, 0, se_idx) se_reduce.bias.data = torch.index_select(se_reduce.bias.data, 0, se_idx) if self.inverted_bottleneck is not None: adjust_bn_according_to_idx(self.inverted_bottleneck.bn.bn, sorted_idx) self.inverted_bottleneck.conv.conv.weight.data = torch.index_select( self.inverted_bottleneck.conv.conv.weight.data, 0, sorted_idx ) return None else: return sorted_idx class DynamicConvLayer(MyModule): def __init__( self, in_channel_list, out_channel_list, kernel_size=3, stride=1, dilation=1, use_bn=True, act_func="relu6", ): super(DynamicConvLayer, self).__init__() self.in_channel_list = in_channel_list self.out_channel_list = out_channel_list self.kernel_size = kernel_size self.stride = stride self.dilation = dilation self.use_bn = use_bn self.act_func = act_func self.conv = DynamicConv2d( max_in_channels=max(self.in_channel_list), max_out_channels=max(self.out_channel_list), kernel_size=self.kernel_size, stride=self.stride, dilation=self.dilation, ) if self.use_bn: self.bn = DynamicBatchNorm2d(max(self.out_channel_list)) self.act = build_activation(self.act_func) self.active_out_channel = max(self.out_channel_list) def forward(self, x): self.conv.active_out_channel = self.active_out_channel x = self.conv(x) if self.use_bn: x = self.bn(x) x = self.act(x) return x @property def module_str(self): return "DyConv(O%d, K%d, S%d)" % ( self.active_out_channel, self.kernel_size, self.stride, ) @property def config(self): return { "name": DynamicConvLayer.__name__, "in_channel_list": self.in_channel_list, "out_channel_list": self.out_channel_list, "kernel_size": self.kernel_size, "stride": self.stride, "dilation": self.dilation, "use_bn": self.use_bn, "act_func": self.act_func, } @staticmethod def build_from_config(config): return DynamicConvLayer(**config) ############################################################################################ @property def in_channels(self): return max(self.in_channel_list) @property def out_channels(self): return max(self.out_channel_list) ############################################################################################ def get_active_subnet(self, in_channel, preserve_weight=True): sub_layer = set_layer_from_config(self.get_active_subnet_config(in_channel)) sub_layer = sub_layer.to(get_net_device(self)) if not preserve_weight: return sub_layer sub_layer.conv.weight.data.copy_( self.conv.get_active_filter(self.active_out_channel, in_channel).data ) if self.use_bn: copy_bn(sub_layer.bn, self.bn.bn) return sub_layer def get_active_subnet_config(self, in_channel): return { "name": ConvLayer.__name__, "in_channels": in_channel, "out_channels": self.active_out_channel, "kernel_size": self.kernel_size, "stride": self.stride, "dilation": self.dilation, "use_bn": self.use_bn, "act_func": self.act_func, } class DynamicResNetBottleneckBlock(MyModule): def __init__( self, in_channel_list, out_channel_list, expand_ratio_list=0.25, kernel_size=3, stride=1, act_func="relu", downsample_mode="avgpool_conv", ): super(DynamicResNetBottleneckBlock, self).__init__() self.in_channel_list = in_channel_list self.out_channel_list = out_channel_list self.expand_ratio_list = val2list(expand_ratio_list) self.kernel_size = kernel_size self.stride = stride self.act_func = act_func self.downsample_mode = downsample_mode # build modules max_middle_channel = make_divisible( round(max(self.out_channel_list) * max(self.expand_ratio_list)), MyNetwork.CHANNEL_DIVISIBLE, ) self.conv1 = nn.Sequential( OrderedDict( [ ( "conv", DynamicConv2d(max(self.in_channel_list), max_middle_channel), ), ("bn", DynamicBatchNorm2d(max_middle_channel)), ("act", build_activation(self.act_func, inplace=True)), ] ) ) self.conv2 = nn.Sequential( OrderedDict( [ ( "conv", DynamicConv2d( max_middle_channel, max_middle_channel, kernel_size, stride ), ), ("bn", DynamicBatchNorm2d(max_middle_channel)), ("act", build_activation(self.act_func, inplace=True)), ] ) ) self.conv3 = nn.Sequential( OrderedDict( [ ( "conv", DynamicConv2d(max_middle_channel, max(self.out_channel_list)), ), ("bn", DynamicBatchNorm2d(max(self.out_channel_list))), ] ) ) if self.stride == 1 and self.in_channel_list == self.out_channel_list: self.downsample = IdentityLayer( max(self.in_channel_list), max(self.out_channel_list) ) elif self.downsample_mode == "conv": self.downsample = nn.Sequential( OrderedDict( [ ( "conv", DynamicConv2d( max(self.in_channel_list), max(self.out_channel_list), stride=stride, ), ), ("bn", DynamicBatchNorm2d(max(self.out_channel_list))), ] ) ) elif self.downsample_mode == "avgpool_conv": self.downsample = nn.Sequential( OrderedDict( [ ( "avg_pool", nn.AvgPool2d( kernel_size=stride, stride=stride, padding=0, ceil_mode=True, ), ), ( "conv", DynamicConv2d( max(self.in_channel_list), max(self.out_channel_list) ), ), ("bn", DynamicBatchNorm2d(max(self.out_channel_list))), ] ) ) else: raise NotImplementedError self.final_act = build_activation(self.act_func, inplace=True) self.active_expand_ratio = max(self.expand_ratio_list) self.active_out_channel = max(self.out_channel_list) def forward(self, x): feature_dim = self.active_middle_channels self.conv1.conv.active_out_channel = feature_dim self.conv2.conv.active_out_channel = feature_dim self.conv3.conv.active_out_channel = self.active_out_channel if not isinstance(self.downsample, IdentityLayer): self.downsample.conv.active_out_channel = self.active_out_channel residual = self.downsample(x) x = self.conv1(x) x = self.conv2(x) x = self.conv3(x) x = x + residual x = self.final_act(x) return x @property def module_str(self): return "(%s, %s)" % ( "%dx%d_BottleneckConv_in->%d->%d_S%d" % ( self.kernel_size, self.kernel_size, self.active_middle_channels, self.active_out_channel, self.stride, ), "Identity" if isinstance(self.downsample, IdentityLayer) else self.downsample_mode, ) @property def config(self): return { "name": DynamicResNetBottleneckBlock.__name__, "in_channel_list": self.in_channel_list, "out_channel_list": self.out_channel_list, "expand_ratio_list": self.expand_ratio_list, "kernel_size": self.kernel_size, "stride": self.stride, "act_func": self.act_func, "downsample_mode": self.downsample_mode, } @staticmethod def build_from_config(config): return DynamicResNetBottleneckBlock(**config) ############################################################################################ @property def in_channels(self): return max(self.in_channel_list) @property def out_channels(self): return max(self.out_channel_list) @property def active_middle_channels(self): feature_dim = round(self.active_out_channel * self.active_expand_ratio) feature_dim = make_divisible(feature_dim, MyNetwork.CHANNEL_DIVISIBLE) return feature_dim ############################################################################################ def get_active_subnet(self, in_channel, preserve_weight=True): # build the new layer sub_layer = set_layer_from_config(self.get_active_subnet_config(in_channel)) sub_layer = sub_layer.to(get_net_device(self)) if not preserve_weight: return sub_layer # copy weight from current layer sub_layer.conv1.conv.weight.data.copy_( self.conv1.conv.get_active_filter( self.active_middle_channels, in_channel ).data ) copy_bn(sub_layer.conv1.bn, self.conv1.bn.bn) sub_layer.conv2.conv.weight.data.copy_( self.conv2.conv.get_active_filter( self.active_middle_channels, self.active_middle_channels ).data ) copy_bn(sub_layer.conv2.bn, self.conv2.bn.bn) sub_layer.conv3.conv.weight.data.copy_( self.conv3.conv.get_active_filter( self.active_out_channel, self.active_middle_channels ).data ) copy_bn(sub_layer.conv3.bn, self.conv3.bn.bn) if not isinstance(self.downsample, IdentityLayer): sub_layer.downsample.conv.weight.data.copy_( self.downsample.conv.get_active_filter( self.active_out_channel, in_channel ).data ) copy_bn(sub_layer.downsample.bn, self.downsample.bn.bn) return sub_layer def get_active_subnet_config(self, in_channel): return { "name": ResNetBottleneckBlock.__name__, "in_channels": in_channel, "out_channels": self.active_out_channel, "kernel_size": self.kernel_size, "stride": self.stride, "expand_ratio": self.active_expand_ratio, "mid_channels": self.active_middle_channels, "act_func": self.act_func, "groups": 1, "downsample_mode": self.downsample_mode, } def re_organize_middle_weights(self, expand_ratio_stage=0): # conv3 -> conv2 importance = torch.sum( torch.abs(self.conv3.conv.conv.weight.data), dim=(0, 2, 3) ) if isinstance(self.conv2.bn, DynamicGroupNorm): channel_per_group = self.conv2.bn.channel_per_group importance_chunks = torch.split(importance, channel_per_group) for chunk in importance_chunks: chunk.data.fill_(torch.mean(chunk)) importance = torch.cat(importance_chunks, dim=0) if expand_ratio_stage > 0: sorted_expand_list = copy.deepcopy(self.expand_ratio_list) sorted_expand_list.sort(reverse=True) target_width_list = [ make_divisible( round(max(self.out_channel_list) * expand), MyNetwork.CHANNEL_DIVISIBLE, ) for expand in sorted_expand_list ] right = len(importance) base = -len(target_width_list) * 1e5 for i in range(expand_ratio_stage + 1): left = target_width_list[i] importance[left:right] += base base += 1e5 right = left sorted_importance, sorted_idx = torch.sort(importance, dim=0, descending=True) self.conv3.conv.conv.weight.data = torch.index_select( self.conv3.conv.conv.weight.data, 1, sorted_idx ) adjust_bn_according_to_idx(self.conv2.bn.bn, sorted_idx) self.conv2.conv.conv.weight.data = torch.index_select( self.conv2.conv.conv.weight.data, 0, sorted_idx ) # conv2 -> conv1 importance = torch.sum( torch.abs(self.conv2.conv.conv.weight.data), dim=(0, 2, 3) ) if isinstance(self.conv1.bn, DynamicGroupNorm): channel_per_group = self.conv1.bn.channel_per_group importance_chunks = torch.split(importance, channel_per_group) for chunk in importance_chunks: chunk.data.fill_(torch.mean(chunk)) importance = torch.cat(importance_chunks, dim=0) if expand_ratio_stage > 0: sorted_expand_list = copy.deepcopy(self.expand_ratio_list) sorted_expand_list.sort(reverse=True) target_width_list = [ make_divisible( round(max(self.out_channel_list) * expand), MyNetwork.CHANNEL_DIVISIBLE, ) for expand in sorted_expand_list ] right = len(importance) base = -len(target_width_list) * 1e5 for i in range(expand_ratio_stage + 1): left = target_width_list[i] importance[left:right] += base base += 1e5 right = left sorted_importance, sorted_idx = torch.sort(importance, dim=0, descending=True) self.conv2.conv.conv.weight.data = torch.index_select( self.conv2.conv.conv.weight.data, 1, sorted_idx ) adjust_bn_according_to_idx(self.conv1.bn.bn, sorted_idx) self.conv1.conv.conv.weight.data = torch.index_select( self.conv1.conv.conv.weight.data, 0, sorted_idx ) return None
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. from .dynamic_layers import * from .dynamic_op import *
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import torch.nn.functional as F import torch.nn as nn import torch from torch.nn.parameter import Parameter from ofa.utils import ( get_same_padding, sub_filter_start_end, make_divisible, SEModule, MyNetwork, MyConv2d, ) __all__ = [ "DynamicSeparableConv2d", "DynamicConv2d", "DynamicGroupConv2d", "DynamicBatchNorm2d", "DynamicGroupNorm", "DynamicSE", "DynamicLinear", ] class DynamicSeparableConv2d(nn.Module): KERNEL_TRANSFORM_MODE = 1 # None or 1 def __init__(self, max_in_channels, kernel_size_list, stride=1, dilation=1): super(DynamicSeparableConv2d, self).__init__() self.max_in_channels = max_in_channels self.kernel_size_list = kernel_size_list self.stride = stride self.dilation = dilation self.conv = nn.Conv2d( self.max_in_channels, self.max_in_channels, max(self.kernel_size_list), self.stride, groups=self.max_in_channels, bias=False, ) self._ks_set = list(set(self.kernel_size_list)) self._ks_set.sort() # e.g., [3, 5, 7] if self.KERNEL_TRANSFORM_MODE is not None: # register scaling parameters # 7to5_matrix, 5to3_matrix scale_params = {} for i in range(len(self._ks_set) - 1): ks_small = self._ks_set[i] ks_larger = self._ks_set[i + 1] param_name = "%dto%d" % (ks_larger, ks_small) # noinspection PyArgumentList scale_params["%s_matrix" % param_name] = Parameter( torch.eye(ks_small ** 2) ) for name, param in scale_params.items(): self.register_parameter(name, param) self.active_kernel_size = max(self.kernel_size_list) def get_active_filter(self, in_channel, kernel_size): out_channel = in_channel max_kernel_size = max(self.kernel_size_list) start, end = sub_filter_start_end(max_kernel_size, kernel_size) filters = self.conv.weight[:out_channel, :in_channel, start:end, start:end] if self.KERNEL_TRANSFORM_MODE is not None and kernel_size < max_kernel_size: start_filter = self.conv.weight[ :out_channel, :in_channel, :, : ] # start with max kernel for i in range(len(self._ks_set) - 1, 0, -1): src_ks = self._ks_set[i] if src_ks <= kernel_size: break target_ks = self._ks_set[i - 1] start, end = sub_filter_start_end(src_ks, target_ks) _input_filter = start_filter[:, :, start:end, start:end] _input_filter = _input_filter.contiguous() _input_filter = _input_filter.view( _input_filter.size(0), _input_filter.size(1), -1 ) _input_filter = _input_filter.view(-1, _input_filter.size(2)) _input_filter = F.linear( _input_filter, self.__getattr__("%dto%d_matrix" % (src_ks, target_ks)), ) _input_filter = _input_filter.view( filters.size(0), filters.size(1), target_ks ** 2 ) _input_filter = _input_filter.view( filters.size(0), filters.size(1), target_ks, target_ks ) start_filter = _input_filter filters = start_filter return filters def forward(self, x, kernel_size=None): if kernel_size is None: kernel_size = self.active_kernel_size in_channel = x.size(1) filters = self.get_active_filter(in_channel, kernel_size).contiguous() padding = get_same_padding(kernel_size) filters = ( self.conv.weight_standardization(filters) if isinstance(self.conv, MyConv2d) else filters ) y = F.conv2d(x, filters, None, self.stride, padding, self.dilation, in_channel) return y class DynamicConv2d(nn.Module): def __init__( self, max_in_channels, max_out_channels, kernel_size=1, stride=1, dilation=1 ): super(DynamicConv2d, self).__init__() self.max_in_channels = max_in_channels self.max_out_channels = max_out_channels self.kernel_size = kernel_size self.stride = stride self.dilation = dilation self.conv = nn.Conv2d( self.max_in_channels, self.max_out_channels, self.kernel_size, stride=self.stride, bias=False, ) self.active_out_channel = self.max_out_channels def get_active_filter(self, out_channel, in_channel): return self.conv.weight[:out_channel, :in_channel, :, :] def forward(self, x, out_channel=None): if out_channel is None: out_channel = self.active_out_channel in_channel = x.size(1) filters = self.get_active_filter(out_channel, in_channel).contiguous() padding = get_same_padding(self.kernel_size) filters = ( self.conv.weight_standardization(filters) if isinstance(self.conv, MyConv2d) else filters ) y = F.conv2d(x, filters, None, self.stride, padding, self.dilation, 1) return y class DynamicGroupConv2d(nn.Module): def __init__( self, in_channels, out_channels, kernel_size_list, groups_list, stride=1, dilation=1, ): super(DynamicGroupConv2d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size_list = kernel_size_list self.groups_list = groups_list self.stride = stride self.dilation = dilation self.conv = nn.Conv2d( self.in_channels, self.out_channels, max(self.kernel_size_list), self.stride, groups=min(self.groups_list), bias=False, ) self.active_kernel_size = max(self.kernel_size_list) self.active_groups = min(self.groups_list) def get_active_filter(self, kernel_size, groups): start, end = sub_filter_start_end(max(self.kernel_size_list), kernel_size) filters = self.conv.weight[:, :, start:end, start:end] sub_filters = torch.chunk(filters, groups, dim=0) sub_in_channels = self.in_channels // groups sub_ratio = filters.size(1) // sub_in_channels filter_crops = [] for i, sub_filter in enumerate(sub_filters): part_id = i % sub_ratio start = part_id * sub_in_channels filter_crops.append(sub_filter[:, start : start + sub_in_channels, :, :]) filters = torch.cat(filter_crops, dim=0) return filters def forward(self, x, kernel_size=None, groups=None): if kernel_size is None: kernel_size = self.active_kernel_size if groups is None: groups = self.active_groups filters = self.get_active_filter(kernel_size, groups).contiguous() padding = get_same_padding(kernel_size) filters = ( self.conv.weight_standardization(filters) if isinstance(self.conv, MyConv2d) else filters ) y = F.conv2d( x, filters, None, self.stride, padding, self.dilation, groups, ) return y class DynamicBatchNorm2d(nn.Module): SET_RUNNING_STATISTICS = False def __init__(self, max_feature_dim): super(DynamicBatchNorm2d, self).__init__() self.max_feature_dim = max_feature_dim self.bn = nn.BatchNorm2d(self.max_feature_dim) @staticmethod def bn_forward(x, bn: nn.BatchNorm2d, feature_dim): if bn.num_features == feature_dim or DynamicBatchNorm2d.SET_RUNNING_STATISTICS: return bn(x) else: exponential_average_factor = 0.0 if bn.training and bn.track_running_stats: if bn.num_batches_tracked is not None: bn.num_batches_tracked += 1 if bn.momentum is None: # use cumulative moving average exponential_average_factor = 1.0 / float(bn.num_batches_tracked) else: # use exponential moving average exponential_average_factor = bn.momentum return F.batch_norm( x, bn.running_mean[:feature_dim], bn.running_var[:feature_dim], bn.weight[:feature_dim], bn.bias[:feature_dim], bn.training or not bn.track_running_stats, exponential_average_factor, bn.eps, ) def forward(self, x): feature_dim = x.size(1) y = self.bn_forward(x, self.bn, feature_dim) return y class DynamicGroupNorm(nn.GroupNorm): def __init__( self, num_groups, num_channels, eps=1e-5, affine=True, channel_per_group=None ): super(DynamicGroupNorm, self).__init__(num_groups, num_channels, eps, affine) self.channel_per_group = channel_per_group def forward(self, x): n_channels = x.size(1) n_groups = n_channels // self.channel_per_group return F.group_norm( x, n_groups, self.weight[:n_channels], self.bias[:n_channels], self.eps ) @property def bn(self): return self class DynamicSE(SEModule): def __init__(self, max_channel): super(DynamicSE, self).__init__(max_channel) def get_active_reduce_weight(self, num_mid, in_channel, groups=None): if groups is None or groups == 1: return self.fc.reduce.weight[:num_mid, :in_channel, :, :] else: assert in_channel % groups == 0 sub_in_channels = in_channel // groups sub_filters = torch.chunk( self.fc.reduce.weight[:num_mid, :, :, :], groups, dim=1 ) return torch.cat( [sub_filter[:, :sub_in_channels, :, :] for sub_filter in sub_filters], dim=1, ) def get_active_reduce_bias(self, num_mid): return ( self.fc.reduce.bias[:num_mid] if self.fc.reduce.bias is not None else None ) def get_active_expand_weight(self, num_mid, in_channel, groups=None): if groups is None or groups == 1: return self.fc.expand.weight[:in_channel, :num_mid, :, :] else: assert in_channel % groups == 0 sub_in_channels = in_channel // groups sub_filters = torch.chunk( self.fc.expand.weight[:, :num_mid, :, :], groups, dim=0 ) return torch.cat( [sub_filter[:sub_in_channels, :, :, :] for sub_filter in sub_filters], dim=0, ) def get_active_expand_bias(self, in_channel, groups=None): if groups is None or groups == 1: return ( self.fc.expand.bias[:in_channel] if self.fc.expand.bias is not None else None ) else: assert in_channel % groups == 0 sub_in_channels = in_channel // groups sub_bias_list = torch.chunk(self.fc.expand.bias, groups, dim=0) return torch.cat( [sub_bias[:sub_in_channels] for sub_bias in sub_bias_list], dim=0 ) def forward(self, x, groups=None): in_channel = x.size(1) num_mid = make_divisible( in_channel // self.reduction, divisor=MyNetwork.CHANNEL_DIVISIBLE ) y = x.mean(3, keepdim=True).mean(2, keepdim=True) # reduce reduce_filter = self.get_active_reduce_weight( num_mid, in_channel, groups=groups ).contiguous() reduce_bias = self.get_active_reduce_bias(num_mid) y = F.conv2d(y, reduce_filter, reduce_bias, 1, 0, 1, 1) # relu y = self.fc.relu(y) # expand expand_filter = self.get_active_expand_weight( num_mid, in_channel, groups=groups ).contiguous() expand_bias = self.get_active_expand_bias(in_channel, groups=groups) y = F.conv2d(y, expand_filter, expand_bias, 1, 0, 1, 1) # hard sigmoid y = self.fc.h_sigmoid(y) return x * y class DynamicLinear(nn.Module): def __init__(self, max_in_features, max_out_features, bias=True): super(DynamicLinear, self).__init__() self.max_in_features = max_in_features self.max_out_features = max_out_features self.bias = bias self.linear = nn.Linear(self.max_in_features, self.max_out_features, self.bias) self.active_out_features = self.max_out_features def get_active_weight(self, out_features, in_features): return self.linear.weight[:out_features, :in_features] def get_active_bias(self, out_features): return self.linear.bias[:out_features] if self.bias else None def forward(self, x, out_features=None): if out_features is None: out_features = self.active_out_features in_features = x.size(1) weight = self.get_active_weight(out_features, in_features).contiguous() bias = self.get_active_bias(out_features) y = F.linear(x, weight, bias) return y
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. from .run_config import * from .run_manager import * from .distributed_run_manager import *
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. from ofa.utils import calc_learning_rate, build_optimizer from ofa.imagenet_classification.data_providers import ImagenetDataProvider __all__ = ["RunConfig", "ImagenetRunConfig", "DistributedImageNetRunConfig"] class RunConfig: def __init__( self, n_epochs, init_lr, lr_schedule_type, lr_schedule_param, dataset, train_batch_size, test_batch_size, valid_size, opt_type, opt_param, weight_decay, label_smoothing, no_decay_keys, mixup_alpha, model_init, validation_frequency, print_frequency, ): self.n_epochs = n_epochs self.init_lr = init_lr self.lr_schedule_type = lr_schedule_type self.lr_schedule_param = lr_schedule_param self.dataset = dataset self.train_batch_size = train_batch_size self.test_batch_size = test_batch_size self.valid_size = valid_size self.opt_type = opt_type self.opt_param = opt_param self.weight_decay = weight_decay self.label_smoothing = label_smoothing self.no_decay_keys = no_decay_keys self.mixup_alpha = mixup_alpha self.model_init = model_init self.validation_frequency = validation_frequency self.print_frequency = print_frequency @property def config(self): config = {} for key in self.__dict__: if not key.startswith("_"): config[key] = self.__dict__[key] return config def copy(self): return RunConfig(**self.config) """ learning rate """ def adjust_learning_rate(self, optimizer, epoch, batch=0, nBatch=None): """adjust learning of a given optimizer and return the new learning rate""" new_lr = calc_learning_rate( epoch, self.init_lr, self.n_epochs, batch, nBatch, self.lr_schedule_type ) for param_group in optimizer.param_groups: param_group["lr"] = new_lr return new_lr def warmup_adjust_learning_rate( self, optimizer, T_total, nBatch, epoch, batch=0, warmup_lr=0 ): T_cur = epoch * nBatch + batch + 1 new_lr = T_cur / T_total * (self.init_lr - warmup_lr) + warmup_lr for param_group in optimizer.param_groups: param_group["lr"] = new_lr return new_lr """ data provider """ @property def data_provider(self): raise NotImplementedError @property def train_loader(self): return self.data_provider.train @property def valid_loader(self): return self.data_provider.valid @property def test_loader(self): return self.data_provider.test def random_sub_train_loader( self, n_images, batch_size, num_worker=None, num_replicas=None, rank=None ): return self.data_provider.build_sub_train_loader( n_images, batch_size, num_worker, num_replicas, rank ) """ optimizer """ def build_optimizer(self, net_params): return build_optimizer( net_params, self.opt_type, self.opt_param, self.init_lr, self.weight_decay, self.no_decay_keys, ) class ImagenetRunConfig(RunConfig): def __init__( self, n_epochs=150, init_lr=0.05, lr_schedule_type="cosine", lr_schedule_param=None, dataset="imagenet", train_batch_size=256, test_batch_size=500, valid_size=None, opt_type="sgd", opt_param=None, weight_decay=4e-5, label_smoothing=0.1, no_decay_keys=None, mixup_alpha=None, model_init="he_fout", validation_frequency=1, print_frequency=10, n_worker=32, resize_scale=0.08, distort_color="tf", image_size=224, **kwargs ): super(ImagenetRunConfig, self).__init__( n_epochs, init_lr, lr_schedule_type, lr_schedule_param, dataset, train_batch_size, test_batch_size, valid_size, opt_type, opt_param, weight_decay, label_smoothing, no_decay_keys, mixup_alpha, model_init, validation_frequency, print_frequency, ) self.n_worker = n_worker self.resize_scale = resize_scale self.distort_color = distort_color self.image_size = image_size @property def data_provider(self): if self.__dict__.get("_data_provider", None) is None: if self.dataset == ImagenetDataProvider.name(): DataProviderClass = ImagenetDataProvider else: raise NotImplementedError self.__dict__["_data_provider"] = DataProviderClass( train_batch_size=self.train_batch_size, test_batch_size=self.test_batch_size, valid_size=self.valid_size, n_worker=self.n_worker, resize_scale=self.resize_scale, distort_color=self.distort_color, image_size=self.image_size, ) return self.__dict__["_data_provider"] class DistributedImageNetRunConfig(ImagenetRunConfig): def __init__( self, n_epochs=150, init_lr=0.05, lr_schedule_type="cosine", lr_schedule_param=None, dataset="imagenet", train_batch_size=64, test_batch_size=64, valid_size=None, opt_type="sgd", opt_param=None, weight_decay=4e-5, label_smoothing=0.1, no_decay_keys=None, mixup_alpha=None, model_init="he_fout", validation_frequency=1, print_frequency=10, n_worker=8, resize_scale=0.08, distort_color="tf", image_size=224, **kwargs ): super(DistributedImageNetRunConfig, self).__init__( n_epochs, init_lr, lr_schedule_type, lr_schedule_param, dataset, train_batch_size, test_batch_size, valid_size, opt_type, opt_param, weight_decay, label_smoothing, no_decay_keys, mixup_alpha, model_init, validation_frequency, print_frequency, n_worker, resize_scale, distort_color, image_size, **kwargs ) self._num_replicas = kwargs["num_replicas"] self._rank = kwargs["rank"] @property def data_provider(self): if self.__dict__.get("_data_provider", None) is None: if self.dataset == ImagenetDataProvider.name(): DataProviderClass = ImagenetDataProvider else: raise NotImplementedError self.__dict__["_data_provider"] = DataProviderClass( train_batch_size=self.train_batch_size, test_batch_size=self.test_batch_size, valid_size=self.valid_size, n_worker=self.n_worker, resize_scale=self.resize_scale, distort_color=self.distort_color, image_size=self.image_size, num_replicas=self._num_replicas, rank=self._rank, ) return self.__dict__["_data_provider"]
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import os import json import time import random import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn from tqdm import tqdm from ofa.utils import ( cross_entropy_with_label_smoothing, cross_entropy_loss_with_soft_target, write_log, init_models, ) from ofa.utils import ( DistributedMetric, list_mean, get_net_info, accuracy, AverageMeter, mix_labels, mix_images, ) from ofa.utils import MyRandomResizedCrop __all__ = ["DistributedRunManager"] class DistributedRunManager: def __init__( self, path, net, run_config, hvd_compression, backward_steps=1, is_root=False, init=True, ): import horovod.torch as hvd self.path = path self.net = net self.run_config = run_config self.is_root = is_root self.best_acc = 0.0 self.start_epoch = 0 os.makedirs(self.path, exist_ok=True) self.net.cuda() cudnn.benchmark = True if init and self.is_root: init_models(self.net, self.run_config.model_init) if self.is_root: # print net info net_info = get_net_info(self.net, self.run_config.data_provider.data_shape) with open("%s/net_info.txt" % self.path, "w") as fout: fout.write(json.dumps(net_info, indent=4) + "\n") try: fout.write(self.net.module_str + "\n") except Exception: fout.write("%s do not support `module_str`" % type(self.net)) fout.write( "%s\n" % self.run_config.data_provider.train.dataset.transform ) fout.write( "%s\n" % self.run_config.data_provider.test.dataset.transform ) fout.write("%s\n" % self.net) # criterion if isinstance(self.run_config.mixup_alpha, float): self.train_criterion = cross_entropy_loss_with_soft_target elif self.run_config.label_smoothing > 0: self.train_criterion = ( lambda pred, target: cross_entropy_with_label_smoothing( pred, target, self.run_config.label_smoothing ) ) else: self.train_criterion = nn.CrossEntropyLoss() self.test_criterion = nn.CrossEntropyLoss() # optimizer if self.run_config.no_decay_keys: keys = self.run_config.no_decay_keys.split("#") net_params = [ self.net.get_parameters( keys, mode="exclude" ), # parameters with weight decay self.net.get_parameters( keys, mode="include" ), # parameters without weight decay ] else: # noinspection PyBroadException try: net_params = self.network.weight_parameters() except Exception: net_params = [] for param in self.network.parameters(): if param.requires_grad: net_params.append(param) self.optimizer = self.run_config.build_optimizer(net_params) self.optimizer = hvd.DistributedOptimizer( self.optimizer, named_parameters=self.net.named_parameters(), compression=hvd_compression, backward_passes_per_step=backward_steps, ) """ save path and log path """ @property def save_path(self): if self.__dict__.get("_save_path", None) is None: save_path = os.path.join(self.path, "checkpoint") os.makedirs(save_path, exist_ok=True) self.__dict__["_save_path"] = save_path return self.__dict__["_save_path"] @property def logs_path(self): if self.__dict__.get("_logs_path", None) is None: logs_path = os.path.join(self.path, "logs") os.makedirs(logs_path, exist_ok=True) self.__dict__["_logs_path"] = logs_path return self.__dict__["_logs_path"] @property def network(self): return self.net @network.setter def network(self, new_val): self.net = new_val def write_log(self, log_str, prefix="valid", should_print=True, mode="a"): if self.is_root: write_log(self.logs_path, log_str, prefix, should_print, mode) """ save & load model & save_config & broadcast """ def save_config(self, extra_run_config=None, extra_net_config=None): if self.is_root: run_save_path = os.path.join(self.path, "run.config") if not os.path.isfile(run_save_path): run_config = self.run_config.config if extra_run_config is not None: run_config.update(extra_run_config) json.dump(run_config, open(run_save_path, "w"), indent=4) print("Run configs dump to %s" % run_save_path) try: net_save_path = os.path.join(self.path, "net.config") net_config = self.net.config if extra_net_config is not None: net_config.update(extra_net_config) json.dump(net_config, open(net_save_path, "w"), indent=4) print("Network configs dump to %s" % net_save_path) except Exception: print("%s do not support net config" % type(self.net)) def save_model(self, checkpoint=None, is_best=False, model_name=None): if self.is_root: if checkpoint is None: checkpoint = {"state_dict": self.net.state_dict()} if model_name is None: model_name = "checkpoint.pth.tar" latest_fname = os.path.join(self.save_path, "latest.txt") model_path = os.path.join(self.save_path, model_name) with open(latest_fname, "w") as _fout: _fout.write(model_path + "\n") torch.save(checkpoint, model_path) if is_best: best_path = os.path.join(self.save_path, "model_best.pth.tar") torch.save({"state_dict": checkpoint["state_dict"]}, best_path) def load_model(self, model_fname=None): if self.is_root: latest_fname = os.path.join(self.save_path, "latest.txt") if model_fname is None and os.path.exists(latest_fname): with open(latest_fname, "r") as fin: model_fname = fin.readline() if model_fname[-1] == "\n": model_fname = model_fname[:-1] # noinspection PyBroadException try: if model_fname is None or not os.path.exists(model_fname): model_fname = "%s/checkpoint.pth.tar" % self.save_path with open(latest_fname, "w") as fout: fout.write(model_fname + "\n") print("=> loading checkpoint '{}'".format(model_fname)) checkpoint = torch.load(model_fname, map_location="cpu") except Exception: self.write_log( "fail to load checkpoint from %s" % self.save_path, "valid" ) return self.net.load_state_dict(checkpoint["state_dict"]) if "epoch" in checkpoint: self.start_epoch = checkpoint["epoch"] + 1 if "best_acc" in checkpoint: self.best_acc = checkpoint["best_acc"] if "optimizer" in checkpoint: self.optimizer.load_state_dict(checkpoint["optimizer"]) self.write_log("=> loaded checkpoint '{}'".format(model_fname), "valid") # noinspection PyArgumentList def broadcast(self): import horovod.torch as hvd self.start_epoch = hvd.broadcast( torch.LongTensor(1).fill_(self.start_epoch)[0], 0, name="start_epoch" ).item() self.best_acc = hvd.broadcast( torch.Tensor(1).fill_(self.best_acc)[0], 0, name="best_acc" ).item() hvd.broadcast_parameters(self.net.state_dict(), 0) hvd.broadcast_optimizer_state(self.optimizer, 0) """ metric related """ def get_metric_dict(self): return { "top1": DistributedMetric("top1"), "top5": DistributedMetric("top5"), } def update_metric(self, metric_dict, output, labels): acc1, acc5 = accuracy(output, labels, topk=(1, 5)) metric_dict["top1"].update(acc1[0], output.size(0)) metric_dict["top5"].update(acc5[0], output.size(0)) def get_metric_vals(self, metric_dict, return_dict=False): if return_dict: return {key: metric_dict[key].avg.item() for key in metric_dict} else: return [metric_dict[key].avg.item() for key in metric_dict] def get_metric_names(self): return "top1", "top5" """ train & validate """ def validate( self, epoch=0, is_test=False, run_str="", net=None, data_loader=None, no_logs=False, ): if net is None: net = self.net if data_loader is None: if is_test: data_loader = self.run_config.test_loader else: data_loader = self.run_config.valid_loader net.eval() losses = DistributedMetric("val_loss") metric_dict = self.get_metric_dict() with torch.no_grad(): with tqdm( total=len(data_loader), desc="Validate Epoch #{} {}".format(epoch + 1, run_str), disable=no_logs or not self.is_root, ) as t: for i, (images, labels) in enumerate(data_loader): images, labels = images.cuda(), labels.cuda() # compute output output = net(images) loss = self.test_criterion(output, labels) # measure accuracy and record loss losses.update(loss, images.size(0)) self.update_metric(metric_dict, output, labels) t.set_postfix( { "loss": losses.avg.item(), **self.get_metric_vals(metric_dict, return_dict=True), "img_size": images.size(2), } ) t.update(1) return losses.avg.item(), self.get_metric_vals(metric_dict) def validate_all_resolution(self, epoch=0, is_test=False, net=None): if net is None: net = self.net if isinstance(self.run_config.data_provider.image_size, list): img_size_list, loss_list, top1_list, top5_list = [], [], [], [] for img_size in self.run_config.data_provider.image_size: img_size_list.append(img_size) self.run_config.data_provider.assign_active_img_size(img_size) self.reset_running_statistics(net=net) loss, (top1, top5) = self.validate(epoch, is_test, net=net) loss_list.append(loss) top1_list.append(top1) top5_list.append(top5) return img_size_list, loss_list, top1_list, top5_list else: loss, (top1, top5) = self.validate(epoch, is_test, net=net) return ( [self.run_config.data_provider.active_img_size], [loss], [top1], [top5], ) def train_one_epoch(self, args, epoch, warmup_epochs=5, warmup_lr=0): self.net.train() self.run_config.train_loader.sampler.set_epoch( epoch ) # required by distributed sampler MyRandomResizedCrop.EPOCH = epoch # required by elastic resolution nBatch = len(self.run_config.train_loader) losses = DistributedMetric("train_loss") metric_dict = self.get_metric_dict() data_time = AverageMeter() with tqdm( total=nBatch, desc="Train Epoch #{}".format(epoch + 1), disable=not self.is_root, ) as t: end = time.time() for i, (images, labels) in enumerate(self.run_config.train_loader): MyRandomResizedCrop.BATCH = i data_time.update(time.time() - end) if epoch < warmup_epochs: new_lr = self.run_config.warmup_adjust_learning_rate( self.optimizer, warmup_epochs * nBatch, nBatch, epoch, i, warmup_lr, ) else: new_lr = self.run_config.adjust_learning_rate( self.optimizer, epoch - warmup_epochs, i, nBatch ) images, labels = images.cuda(), labels.cuda() target = labels if isinstance(self.run_config.mixup_alpha, float): # transform data random.seed(int("%d%.3d" % (i, epoch))) lam = random.betavariate( self.run_config.mixup_alpha, self.run_config.mixup_alpha ) images = mix_images(images, lam) labels = mix_labels( labels, lam, self.run_config.data_provider.n_classes, self.run_config.label_smoothing, ) # soft target if args.teacher_model is not None: args.teacher_model.train() with torch.no_grad(): soft_logits = args.teacher_model(images).detach() soft_label = F.softmax(soft_logits, dim=1) # compute output output = self.net(images) if args.teacher_model is None: loss = self.train_criterion(output, labels) loss_type = "ce" else: if args.kd_type == "ce": kd_loss = cross_entropy_loss_with_soft_target( output, soft_label ) else: kd_loss = F.mse_loss(output, soft_logits) loss = args.kd_ratio * kd_loss + self.train_criterion( output, labels ) loss_type = "%.1fkd+ce" % args.kd_ratio # update self.optimizer.zero_grad() loss.backward() self.optimizer.step() # measure accuracy and record loss losses.update(loss, images.size(0)) self.update_metric(metric_dict, output, target) t.set_postfix( { "loss": losses.avg.item(), **self.get_metric_vals(metric_dict, return_dict=True), "img_size": images.size(2), "lr": new_lr, "loss_type": loss_type, "data_time": data_time.avg, } ) t.update(1) end = time.time() return losses.avg.item(), self.get_metric_vals(metric_dict) def train(self, args, warmup_epochs=5, warmup_lr=0): for epoch in range(self.start_epoch, self.run_config.n_epochs + warmup_epochs): train_loss, (train_top1, train_top5) = self.train_one_epoch( args, epoch, warmup_epochs, warmup_lr ) img_size, val_loss, val_top1, val_top5 = self.validate_all_resolution( epoch, is_test=False ) is_best = list_mean(val_top1) > self.best_acc self.best_acc = max(self.best_acc, list_mean(val_top1)) if self.is_root: val_log = ( "[{0}/{1}]\tloss {2:.3f}\t{6} acc {3:.3f} ({4:.3f})\t{7} acc {5:.3f}\t" "Train {6} {top1:.3f}\tloss {train_loss:.3f}\t".format( epoch + 1 - warmup_epochs, self.run_config.n_epochs, list_mean(val_loss), list_mean(val_top1), self.best_acc, list_mean(val_top5), *self.get_metric_names(), top1=train_top1, train_loss=train_loss ) ) for i_s, v_a in zip(img_size, val_top1): val_log += "(%d, %.3f), " % (i_s, v_a) self.write_log(val_log, prefix="valid", should_print=False) self.save_model( { "epoch": epoch, "best_acc": self.best_acc, "optimizer": self.optimizer.state_dict(), "state_dict": self.net.state_dict(), }, is_best=is_best, ) def reset_running_statistics( self, net=None, subset_size=2000, subset_batch_size=200, data_loader=None ): from ofa.imagenet_classification.elastic_nn.utils import set_running_statistics if net is None: net = self.net if data_loader is None: data_loader = self.run_config.random_sub_train_loader( subset_size, subset_batch_size ) set_running_statistics(net, data_loader)
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import os import random import time import json import numpy as np import torch.nn as nn import torch.nn.functional as F import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim from tqdm import tqdm from ofa.utils import ( get_net_info, cross_entropy_loss_with_soft_target, cross_entropy_with_label_smoothing, ) from ofa.utils import ( AverageMeter, accuracy, write_log, mix_images, mix_labels, init_models, ) from ofa.utils import MyRandomResizedCrop __all__ = ["RunManager"] class RunManager: def __init__( self, path, net, run_config, init=True, measure_latency=None, no_gpu=False ): self.path = path self.net = net self.run_config = run_config self.best_acc = 0 self.start_epoch = 0 os.makedirs(self.path, exist_ok=True) # move network to GPU if available if torch.cuda.is_available() and (not no_gpu): self.device = torch.device("cuda:0") self.net = self.net.to(self.device) cudnn.benchmark = True else: self.device = torch.device("cpu") # initialize model (default) if init: init_models(run_config.model_init) # net info net_info = get_net_info( self.net, self.run_config.data_provider.data_shape, measure_latency, True ) with open("%s/net_info.txt" % self.path, "w") as fout: fout.write(json.dumps(net_info, indent=4) + "\n") # noinspection PyBroadException try: fout.write(self.network.module_str + "\n") except Exception: pass fout.write("%s\n" % self.run_config.data_provider.train.dataset.transform) fout.write("%s\n" % self.run_config.data_provider.test.dataset.transform) fout.write("%s\n" % self.network) # criterion if isinstance(self.run_config.mixup_alpha, float): self.train_criterion = cross_entropy_loss_with_soft_target elif self.run_config.label_smoothing > 0: self.train_criterion = ( lambda pred, target: cross_entropy_with_label_smoothing( pred, target, self.run_config.label_smoothing ) ) else: self.train_criterion = nn.CrossEntropyLoss() self.test_criterion = nn.CrossEntropyLoss() # optimizer if self.run_config.no_decay_keys: keys = self.run_config.no_decay_keys.split("#") net_params = [ self.network.get_parameters( keys, mode="exclude" ), # parameters with weight decay self.network.get_parameters( keys, mode="include" ), # parameters without weight decay ] else: # noinspection PyBroadException try: net_params = self.network.weight_parameters() except Exception: net_params = [] for param in self.network.parameters(): if param.requires_grad: net_params.append(param) self.optimizer = self.run_config.build_optimizer(net_params) self.net = torch.nn.DataParallel(self.net) """ save path and log path """ @property def save_path(self): if self.__dict__.get("_save_path", None) is None: save_path = os.path.join(self.path, "checkpoint") os.makedirs(save_path, exist_ok=True) self.__dict__["_save_path"] = save_path return self.__dict__["_save_path"] @property def logs_path(self): if self.__dict__.get("_logs_path", None) is None: logs_path = os.path.join(self.path, "logs") os.makedirs(logs_path, exist_ok=True) self.__dict__["_logs_path"] = logs_path return self.__dict__["_logs_path"] @property def network(self): return self.net.module if isinstance(self.net, nn.DataParallel) else self.net def write_log(self, log_str, prefix="valid", should_print=True, mode="a"): write_log(self.logs_path, log_str, prefix, should_print, mode) """ save and load models """ def save_model(self, checkpoint=None, is_best=False, model_name=None): if checkpoint is None: checkpoint = {"state_dict": self.network.state_dict()} if model_name is None: model_name = "checkpoint.pth.tar" checkpoint[ "dataset" ] = self.run_config.dataset # add `dataset` info to the checkpoint latest_fname = os.path.join(self.save_path, "latest.txt") model_path = os.path.join(self.save_path, model_name) with open(latest_fname, "w") as fout: fout.write(model_path + "\n") torch.save(checkpoint, model_path) if is_best: best_path = os.path.join(self.save_path, "model_best.pth.tar") torch.save({"state_dict": checkpoint["state_dict"]}, best_path) def load_model(self, model_fname=None): latest_fname = os.path.join(self.save_path, "latest.txt") if model_fname is None and os.path.exists(latest_fname): with open(latest_fname, "r") as fin: model_fname = fin.readline() if model_fname[-1] == "\n": model_fname = model_fname[:-1] # noinspection PyBroadException try: if model_fname is None or not os.path.exists(model_fname): model_fname = "%s/checkpoint.pth.tar" % self.save_path with open(latest_fname, "w") as fout: fout.write(model_fname + "\n") print("=> loading checkpoint '{}'".format(model_fname)) checkpoint = torch.load(model_fname, map_location="cpu") except Exception: print("fail to load checkpoint from %s" % self.save_path) return {} self.network.load_state_dict(checkpoint["state_dict"]) if "epoch" in checkpoint: self.start_epoch = checkpoint["epoch"] + 1 if "best_acc" in checkpoint: self.best_acc = checkpoint["best_acc"] if "optimizer" in checkpoint: self.optimizer.load_state_dict(checkpoint["optimizer"]) print("=> loaded checkpoint '{}'".format(model_fname)) return checkpoint def save_config(self, extra_run_config=None, extra_net_config=None): """dump run_config and net_config to the model_folder""" run_save_path = os.path.join(self.path, "run.config") if not os.path.isfile(run_save_path): run_config = self.run_config.config if extra_run_config is not None: run_config.update(extra_run_config) json.dump(run_config, open(run_save_path, "w"), indent=4) print("Run configs dump to %s" % run_save_path) try: net_save_path = os.path.join(self.path, "net.config") net_config = self.network.config if extra_net_config is not None: net_config.update(extra_net_config) json.dump(net_config, open(net_save_path, "w"), indent=4) print("Network configs dump to %s" % net_save_path) except Exception: print("%s do not support net config" % type(self.network)) """ metric related """ def get_metric_dict(self): return { "top1": AverageMeter(), "top5": AverageMeter(), } def update_metric(self, metric_dict, output, labels): acc1, acc5 = accuracy(output, labels, topk=(1, 5)) metric_dict["top1"].update(acc1[0].item(), output.size(0)) metric_dict["top5"].update(acc5[0].item(), output.size(0)) def get_metric_vals(self, metric_dict, return_dict=False): if return_dict: return {key: metric_dict[key].avg for key in metric_dict} else: return [metric_dict[key].avg for key in metric_dict] def get_metric_names(self): return "top1", "top5" """ train and test """ def validate( self, epoch=0, is_test=False, run_str="", net=None, data_loader=None, no_logs=False, train_mode=False, ): if net is None: net = self.net if not isinstance(net, nn.DataParallel): net = nn.DataParallel(net) if data_loader is None: data_loader = ( self.run_config.test_loader if is_test else self.run_config.valid_loader ) if train_mode: net.train() else: net.eval() losses = AverageMeter() metric_dict = self.get_metric_dict() with torch.no_grad(): with tqdm( total=len(data_loader), desc="Validate Epoch #{} {}".format(epoch + 1, run_str), disable=no_logs, ) as t: for i, (images, labels) in enumerate(data_loader): images, labels = images.to(self.device), labels.to(self.device) # compute output output = net(images) loss = self.test_criterion(output, labels) # measure accuracy and record loss self.update_metric(metric_dict, output, labels) losses.update(loss.item(), images.size(0)) t.set_postfix( { "loss": losses.avg, **self.get_metric_vals(metric_dict, return_dict=True), "img_size": images.size(2), } ) t.update(1) return losses.avg, self.get_metric_vals(metric_dict) def validate_all_resolution(self, epoch=0, is_test=False, net=None): if net is None: net = self.network if isinstance(self.run_config.data_provider.image_size, list): img_size_list, loss_list, top1_list, top5_list = [], [], [], [] for img_size in self.run_config.data_provider.image_size: img_size_list.append(img_size) self.run_config.data_provider.assign_active_img_size(img_size) self.reset_running_statistics(net=net) loss, (top1, top5) = self.validate(epoch, is_test, net=net) loss_list.append(loss) top1_list.append(top1) top5_list.append(top5) return img_size_list, loss_list, top1_list, top5_list else: loss, (top1, top5) = self.validate(epoch, is_test, net=net) return ( [self.run_config.data_provider.active_img_size], [loss], [top1], [top5], ) def train_one_epoch(self, args, epoch, warmup_epochs=0, warmup_lr=0): # switch to train mode self.net.train() MyRandomResizedCrop.EPOCH = epoch # required by elastic resolution nBatch = len(self.run_config.train_loader) losses = AverageMeter() metric_dict = self.get_metric_dict() data_time = AverageMeter() with tqdm( total=nBatch, desc="{} Train Epoch #{}".format(self.run_config.dataset, epoch + 1), ) as t: end = time.time() for i, (images, labels) in enumerate(self.run_config.train_loader): MyRandomResizedCrop.BATCH = i data_time.update(time.time() - end) if epoch < warmup_epochs: new_lr = self.run_config.warmup_adjust_learning_rate( self.optimizer, warmup_epochs * nBatch, nBatch, epoch, i, warmup_lr, ) else: new_lr = self.run_config.adjust_learning_rate( self.optimizer, epoch - warmup_epochs, i, nBatch ) images, labels = images.to(self.device), labels.to(self.device) target = labels if isinstance(self.run_config.mixup_alpha, float): # transform data lam = random.betavariate( self.run_config.mixup_alpha, self.run_config.mixup_alpha ) images = mix_images(images, lam) labels = mix_labels( labels, lam, self.run_config.data_provider.n_classes, self.run_config.label_smoothing, ) # soft target if args.teacher_model is not None: args.teacher_model.train() with torch.no_grad(): soft_logits = args.teacher_model(images).detach() soft_label = F.softmax(soft_logits, dim=1) # compute output output = self.net(images) loss = self.train_criterion(output, labels) if args.teacher_model is None: loss_type = "ce" else: if args.kd_type == "ce": kd_loss = cross_entropy_loss_with_soft_target( output, soft_label ) else: kd_loss = F.mse_loss(output, soft_logits) loss = args.kd_ratio * kd_loss + loss loss_type = "%.1fkd+ce" % args.kd_ratio # compute gradient and do SGD step self.net.zero_grad() # or self.optimizer.zero_grad() loss.backward() self.optimizer.step() # measure accuracy and record loss losses.update(loss.item(), images.size(0)) self.update_metric(metric_dict, output, target) t.set_postfix( { "loss": losses.avg, **self.get_metric_vals(metric_dict, return_dict=True), "img_size": images.size(2), "lr": new_lr, "loss_type": loss_type, "data_time": data_time.avg, } ) t.update(1) end = time.time() return losses.avg, self.get_metric_vals(metric_dict) def train(self, args, warmup_epoch=0, warmup_lr=0): for epoch in range(self.start_epoch, self.run_config.n_epochs + warmup_epoch): train_loss, (train_top1, train_top5) = self.train_one_epoch( args, epoch, warmup_epoch, warmup_lr ) if (epoch + 1) % self.run_config.validation_frequency == 0: img_size, val_loss, val_acc, val_acc5 = self.validate_all_resolution( epoch=epoch, is_test=False ) is_best = np.mean(val_acc) > self.best_acc self.best_acc = max(self.best_acc, np.mean(val_acc)) val_log = "Valid [{0}/{1}]\tloss {2:.3f}\t{5} {3:.3f} ({4:.3f})".format( epoch + 1 - warmup_epoch, self.run_config.n_epochs, np.mean(val_loss), np.mean(val_acc), self.best_acc, self.get_metric_names()[0], ) val_log += "\t{2} {0:.3f}\tTrain {1} {top1:.3f}\tloss {train_loss:.3f}\t".format( np.mean(val_acc5), *self.get_metric_names(), top1=train_top1, train_loss=train_loss ) for i_s, v_a in zip(img_size, val_acc): val_log += "(%d, %.3f), " % (i_s, v_a) self.write_log(val_log, prefix="valid", should_print=False) else: is_best = False self.save_model( { "epoch": epoch, "best_acc": self.best_acc, "optimizer": self.optimizer.state_dict(), "state_dict": self.network.state_dict(), }, is_best=is_best, ) def reset_running_statistics( self, net=None, subset_size=2000, subset_batch_size=200, data_loader=None ): from ofa.imagenet_classification.elastic_nn.utils import set_running_statistics if net is None: net = self.network if data_loader is None: data_loader = self.run_config.random_sub_train_loader( subset_size, subset_batch_size ) set_running_statistics(net, data_loader)
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. from .proxyless_nets import * from .mobilenet_v3 import * from .resnets import * def get_net_by_name(name): if name == ProxylessNASNets.__name__: return ProxylessNASNets elif name == MobileNetV3.__name__: return MobileNetV3 elif name == ResNets.__name__: return ResNets else: raise ValueError("unrecognized type of network: %s" % name)
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import copy import torch.nn as nn from ofa.utils.layers import ( set_layer_from_config, MBConvLayer, ConvLayer, IdentityLayer, LinearLayer, ResidualBlock, ) from ofa.utils import MyNetwork, make_divisible, MyGlobalAvgPool2d __all__ = ["MobileNetV3", "MobileNetV3Large"] class MobileNetV3(MyNetwork): def __init__( self, first_conv, blocks, final_expand_layer, feature_mix_layer, classifier ): super(MobileNetV3, self).__init__() self.first_conv = first_conv self.blocks = nn.ModuleList(blocks) self.final_expand_layer = final_expand_layer self.global_avg_pool = MyGlobalAvgPool2d(keep_dim=True) self.feature_mix_layer = feature_mix_layer self.classifier = classifier def forward(self, x): x = self.first_conv(x) for block in self.blocks: x = block(x) x = self.final_expand_layer(x) x = self.global_avg_pool(x) # global average pooling x = self.feature_mix_layer(x) x = x.view(x.size(0), -1) x = self.classifier(x) return x @property def module_str(self): _str = self.first_conv.module_str + "\n" for block in self.blocks: _str += block.module_str + "\n" _str += self.final_expand_layer.module_str + "\n" _str += self.global_avg_pool.__repr__() + "\n" _str += self.feature_mix_layer.module_str + "\n" _str += self.classifier.module_str return _str @property def config(self): return { "name": MobileNetV3.__name__, "bn": self.get_bn_param(), "first_conv": self.first_conv.config, "blocks": [block.config for block in self.blocks], "final_expand_layer": self.final_expand_layer.config, "feature_mix_layer": self.feature_mix_layer.config, "classifier": self.classifier.config, } @staticmethod def build_from_config(config): first_conv = set_layer_from_config(config["first_conv"]) final_expand_layer = set_layer_from_config(config["final_expand_layer"]) feature_mix_layer = set_layer_from_config(config["feature_mix_layer"]) classifier = set_layer_from_config(config["classifier"]) blocks = [] for block_config in config["blocks"]: blocks.append(ResidualBlock.build_from_config(block_config)) net = MobileNetV3( first_conv, blocks, final_expand_layer, feature_mix_layer, classifier ) if "bn" in config: net.set_bn_param(**config["bn"]) else: net.set_bn_param(momentum=0.1, eps=1e-5) return net def zero_last_gamma(self): for m in self.modules(): if isinstance(m, ResidualBlock): if isinstance(m.conv, MBConvLayer) and isinstance( m.shortcut, IdentityLayer ): m.conv.point_linear.bn.weight.data.zero_() @property def grouped_block_index(self): info_list = [] block_index_list = [] for i, block in enumerate(self.blocks[1:], 1): if block.shortcut is None and len(block_index_list) > 0: info_list.append(block_index_list) block_index_list = [] block_index_list.append(i) if len(block_index_list) > 0: info_list.append(block_index_list) return info_list @staticmethod def build_net_via_cfg(cfg, input_channel, last_channel, n_classes, dropout_rate): # first conv layer first_conv = ConvLayer( 3, input_channel, kernel_size=3, stride=2, use_bn=True, act_func="h_swish", ops_order="weight_bn_act", ) # build mobile blocks feature_dim = input_channel blocks = [] for stage_id, block_config_list in cfg.items(): for ( k, mid_channel, out_channel, use_se, act_func, stride, expand_ratio, ) in block_config_list: mb_conv = MBConvLayer( feature_dim, out_channel, k, stride, expand_ratio, mid_channel, act_func, use_se, ) if stride == 1 and out_channel == feature_dim: shortcut = IdentityLayer(out_channel, out_channel) else: shortcut = None blocks.append(ResidualBlock(mb_conv, shortcut)) feature_dim = out_channel # final expand layer final_expand_layer = ConvLayer( feature_dim, feature_dim * 6, kernel_size=1, use_bn=True, act_func="h_swish", ops_order="weight_bn_act", ) # feature mix layer feature_mix_layer = ConvLayer( feature_dim * 6, last_channel, kernel_size=1, bias=False, use_bn=False, act_func="h_swish", ) # classifier classifier = LinearLayer(last_channel, n_classes, dropout_rate=dropout_rate) return first_conv, blocks, final_expand_layer, feature_mix_layer, classifier @staticmethod def adjust_cfg( cfg, ks=None, expand_ratio=None, depth_param=None, stage_width_list=None ): for i, (stage_id, block_config_list) in enumerate(cfg.items()): for block_config in block_config_list: if ks is not None and stage_id != "0": block_config[0] = ks if expand_ratio is not None and stage_id != "0": block_config[-1] = expand_ratio block_config[1] = None if stage_width_list is not None: block_config[2] = stage_width_list[i] if depth_param is not None and stage_id != "0": new_block_config_list = [block_config_list[0]] new_block_config_list += [ copy.deepcopy(block_config_list[-1]) for _ in range(depth_param - 1) ] cfg[stage_id] = new_block_config_list return cfg def load_state_dict(self, state_dict, **kwargs): current_state_dict = self.state_dict() for key in state_dict: if key not in current_state_dict: assert ".mobile_inverted_conv." in key new_key = key.replace(".mobile_inverted_conv.", ".conv.") else: new_key = key current_state_dict[new_key] = state_dict[key] super(MobileNetV3, self).load_state_dict(current_state_dict) class MobileNetV3Large(MobileNetV3): def __init__( self, n_classes=1000, width_mult=1.0, bn_param=(0.1, 1e-5), dropout_rate=0.2, ks=None, expand_ratio=None, depth_param=None, stage_width_list=None, ): input_channel = 16 last_channel = 1280 input_channel = make_divisible( input_channel * width_mult, MyNetwork.CHANNEL_DIVISIBLE ) last_channel = ( make_divisible(last_channel * width_mult, MyNetwork.CHANNEL_DIVISIBLE) if width_mult > 1.0 else last_channel ) cfg = { # k, exp, c, se, nl, s, e, "0": [ [3, 16, 16, False, "relu", 1, 1], ], "1": [ [3, 64, 24, False, "relu", 2, None], # 4 [3, 72, 24, False, "relu", 1, None], # 3 ], "2": [ [5, 72, 40, True, "relu", 2, None], # 3 [5, 120, 40, True, "relu", 1, None], # 3 [5, 120, 40, True, "relu", 1, None], # 3 ], "3": [ [3, 240, 80, False, "h_swish", 2, None], # 6 [3, 200, 80, False, "h_swish", 1, None], # 2.5 [3, 184, 80, False, "h_swish", 1, None], # 2.3 [3, 184, 80, False, "h_swish", 1, None], # 2.3 ], "4": [ [3, 480, 112, True, "h_swish", 1, None], # 6 [3, 672, 112, True, "h_swish", 1, None], # 6 ], "5": [ [5, 672, 160, True, "h_swish", 2, None], # 6 [5, 960, 160, True, "h_swish", 1, None], # 6 [5, 960, 160, True, "h_swish", 1, None], # 6 ], } cfg = self.adjust_cfg(cfg, ks, expand_ratio, depth_param, stage_width_list) # width multiplier on mobile setting, change `exp: 1` and `c: 2` for stage_id, block_config_list in cfg.items(): for block_config in block_config_list: if block_config[1] is not None: block_config[1] = make_divisible( block_config[1] * width_mult, MyNetwork.CHANNEL_DIVISIBLE ) block_config[2] = make_divisible( block_config[2] * width_mult, MyNetwork.CHANNEL_DIVISIBLE ) ( first_conv, blocks, final_expand_layer, feature_mix_layer, classifier, ) = self.build_net_via_cfg( cfg, input_channel, last_channel, n_classes, dropout_rate ) super(MobileNetV3Large, self).__init__( first_conv, blocks, final_expand_layer, feature_mix_layer, classifier ) # set bn param self.set_bn_param(*bn_param)
import torch.nn as nn from ofa.utils.layers import ( set_layer_from_config, ConvLayer, IdentityLayer, LinearLayer, ) from ofa.utils.layers import ResNetBottleneckBlock, ResidualBlock from ofa.utils import make_divisible, MyNetwork, MyGlobalAvgPool2d __all__ = ["ResNets", "ResNet50", "ResNet50D"] class ResNets(MyNetwork): BASE_DEPTH_LIST = [2, 2, 4, 2] STAGE_WIDTH_LIST = [256, 512, 1024, 2048] def __init__(self, input_stem, blocks, classifier): super(ResNets, self).__init__() self.input_stem = nn.ModuleList(input_stem) self.max_pooling = nn.MaxPool2d( kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False ) self.blocks = nn.ModuleList(blocks) self.global_avg_pool = MyGlobalAvgPool2d(keep_dim=False) self.classifier = classifier def forward(self, x): for layer in self.input_stem: x = layer(x) x = self.max_pooling(x) for block in self.blocks: x = block(x) x = self.global_avg_pool(x) x = self.classifier(x) return x @property def module_str(self): _str = "" for layer in self.input_stem: _str += layer.module_str + "\n" _str += "max_pooling(ks=3, stride=2)\n" for block in self.blocks: _str += block.module_str + "\n" _str += self.global_avg_pool.__repr__() + "\n" _str += self.classifier.module_str return _str @property def config(self): return { "name": ResNets.__name__, "bn": self.get_bn_param(), "input_stem": [layer.config for layer in self.input_stem], "blocks": [block.config for block in self.blocks], "classifier": self.classifier.config, } @staticmethod def build_from_config(config): classifier = set_layer_from_config(config["classifier"]) input_stem = [] for layer_config in config["input_stem"]: input_stem.append(set_layer_from_config(layer_config)) blocks = [] for block_config in config["blocks"]: blocks.append(set_layer_from_config(block_config)) net = ResNets(input_stem, blocks, classifier) if "bn" in config: net.set_bn_param(**config["bn"]) else: net.set_bn_param(momentum=0.1, eps=1e-5) return net def zero_last_gamma(self): for m in self.modules(): if isinstance(m, ResNetBottleneckBlock) and isinstance( m.downsample, IdentityLayer ): m.conv3.bn.weight.data.zero_() @property def grouped_block_index(self): info_list = [] block_index_list = [] for i, block in enumerate(self.blocks): if ( not isinstance(block.downsample, IdentityLayer) and len(block_index_list) > 0 ): info_list.append(block_index_list) block_index_list = [] block_index_list.append(i) if len(block_index_list) > 0: info_list.append(block_index_list) return info_list def load_state_dict(self, state_dict, **kwargs): super(ResNets, self).load_state_dict(state_dict) class ResNet50(ResNets): def __init__( self, n_classes=1000, width_mult=1.0, bn_param=(0.1, 1e-5), dropout_rate=0, expand_ratio=None, depth_param=None, ): expand_ratio = 0.25 if expand_ratio is None else expand_ratio input_channel = make_divisible(64 * width_mult, MyNetwork.CHANNEL_DIVISIBLE) stage_width_list = ResNets.STAGE_WIDTH_LIST.copy() for i, width in enumerate(stage_width_list): stage_width_list[i] = make_divisible( width * width_mult, MyNetwork.CHANNEL_DIVISIBLE ) depth_list = [3, 4, 6, 3] if depth_param is not None: for i, depth in enumerate(ResNets.BASE_DEPTH_LIST): depth_list[i] = depth + depth_param stride_list = [1, 2, 2, 2] # build input stem input_stem = [ ConvLayer( 3, input_channel, kernel_size=7, stride=2, use_bn=True, act_func="relu", ops_order="weight_bn_act", ) ] # blocks blocks = [] for d, width, s in zip(depth_list, stage_width_list, stride_list): for i in range(d): stride = s if i == 0 else 1 bottleneck_block = ResNetBottleneckBlock( input_channel, width, kernel_size=3, stride=stride, expand_ratio=expand_ratio, act_func="relu", downsample_mode="conv", ) blocks.append(bottleneck_block) input_channel = width # classifier classifier = LinearLayer(input_channel, n_classes, dropout_rate=dropout_rate) super(ResNet50, self).__init__(input_stem, blocks, classifier) # set bn param self.set_bn_param(*bn_param) class ResNet50D(ResNets): def __init__( self, n_classes=1000, width_mult=1.0, bn_param=(0.1, 1e-5), dropout_rate=0, expand_ratio=None, depth_param=None, ): expand_ratio = 0.25 if expand_ratio is None else expand_ratio input_channel = make_divisible(64 * width_mult, MyNetwork.CHANNEL_DIVISIBLE) mid_input_channel = make_divisible( input_channel // 2, MyNetwork.CHANNEL_DIVISIBLE ) stage_width_list = ResNets.STAGE_WIDTH_LIST.copy() for i, width in enumerate(stage_width_list): stage_width_list[i] = make_divisible( width * width_mult, MyNetwork.CHANNEL_DIVISIBLE ) depth_list = [3, 4, 6, 3] if depth_param is not None: for i, depth in enumerate(ResNets.BASE_DEPTH_LIST): depth_list[i] = depth + depth_param stride_list = [1, 2, 2, 2] # build input stem input_stem = [ ConvLayer(3, mid_input_channel, 3, stride=2, use_bn=True, act_func="relu"), ResidualBlock( ConvLayer( mid_input_channel, mid_input_channel, 3, stride=1, use_bn=True, act_func="relu", ), IdentityLayer(mid_input_channel, mid_input_channel), ), ConvLayer( mid_input_channel, input_channel, 3, stride=1, use_bn=True, act_func="relu", ), ] # blocks blocks = [] for d, width, s in zip(depth_list, stage_width_list, stride_list): for i in range(d): stride = s if i == 0 else 1 bottleneck_block = ResNetBottleneckBlock( input_channel, width, kernel_size=3, stride=stride, expand_ratio=expand_ratio, act_func="relu", downsample_mode="avgpool_conv", ) blocks.append(bottleneck_block) input_channel = width # classifier classifier = LinearLayer(input_channel, n_classes, dropout_rate=dropout_rate) super(ResNet50D, self).__init__(input_stem, blocks, classifier) # set bn param self.set_bn_param(*bn_param)
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import json import torch.nn as nn from ofa.utils.layers import ( set_layer_from_config, MBConvLayer, ConvLayer, IdentityLayer, LinearLayer, ResidualBlock, ) from ofa.utils import ( download_url, make_divisible, val2list, MyNetwork, MyGlobalAvgPool2d, ) __all__ = ["proxyless_base", "ProxylessNASNets", "MobileNetV2"] def proxyless_base( net_config=None, n_classes=None, bn_param=None, dropout_rate=None, local_path="~/.torch/proxylessnas/", ): assert net_config is not None, "Please input a network config" if "http" in net_config: net_config_path = download_url(net_config, local_path) else: net_config_path = net_config net_config_json = json.load(open(net_config_path, "r")) if n_classes is not None: net_config_json["classifier"]["out_features"] = n_classes if dropout_rate is not None: net_config_json["classifier"]["dropout_rate"] = dropout_rate net = ProxylessNASNets.build_from_config(net_config_json) if bn_param is not None: net.set_bn_param(*bn_param) return net class ProxylessNASNets(MyNetwork): def __init__(self, first_conv, blocks, feature_mix_layer, classifier): super(ProxylessNASNets, self).__init__() self.first_conv = first_conv self.blocks = nn.ModuleList(blocks) self.feature_mix_layer = feature_mix_layer self.global_avg_pool = MyGlobalAvgPool2d(keep_dim=False) self.classifier = classifier def forward(self, x): x = self.first_conv(x) for block in self.blocks: x = block(x) if self.feature_mix_layer is not None: x = self.feature_mix_layer(x) x = self.global_avg_pool(x) x = self.classifier(x) return x @property def module_str(self): _str = self.first_conv.module_str + "\n" for block in self.blocks: _str += block.module_str + "\n" _str += self.feature_mix_layer.module_str + "\n" _str += self.global_avg_pool.__repr__() + "\n" _str += self.classifier.module_str return _str @property def config(self): return { "name": ProxylessNASNets.__name__, "bn": self.get_bn_param(), "first_conv": self.first_conv.config, "blocks": [block.config for block in self.blocks], "feature_mix_layer": None if self.feature_mix_layer is None else self.feature_mix_layer.config, "classifier": self.classifier.config, } @staticmethod def build_from_config(config): first_conv = set_layer_from_config(config["first_conv"]) feature_mix_layer = set_layer_from_config(config["feature_mix_layer"]) classifier = set_layer_from_config(config["classifier"]) blocks = [] for block_config in config["blocks"]: blocks.append(ResidualBlock.build_from_config(block_config)) net = ProxylessNASNets(first_conv, blocks, feature_mix_layer, classifier) if "bn" in config: net.set_bn_param(**config["bn"]) else: net.set_bn_param(momentum=0.1, eps=1e-3) return net def zero_last_gamma(self): for m in self.modules(): if isinstance(m, ResidualBlock): if isinstance(m.conv, MBConvLayer) and isinstance( m.shortcut, IdentityLayer ): m.conv.point_linear.bn.weight.data.zero_() @property def grouped_block_index(self): info_list = [] block_index_list = [] for i, block in enumerate(self.blocks[1:], 1): if block.shortcut is None and len(block_index_list) > 0: info_list.append(block_index_list) block_index_list = [] block_index_list.append(i) if len(block_index_list) > 0: info_list.append(block_index_list) return info_list def load_state_dict(self, state_dict, **kwargs): current_state_dict = self.state_dict() for key in state_dict: if key not in current_state_dict: assert ".mobile_inverted_conv." in key new_key = key.replace(".mobile_inverted_conv.", ".conv.") else: new_key = key current_state_dict[new_key] = state_dict[key] super(ProxylessNASNets, self).load_state_dict(current_state_dict) class MobileNetV2(ProxylessNASNets): def __init__( self, n_classes=1000, width_mult=1.0, bn_param=(0.1, 1e-3), dropout_rate=0.2, ks=None, expand_ratio=None, depth_param=None, stage_width_list=None, ): ks = 3 if ks is None else ks expand_ratio = 6 if expand_ratio is None else expand_ratio input_channel = 32 last_channel = 1280 input_channel = make_divisible( input_channel * width_mult, MyNetwork.CHANNEL_DIVISIBLE ) last_channel = ( make_divisible(last_channel * width_mult, MyNetwork.CHANNEL_DIVISIBLE) if width_mult > 1.0 else last_channel ) inverted_residual_setting = [ # t, c, n, s [1, 16, 1, 1], [expand_ratio, 24, 2, 2], [expand_ratio, 32, 3, 2], [expand_ratio, 64, 4, 2], [expand_ratio, 96, 3, 1], [expand_ratio, 160, 3, 2], [expand_ratio, 320, 1, 1], ] if depth_param is not None: assert isinstance(depth_param, int) for i in range(1, len(inverted_residual_setting) - 1): inverted_residual_setting[i][2] = depth_param if stage_width_list is not None: for i in range(len(inverted_residual_setting)): inverted_residual_setting[i][1] = stage_width_list[i] ks = val2list(ks, sum([n for _, _, n, _ in inverted_residual_setting]) - 1) _pt = 0 # first conv layer first_conv = ConvLayer( 3, input_channel, kernel_size=3, stride=2, use_bn=True, act_func="relu6", ops_order="weight_bn_act", ) # inverted residual blocks blocks = [] for t, c, n, s in inverted_residual_setting: output_channel = make_divisible(c * width_mult, MyNetwork.CHANNEL_DIVISIBLE) for i in range(n): if i == 0: stride = s else: stride = 1 if t == 1: kernel_size = 3 else: kernel_size = ks[_pt] _pt += 1 mobile_inverted_conv = MBConvLayer( in_channels=input_channel, out_channels=output_channel, kernel_size=kernel_size, stride=stride, expand_ratio=t, ) if stride == 1: if input_channel == output_channel: shortcut = IdentityLayer(input_channel, input_channel) else: shortcut = None else: shortcut = None blocks.append(ResidualBlock(mobile_inverted_conv, shortcut)) input_channel = output_channel # 1x1_conv before global average pooling feature_mix_layer = ConvLayer( input_channel, last_channel, kernel_size=1, use_bn=True, act_func="relu6", ops_order="weight_bn_act", ) classifier = LinearLayer(last_channel, n_classes, dropout_rate=dropout_rate) super(MobileNetV2, self).__init__( first_conv, blocks, feature_mix_layer, classifier ) # set bn param self.set_bn_param(*bn_param)
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import numpy as np import torch __all__ = ["DataProvider"] class DataProvider: SUB_SEED = 937162211 # random seed for sampling subset VALID_SEED = 2147483647 # random seed for the validation set @staticmethod def name(): """Return name of the dataset""" raise NotImplementedError @property def data_shape(self): """Return shape as python list of one data entry""" raise NotImplementedError @property def n_classes(self): """Return `int` of num classes""" raise NotImplementedError @property def save_path(self): """local path to save the data""" raise NotImplementedError @property def data_url(self): """link to download the data""" raise NotImplementedError @staticmethod def random_sample_valid_set(train_size, valid_size): assert train_size > valid_size g = torch.Generator() g.manual_seed( DataProvider.VALID_SEED ) # set random seed before sampling validation set rand_indexes = torch.randperm(train_size, generator=g).tolist() valid_indexes = rand_indexes[:valid_size] train_indexes = rand_indexes[valid_size:] return train_indexes, valid_indexes @staticmethod def labels_to_one_hot(n_classes, labels): new_labels = np.zeros((labels.shape[0], n_classes), dtype=np.float32) new_labels[range(labels.shape[0]), labels] = np.ones(labels.shape) return new_labels
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import warnings import os import math import numpy as np import torch.utils.data import torchvision.transforms as transforms import torchvision.datasets as datasets from .base_provider import DataProvider from ofa.utils.my_dataloader import MyRandomResizedCrop, MyDistributedSampler __all__ = ["ImagenetDataProvider"] class ImagenetDataProvider(DataProvider): DEFAULT_PATH = "/dataset/imagenet" def __init__( self, save_path=None, train_batch_size=256, test_batch_size=512, valid_size=None, n_worker=32, resize_scale=0.08, distort_color=None, image_size=224, num_replicas=None, rank=None, ): warnings.filterwarnings("ignore") self._save_path = save_path self.image_size = image_size # int or list of int self.distort_color = "None" if distort_color is None else distort_color self.resize_scale = resize_scale self._valid_transform_dict = {} if not isinstance(self.image_size, int): from ofa.utils.my_dataloader import MyDataLoader assert isinstance(self.image_size, list) self.image_size.sort() # e.g., 160 -> 224 MyRandomResizedCrop.IMAGE_SIZE_LIST = self.image_size.copy() MyRandomResizedCrop.ACTIVE_SIZE = max(self.image_size) for img_size in self.image_size: self._valid_transform_dict[img_size] = self.build_valid_transform( img_size ) self.active_img_size = max(self.image_size) # active resolution for test valid_transforms = self._valid_transform_dict[self.active_img_size] train_loader_class = MyDataLoader # randomly sample image size for each batch of training image else: self.active_img_size = self.image_size valid_transforms = self.build_valid_transform() train_loader_class = torch.utils.data.DataLoader train_dataset = self.train_dataset(self.build_train_transform()) if valid_size is not None: if not isinstance(valid_size, int): assert isinstance(valid_size, float) and 0 < valid_size < 1 valid_size = int(len(train_dataset) * valid_size) valid_dataset = self.train_dataset(valid_transforms) train_indexes, valid_indexes = self.random_sample_valid_set( len(train_dataset), valid_size ) if num_replicas is not None: train_sampler = MyDistributedSampler( train_dataset, num_replicas, rank, True, np.array(train_indexes) ) valid_sampler = MyDistributedSampler( valid_dataset, num_replicas, rank, True, np.array(valid_indexes) ) else: train_sampler = torch.utils.data.sampler.SubsetRandomSampler( train_indexes ) valid_sampler = torch.utils.data.sampler.SubsetRandomSampler( valid_indexes ) self.train = train_loader_class( train_dataset, batch_size=train_batch_size, sampler=train_sampler, num_workers=n_worker, pin_memory=True, ) self.valid = torch.utils.data.DataLoader( valid_dataset, batch_size=test_batch_size, sampler=valid_sampler, num_workers=n_worker, pin_memory=True, ) else: if num_replicas is not None: train_sampler = torch.utils.data.distributed.DistributedSampler( train_dataset, num_replicas, rank ) self.train = train_loader_class( train_dataset, batch_size=train_batch_size, sampler=train_sampler, num_workers=n_worker, pin_memory=True, ) else: self.train = train_loader_class( train_dataset, batch_size=train_batch_size, shuffle=True, num_workers=n_worker, pin_memory=True, ) self.valid = None test_dataset = self.test_dataset(valid_transforms) if num_replicas is not None: test_sampler = torch.utils.data.distributed.DistributedSampler( test_dataset, num_replicas, rank ) self.test = torch.utils.data.DataLoader( test_dataset, batch_size=test_batch_size, sampler=test_sampler, num_workers=n_worker, pin_memory=True, ) else: self.test = torch.utils.data.DataLoader( test_dataset, batch_size=test_batch_size, shuffle=True, num_workers=n_worker, pin_memory=True, ) if self.valid is None: self.valid = self.test @staticmethod def name(): return "imagenet" @property def data_shape(self): return 3, self.active_img_size, self.active_img_size # C, H, W @property def n_classes(self): return 1000 @property def save_path(self): if self._save_path is None: self._save_path = self.DEFAULT_PATH if not os.path.exists(self._save_path): self._save_path = os.path.expanduser("~/dataset/imagenet") return self._save_path @property def data_url(self): raise ValueError("unable to download %s" % self.name()) def train_dataset(self, _transforms): return datasets.ImageFolder(self.train_path, _transforms) def test_dataset(self, _transforms): return datasets.ImageFolder(self.valid_path, _transforms) @property def train_path(self): return os.path.join(self.save_path, "train") @property def valid_path(self): return os.path.join(self.save_path, "val") @property def normalize(self): return transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) def build_train_transform(self, image_size=None, print_log=True): if image_size is None: image_size = self.image_size if print_log: print( "Color jitter: %s, resize_scale: %s, img_size: %s" % (self.distort_color, self.resize_scale, image_size) ) if isinstance(image_size, list): resize_transform_class = MyRandomResizedCrop print( "Use MyRandomResizedCrop: %s, \t %s" % MyRandomResizedCrop.get_candidate_image_size(), "sync=%s, continuous=%s" % ( MyRandomResizedCrop.SYNC_DISTRIBUTED, MyRandomResizedCrop.CONTINUOUS, ), ) else: resize_transform_class = transforms.RandomResizedCrop # random_resize_crop -> random_horizontal_flip train_transforms = [ resize_transform_class(image_size, scale=(self.resize_scale, 1.0)), transforms.RandomHorizontalFlip(), ] # color augmentation (optional) color_transform = None if self.distort_color == "torch": color_transform = transforms.ColorJitter( brightness=0.4, contrast=0.4, saturation=0.4, hue=0.1 ) elif self.distort_color == "tf": color_transform = transforms.ColorJitter( brightness=32.0 / 255.0, saturation=0.5 ) if color_transform is not None: train_transforms.append(color_transform) train_transforms += [ transforms.ToTensor(), self.normalize, ] train_transforms = transforms.Compose(train_transforms) return train_transforms def build_valid_transform(self, image_size=None): if image_size is None: image_size = self.active_img_size return transforms.Compose( [ transforms.Resize(int(math.ceil(image_size / 0.875))), transforms.CenterCrop(image_size), transforms.ToTensor(), self.normalize, ] ) def assign_active_img_size(self, new_img_size): self.active_img_size = new_img_size if self.active_img_size not in self._valid_transform_dict: self._valid_transform_dict[ self.active_img_size ] = self.build_valid_transform() # change the transform of the valid and test set self.valid.dataset.transform = self._valid_transform_dict[self.active_img_size] self.test.dataset.transform = self._valid_transform_dict[self.active_img_size] def build_sub_train_loader( self, n_images, batch_size, num_worker=None, num_replicas=None, rank=None ): # used for resetting BN running statistics if self.__dict__.get("sub_train_%d" % self.active_img_size, None) is None: if num_worker is None: num_worker = self.train.num_workers n_samples = len(self.train.dataset) g = torch.Generator() g.manual_seed(DataProvider.SUB_SEED) rand_indexes = torch.randperm(n_samples, generator=g).tolist() new_train_dataset = self.train_dataset( self.build_train_transform( image_size=self.active_img_size, print_log=False ) ) chosen_indexes = rand_indexes[:n_images] if num_replicas is not None: sub_sampler = MyDistributedSampler( new_train_dataset, num_replicas, rank, True, np.array(chosen_indexes), ) else: sub_sampler = torch.utils.data.sampler.SubsetRandomSampler( chosen_indexes ) sub_data_loader = torch.utils.data.DataLoader( new_train_dataset, batch_size=batch_size, sampler=sub_sampler, num_workers=num_worker, pin_memory=True, ) self.__dict__["sub_train_%d" % self.active_img_size] = [] for images, labels in sub_data_loader: self.__dict__["sub_train_%d" % self.active_img_size].append( (images, labels) ) return self.__dict__["sub_train_%d" % self.active_img_size]
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. from .imagenet import *