index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
50,397
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/coerce.py
6,8
1,80
symbol
Coerce
8,24
8,24
class Coerce(object): @staticmethod def bool(space, w_obj): return space.is_true(w_obj) @staticmethod def symbol(space, w_obj): FILL_FUNC_BODY @staticmethod def int(space, w_obj): if space.is_kind_of(w_obj, space.w_fixnum): return space.int_w(w_obj) else: ...
class Coerce(object): @staticmethod def bool(space, w_obj): return space.is_true(w_obj) @staticmethod def symbol(space, w_obj): FILL_FUNC_BODY @staticmethod def int(space, w_obj): if space.is_kind_of(w_obj, space.w_fixnum): return space.int_w(w_obj) else: ...
if space.is_kind_of(w_obj, space.w_symbol): return space.symbol_w(w_obj) else: w_str = space.convert_type(w_obj, space.w_string, "to_str", raise_error=False) if w_str is space.w_nil: w_inspect_str = space.send(w_o...
if space.is_kind_of(w_obj, space.w_symbol): return space.symbol_w(w_obj) else: w_str = space.convert_type(w_obj, space.w_string, "to_str", raise_error=False) if w_str is space.w_nil: w_inspect_str = space.send(w_o...
43
747
235
982
class Coerce(object): @staticmethod def bool(space, w_obj): return space.is_true(w_obj) @staticmethod def symbol(space, w_obj): FILL_FUNC_BODY @staticmethod def int(space, w_obj): if space.is_kind_of(w_obj, space.w_fixnum): return space.int_w(w_obj) else: ...
class Coerce(object): @staticmethod def bool(space, w_obj): return space.is_true(w_obj) @staticmethod def symbol(space, w_obj): FILL_FUNC_BODY @staticmethod def int(space, w_obj): if space.is_kind_of(w_obj, space.w_fixnum): return space.int_w(w_obj) else: ...
50,398
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/error.py
44,45
1,61
error_for_oserror
45,48
45,48
import os import errno class RubyError(Exception): def __init__(self, w_value): self.w_value = w_value def __str__(self): return "<RubyError: %s>" % self.w_value def format_traceback(space, exc, top_filepath): w_bt = space.send(exc, "backtrace") bt_w = space.listview(w_bt) if bt...
import os import errno class RubyError(Exception): def __init__(self, w_value): self.w_value = w_value def __str__(self): return "<RubyError: %s>" % self.w_value def format_traceback(space, exc, top_filepath): w_bt = space.send(exc, "backtrace") bt_w = space.listview(w_bt) if bt...
return error_for_errno(space, exc.errno)
return error_for_errno(space, exc.errno)
3
606
22
628
import os import errno class RubyError(Exception): def __init__(self, w_value): self.w_value = w_value def __str__(self): return "<RubyError: %s>" % self.w_value def format_traceback(space, exc, top_filepath): w_bt = space.send(exc, "backtrace") bt_w = space.listview(w_bt) if bt...
import os import errno class RubyError(Exception): def __init__(self, w_value): self.w_value = w_value def __str__(self): return "<RubyError: %s>" % self.w_value def format_traceback(space, exc, top_filepath): w_bt = space.send(exc, "backtrace") bt_w = space.listview(w_bt) if bt...
50,399
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/module.py
103,104
1,180
check_frozen
104,124
104,124
import functools from topaz.gateway import WrapperGenerator from topaz.utils.cache import Cache class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = N...
import functools from topaz.gateway import WrapperGenerator from topaz.utils.cache import Cache class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = N...
def inner(func): code = func.__code__ space_idx = code.co_varnames.index("space") obj_idx = code.co_varnames.index(param) @functools.wraps(func) def wrapper(*args): space = args[space_idx] w_obj = args[obj_idx] if space.is_true(w_obj.get_f...
def inner(func): code = func.__code__ space_idx = code.co_varnames.index("space") obj_idx = code.co_varnames.index(param) @functools.wraps(func) def wrapper(*args): space = args[space_idx] w_obj = args[obj_idx] if space.is_true(w_obj.get_f...
44
1,490
212
1,702
import functools from topaz.gateway import WrapperGenerator from topaz.utils.cache import Cache class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = N...
import functools from topaz.gateway import WrapperGenerator from topaz.utils.cache import Cache class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = N...
50,400
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/module.py
125,126
124,158
_build
ClassCache
126,158
126,158
class ClassCache(Cache): def _build(self, classdef): FILL_FUNC_BODY
class ClassCache(Cache): def _build(self, classdef): FILL_FUNC_BODY
from topaz.objects.classobject import W_ClassObject from topaz.objects.functionobject import W_BuiltinFunction assert classdef.cls is not None, classdef.name if classdef.superclassdef is None: superclass = None else: superclass = self.space.getclassobjec...
from topaz.objects.classobject import W_ClassObject from topaz.objects.functionobject import W_BuiltinFunction assert classdef.cls is not None, classdef.name if classdef.superclassdef is None: superclass = None else: superclass = self.space.getclassobjec...
87
28
412
440
import functools from topaz.gateway import WrapperGenerator from topaz.utils.cache import Cache class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = N...
import functools from topaz.gateway import WrapperGenerator from topaz.utils.cache import Cache class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = N...
50,401
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/module.py
37,38
7,69
singleton_method
ClassDef
38,47
38,47
class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = None self.superclassdef = superclassdef self.cls = None def __repr__(self): ...
class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = None self.superclassdef = superclassdef self.cls = None def __repr__(self): ...
name = __name def adder(func): if isinstance(func, staticmethod): func = func.__func__ self.singleton_methods[name] = (func, argspec) return staticmethod(func) return adder
name = __name def adder(func): if isinstance(func, staticmethod): func = func.__func__ self.singleton_methods[name] = (func, argspec) return staticmethod(func) return adder
19
448
75
523
import functools from topaz.gateway import WrapperGenerator from topaz.utils.cache import Cache class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = N...
import functools from topaz.gateway import WrapperGenerator from topaz.utils.cache import Cache class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = N...
50,402
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/module.py
159,160
158,180
_build
ModuleCache
160,180
160,180
class ModuleCache(Cache): def _build(self, moduledef): FILL_FUNC_BODY
class ModuleCache(Cache): def _build(self, moduledef): FILL_FUNC_BODY
from topaz.objects.functionobject import W_BuiltinFunction from topaz.objects.moduleobject import W_ModuleObject from topaz.objects.objectobject import W_BaseObject w_mod = self.space.newmodule(moduledef.name) for name, (method, argspec) in moduledef.methods.iteritems(): ...
from topaz.objects.functionobject import W_BuiltinFunction from topaz.objects.moduleobject import W_ModuleObject from topaz.objects.objectobject import W_BaseObject w_mod = self.space.newmodule(moduledef.name) for name, (method, argspec) in moduledef.methods.iteritems(): ...
62
29
297
326
import functools from topaz.gateway import WrapperGenerator from topaz.utils.cache import Cache class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = N...
import functools from topaz.gateway import WrapperGenerator from topaz.utils.cache import Cache class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = N...
50,403
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/module.py
91,92
69,103
adder
ModuleDef
92,96
92,96
class ModuleDef(object): def __init__(self, name): self.name = name self.methods = {} self.singleton_methods = {} self.setup_module_func = None def __deepcopy__(self, memo): return self def method(self, __name, **argspec): name = __name def adder(f...
class ModuleDef(object): def __init__(self, name): self.name = name self.methods = {} self.singleton_methods = {} self.setup_module_func = None def __deepcopy__(self, memo): return self def method(self, __name, **argspec): name = __name def adder(f...
# TODO: should be private, once we have visibility self.methods[name] = (func, argspec) self.singleton_methods[name] = (func, argspec) return func
# TODO: should be private, once we have visibility self.methods[name] = (func, argspec) self.singleton_methods[name] = (func, argspec) return func
19
198
54
252
import functools from topaz.gateway import WrapperGenerator from topaz.utils.cache import Cache class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = N...
import functools from topaz.gateway import WrapperGenerator from topaz.utils.cache import Cache class ClassDef(object): def __init__(self, name, superclassdef=None): self.name = name self.methods = {} self.singleton_methods = {} self.includes = [] self.setup_class_func = N...
50,404
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/modules/ffi/data_converter.py
10,12
5,33
native_type
DataConverter
12,26
12,26
class DataConverter(object): # A rather abstract base class moduledef = ModuleDef('FFI::DataConverter') @moduledef.method('native_type') def native_type(self, space, args_w): FILL_FUNC_BODY @moduledef.method('to_native') def to_native(self, space, w_value, w_ctx): return w_value @m...
class DataConverter(object): # A rather abstract base class moduledef = ModuleDef('FFI::DataConverter') @moduledef.method('native_type') def native_type(self, space, args_w): FILL_FUNC_BODY @moduledef.method('to_native') def to_native(self, space, w_value, w_ctx): return w_value @m...
# if len(args_w) == 0: # raise space.error(space.w_NotImplementedError, # "native_type method not overridden and no " # "native_type set") if len(args_w) == 0: w_void = space.execute("FFI::Type::VOID") space.set...
# if len(args_w) == 0: # raise space.error(space.w_NotImplementedError, # "native_type method not overridden and no " # "native_type set") if len(args_w) == 0: w_void = space.execute("FFI::Type::VOID") space.set...
48
147
221
368
from topaz.module import ModuleDef from topaz.modules.ffi.type import type_object class DataConverter(object): # A rather abstract base class moduledef = ModuleDef('FFI::DataConverter') @moduledef.method('native_type') def native_type(self, space, args_w): FILL_FUNC_BODY @moduledef.method('to_nat...
from topaz.module import ModuleDef from topaz.modules.ffi.type import type_object class DataConverter(object): # A rather abstract base class moduledef = ModuleDef('FFI::DataConverter') @moduledef.method('native_type') def native_type(self, space, args_w): FILL_FUNC_BODY @moduledef.method('to_nat...
50,405
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/bindingobject.py
19,21
6,30
method_eval
W_BindingObject
21,30
21,30
class W_BindingObject(W_Object): classdef = ClassDef("Binding", W_Object.classdef) _immutable_fields_ = ["names[*]", "cells[*]", "w_self", "lexical_scope"] def __init__(self, space, names, cells, w_self, lexical_scope): W_Object.__init__(self, space) self.names = names self.cells = ...
class W_BindingObject(W_Object): classdef = ClassDef("Binding", W_Object.classdef) _immutable_fields_ = ["names[*]", "cells[*]", "w_self", "lexical_scope"] def __init__(self, space, names, cells, w_self, lexical_scope): W_Object.__init__(self, space) self.names = names self.cells = ...
symtable = SymbolTable() for name in self.names: symtable.cells[name] = symtable.FREEVAR bc = space.compile(source, "(eval)", symtable=symtable) frame = space.create_frame(bc, w_self=self.w_self, lexical_scope=self.lexical_scope) for idx, cell in enumerate(self.cells)...
symtable = SymbolTable() for name in self.names: symtable.cells[name] = symtable.FREEVAR bc = space.compile(source, "(eval)", symtable=symtable) frame = space.create_frame(bc, w_self=self.w_self, lexical_scope=self.lexical_scope) for idx, cell in enumerate(self.cells)...
35
189
162
351
from topaz.astcompiler import SymbolTable from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_BindingObject(W_Object): classdef = ClassDef("Binding", W_Object.classdef) _immutable_fields_ = ["names[*]", "cells[*]", "w_self", "lexical_scope"] def __init__(self, space,...
from topaz.astcompiler import SymbolTable from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_BindingObject(W_Object): classdef = ClassDef("Binding", W_Object.classdef) _immutable_fields_ = ["names[*]", "cells[*]", "w_self", "lexical_scope"] def __init__(self, space,...
50,406
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/boolobject.py
55,57
33,62
method_or
W_FalseObject
57,59
57,59
class W_FalseObject(W_Object): classdef = ClassDef("FalseClass", W_Object.classdef) def is_true(self, space): return False def getsingletonclass(self, space): return space.getclassfor(W_FalseObject) @classdef.method("inspect") @classdef.method("to_s") def method_to_s(self, spa...
class W_FalseObject(W_Object): classdef = ClassDef("FalseClass", W_Object.classdef) def is_true(self, space): return False def getsingletonclass(self, space): return space.getclassfor(W_FalseObject) @classdef.method("inspect") @classdef.method("to_s") def method_to_s(self, spa...
return space.newbool(space.is_true(w_other))
return space.newbool(space.is_true(w_other))
2
277
21
298
from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_TrueObject(W_Object): classdef = ClassDef("TrueClass", W_Object.classdef) def getsingletonclass(self, space): return space.getclassfor(W_TrueObject) @classdef.method("inspect") @classdef.method("to_s") ...
from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_TrueObject(W_Object): classdef = ClassDef("TrueClass", W_Object.classdef) def getsingletonclass(self, space): return space.getclassfor(W_TrueObject) @classdef.method("inspect") @classdef.method("to_s") ...
50,407
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/boolobject.py
8,9
5,33
getsingletonclass
W_TrueObject
9,11
9,11
class W_TrueObject(W_Object): classdef = ClassDef("TrueClass", W_Object.classdef) def getsingletonclass(self, space): FILL_FUNC_BODY @classdef.method("inspect") @classdef.method("to_s") def method_to_s(self, space): return space.newstr_fromstr("true") @classdef.method("==") def meth...
class W_TrueObject(W_Object): classdef = ClassDef("TrueClass", W_Object.classdef) def getsingletonclass(self, space): FILL_FUNC_BODY @classdef.method("inspect") @classdef.method("to_s") def method_to_s(self, space): return space.newstr_fromstr("true") @classdef.method("==") def meth...
return space.getclassfor(W_TrueObject)
return space.getclassfor(W_TrueObject)
2
268
17
285
from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_TrueObject(W_Object): classdef = ClassDef("TrueClass", W_Object.classdef) def getsingletonclass(self, space): FILL_FUNC_BODY @classdef.method("inspect") @classdef.method("to_s") def method_to_s(self, space): ...
from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_TrueObject(W_Object): classdef = ClassDef("TrueClass", W_Object.classdef) def getsingletonclass(self, space): FILL_FUNC_BODY @classdef.method("inspect") @classdef.method("to_s") def method_to_s(self, space): ...
50,408
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/codeobject.py
82,83
7,91
arity
W_CodeObject
83,88
83,88
class W_CodeObject(W_BaseObject): _immutable_fields_ = [ "code", "consts_w[*]", "max_stackdepth", "cellvars[*]", "freevars[*]", "arg_pos[*]", "defaults[*]", "block_arg_pos", "splat_arg_pos", "kwarg_names[*]", "kwrest_pos", "kw_defaults[*]", "default_arg_begin", "filepath", "lineno", ...
class W_CodeObject(W_BaseObject): _immutable_fields_ = [ "code", "consts_w[*]", "max_stackdepth", "cellvars[*]", "freevars[*]", "arg_pos[*]", "defaults[*]", "block_arg_pos", "splat_arg_pos", "kwarg_names[*]", "kwrest_pos", "kw_defaults[*]", "default_arg_begin", "filepath", "lineno", ...
args_count = len(self.arg_pos) - len(self.defaults) if self.splat_arg_pos != -1 or (negative_defaults and len(self.defaults) > 0): args_count = -(args_count + 1) return args_count
args_count = len(self.arg_pos) - len(self.defaults) if self.splat_arg_pos != -1 or (negative_defaults and len(self.defaults) > 0): args_count = -(args_count + 1) return args_count
22
974
77
1,051
import copy from topaz.module import ClassDef from topaz.objects.objectobject import W_BaseObject class W_CodeObject(W_BaseObject): _immutable_fields_ = [ "code", "consts_w[*]", "max_stackdepth", "cellvars[*]", "freevars[*]", "arg_pos[*]", "defaults[*]", "block_arg_pos", "splat_arg_pos", ...
import copy from topaz.module import ClassDef from topaz.objects.objectobject import W_BaseObject class W_CodeObject(W_BaseObject): _immutable_fields_ = [ "code", "consts_w[*]", "max_stackdepth", "cellvars[*]", "freevars[*]", "arg_pos[*]", "defaults[*]", "block_arg_pos", "splat_arg_pos", ...
50,409
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/encodingobject.py
24,26
5,31
singleton_method_aliases
W_EncodingObject
26,28
26,28
class W_EncodingObject(W_Object): classdef = ClassDef("Encoding", W_Object.classdef) @classdef.singleton_method("default_external") def singleton_method_default_external(self, space): return W_EncodingObject(space) @classdef.singleton_method("default_internal") def singleton_method_default...
class W_EncodingObject(W_Object): classdef = ClassDef("Encoding", W_Object.classdef) @classdef.singleton_method("default_external") def singleton_method_default_external(self, space): return W_EncodingObject(space) @classdef.singleton_method("default_internal") def singleton_method_default...
return space.newarray([])
return space.newarray([])
2
277
13
290
from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_EncodingObject(W_Object): classdef = ClassDef("Encoding", W_Object.classdef) @classdef.singleton_method("default_external") def singleton_method_default_external(self, space): return W_EncodingObject(space) ...
from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_EncodingObject(W_Object): classdef = ClassDef("Encoding", W_Object.classdef) @classdef.singleton_method("default_external") def singleton_method_default_external(self, space): return W_EncodingObject(space) ...
50,410
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/functionobject.py
83,84
71,93
call
W_BuiltinFunction
84,93
84,93
class W_BuiltinFunction(W_FunctionObject): _immutable_fields_ = ["func"] def __init__(self, name, w_class, func, visibility=W_FunctionObject.PUBLIC): W_FunctionObject.__init__(self, name, w_class, visibility=visibility) self.func = func def __deepcopy__(self, memo): obj = super(W_B...
class W_BuiltinFunction(W_FunctionObject): _immutable_fields_ = ["func"] def __init__(self, name, w_class, func, visibility=W_FunctionObject.PUBLIC): W_FunctionObject.__init__(self, name, w_class, visibility=visibility) self.func = func def __deepcopy__(self, memo): obj = super(W_B...
from topaz.frame import BuiltinFrame frame = BuiltinFrame(self.name) ec = space.getexecutioncontext() ec.invoke_trace_proc(space, "c-call", self.name, self.w_class.name) with ec.visit_frame(frame): w_res = self.func(w_receiver, space, args_w, block) ec.invoke...
from topaz.frame import BuiltinFrame frame = BuiltinFrame(self.name) ec = space.getexecutioncontext() ec.invoke_trace_proc(space, "c-call", self.name, self.w_class.name) with ec.visit_frame(frame): w_res = self.func(w_receiver, space, args_w, block) ec.invoke...
28
162
144
306
import copy from topaz.objects.objectobject import W_BaseObject class W_FunctionObject(W_BaseObject): _immutable_fields_ = ["name", "w_class", "visibility?"] PUBLIC = 0 PROTECTED = 1 PRIVATE = 2 MODULE_FUNCTION = 3 def __init__(self, name, w_class=None, visibility=PUBLIC): self.name...
import copy from topaz.objects.objectobject import W_BaseObject class W_FunctionObject(W_BaseObject): _immutable_fields_ = ["name", "w_class", "visibility?"] PUBLIC = 0 PROTECTED = 1 PRIVATE = 2 MODULE_FUNCTION = 3 def __init__(self, name, w_class=None, visibility=PUBLIC): self.name...
50,411
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/functionobject.py
26,27
6,36
update_visibility
W_FunctionObject
27,29
27,29
class W_FunctionObject(W_BaseObject): _immutable_fields_ = ["name", "w_class", "visibility?"] PUBLIC = 0 PROTECTED = 1 PRIVATE = 2 MODULE_FUNCTION = 3 def __init__(self, name, w_class=None, visibility=PUBLIC): self.name = name self.w_class = w_class self.visibility = vi...
class W_FunctionObject(W_BaseObject): _immutable_fields_ = ["name", "w_class", "visibility?"] PUBLIC = 0 PROTECTED = 1 PRIVATE = 2 MODULE_FUNCTION = 3 def __init__(self, name, w_class=None, visibility=PUBLIC): self.name = name self.w_class = w_class self.visibility = vi...
self.visibility = visibility
self.visibility = visibility
3
268
11
279
import copy from topaz.objects.objectobject import W_BaseObject class W_FunctionObject(W_BaseObject): _immutable_fields_ = ["name", "w_class", "visibility?"] PUBLIC = 0 PROTECTED = 1 PRIVATE = 2 MODULE_FUNCTION = 3 def __init__(self, name, w_class=None, visibility=PUBLIC): self.name...
import copy from topaz.objects.objectobject import W_BaseObject class W_FunctionObject(W_BaseObject): _immutable_fields_ = ["name", "w_class", "visibility?"] PUBLIC = 0 PROTECTED = 1 PRIVATE = 2 MODULE_FUNCTION = 3 def __init__(self, name, w_class=None, visibility=PUBLIC): self.name...
50,412
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/functionobject.py
50,51
36,71
call
W_UserFunction
51,61
51,61
class W_UserFunction(W_FunctionObject): _immutable_fields_ = ["bytecode", "lexical_scope"] def __init__(self, name, bytecode, lexical_scope, visibility=W_FunctionObject.PUBLIC): W_FunctionObject.__init__(self, name, visibility=visibility) self.bytecode = bytecode self.lexical_scope = le...
class W_UserFunction(W_FunctionObject): _immutable_fields_ = ["bytecode", "lexical_scope"] def __init__(self, name, bytecode, lexical_scope, visibility=W_FunctionObject.PUBLIC): W_FunctionObject.__init__(self, name, visibility=visibility) self.bytecode = bytecode self.lexical_scope = le...
frame = space.create_frame( self.bytecode, w_self=w_receiver, lexical_scope=self.lexical_scope, block=block, ) with space.getexecutioncontext().visit_frame(frame): frame.handle_args(space, self.bytecode, args_w, block) retur...
frame = space.create_frame( self.bytecode, w_self=w_receiver, lexical_scope=self.lexical_scope, block=block, ) with space.getexecutioncontext().visit_frame(frame): frame.handle_args(space, self.bytecode, args_w, block) retur...
17
305
116
421
import copy from topaz.objects.objectobject import W_BaseObject class W_FunctionObject(W_BaseObject): _immutable_fields_ = ["name", "w_class", "visibility?"] PUBLIC = 0 PROTECTED = 1 PRIVATE = 2 MODULE_FUNCTION = 3 def __init__(self, name, w_class=None, visibility=PUBLIC): self.name...
import copy from topaz.objects.objectobject import W_BaseObject class W_FunctionObject(W_BaseObject): _immutable_fields_ = ["name", "w_class", "visibility?"] PUBLIC = 0 PROTECTED = 1 PRIVATE = 2 MODULE_FUNCTION = 3 def __init__(self, name, w_class=None, visibility=PUBLIC): self.name...
50,413
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/nilobject.py
18,20
5,46
method_to_s
W_NilObject
20,22
20,22
class W_NilObject(W_Object): classdef = ClassDef("NilClass", W_Object.classdef) def is_true(self, space): return False def getsingletonclass(self, space): return space.getclassfor(W_NilObject) @classdef.method("nil?") def method_nilp(self, space): return space.w_true ...
class W_NilObject(W_Object): classdef = ClassDef("NilClass", W_Object.classdef) def is_true(self, space): return False def getsingletonclass(self, space): return space.getclassfor(W_NilObject) @classdef.method("nil?") def method_nilp(self, space): return space.w_true ...
return space.newstr_fromstr("")
return space.newstr_fromstr("")
2
377
15
392
from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_NilObject(W_Object): classdef = ClassDef("NilClass", W_Object.classdef) def is_true(self, space): return False def getsingletonclass(self, space): return space.getclassfor(W_NilObject) @classde...
from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_NilObject(W_Object): classdef = ClassDef("NilClass", W_Object.classdef) def is_true(self, space): return False def getsingletonclass(self, space): return space.getclassfor(W_NilObject) @classde...
50,414
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/procobject.py
46,51
5,84
method_call
W_ProcObject
51,66
51,66
class W_ProcObject(W_Object): classdef = ClassDef("Proc", W_Object.classdef) _immutable_fields_ = [ "bytecode", "w_self", "lexical_scope", "cells[*]", "block", "parent_interp", "top_parent_interp", "regexp_match_cell", "is_lambda"] def __init__(self, space, bytecode, w_self, lexical...
class W_ProcObject(W_Object): classdef = ClassDef("Proc", W_Object.classdef) _immutable_fields_ = [ "bytecode", "w_self", "lexical_scope", "cells[*]", "block", "parent_interp", "top_parent_interp", "regexp_match_cell", "is_lambda"] def __init__(self, space, bytecode, w_self, lexical...
from topaz.interpreter import RaiseReturn, RaiseBreak try: return space.invoke_block(self, args_w, block_arg=block) except RaiseReturn as e: if self.is_lambda: return e.w_value else: raise except RaiseBreak as e: ...
from topaz.interpreter import RaiseReturn, RaiseBreak try: return space.invoke_block(self, args_w, block_arg=block) except RaiseReturn as e: if self.is_lambda: return e.w_value else: raise except RaiseBreak as e: ...
34
766
145
911
from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_ProcObject(W_Object): classdef = ClassDef("Proc", W_Object.classdef) _immutable_fields_ = [ "bytecode", "w_self", "lexical_scope", "cells[*]", "block", "parent_interp", "top_parent_interp", "regex...
from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_ProcObject(W_Object): classdef = ClassDef("Proc", W_Object.classdef) _immutable_fields_ = [ "bytecode", "w_self", "lexical_scope", "cells[*]", "block", "parent_interp", "top_parent_interp", "regex...
50,415
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/rangeobject.py
21,23
6,43
method_initialize
W_RangeObject
23,32
23,32
class W_RangeObject(W_Object): classdef = ClassDef("Range", W_Object.classdef) classdef.include_module(Enumerable) _immutable_fields_ = ["w_start", "w_end", "exclusive"] def __init__(self, space, w_start, w_end, exclusive): W_Object.__init__(self, space) self.w_start = w_start s...
class W_RangeObject(W_Object): classdef = ClassDef("Range", W_Object.classdef) classdef.include_module(Enumerable) _immutable_fields_ = ["w_start", "w_end", "exclusive"] def __init__(self, space, w_start, w_end, exclusive): W_Object.__init__(self, space) self.w_start = w_start s...
if self.w_start is not None or self.w_end is not None: raise space.error(space.w_NameError, "`initialize' called twice") if space.send(w_start, "<=>", [w_end]) is space.w_nil: raise space.error(space.w_ArgumentError, "bad value for range") self.w_start = w_start ...
if self.w_start is not None or self.w_end is not None: raise space.error(space.w_NameError, "`initialize' called twice") if space.send(w_start, "<=>", [w_end]) is space.w_nil: raise space.error(space.w_ArgumentError, "bad value for range") self.w_start = w_start ...
36
323
132
455
from topaz.module import ClassDef from topaz.modules.enumerable import Enumerable from topaz.objects.objectobject import W_Object class W_RangeObject(W_Object): classdef = ClassDef("Range", W_Object.classdef) classdef.include_module(Enumerable) _immutable_fields_ = ["w_start", "w_end", "exclusive"] d...
from topaz.module import ClassDef from topaz.modules.enumerable import Enumerable from topaz.objects.objectobject import W_Object class W_RangeObject(W_Object): classdef = ClassDef("Range", W_Object.classdef) classdef.include_module(Enumerable) _immutable_fields_ = ["w_start", "w_end", "exclusive"] d...
50,416
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/symbolobject.py
63,65
6,83
method_comparator
W_SymbolObject
65,76
65,76
class W_SymbolObject(W_Object): _immutable_fields_ = ["symbol"] classdef = ClassDef("Symbol", W_Object.classdef) classdef.include_module(Comparable) def __init__(self, space, symbol): W_Object.__init__(self, space) self.symbol = symbol def __deepcopy__(self, memo): obj = su...
class W_SymbolObject(W_Object): _immutable_fields_ = ["symbol"] classdef = ClassDef("Symbol", W_Object.classdef) classdef.include_module(Comparable) def __init__(self, space, symbol): W_Object.__init__(self, space) self.symbol = symbol def __deepcopy__(self, memo): obj = su...
if not space.is_kind_of(w_other, space.w_symbol): return space.w_nil s1 = self.symbol s2 = space.symbol_w(w_other) if s1 < s2: return space.newint(-1) elif s1 == s2: return space.newint(0) elif s1 > s2: return space.newint(1...
if not space.is_kind_of(w_other, space.w_symbol): return space.w_nil s1 = self.symbol s2 = space.symbol_w(w_other) if s1 < s2: return space.newint(-1) elif s1 == s2: return space.newint(0) elif s1 > s2: return space.newint(1...
30
667
122
789
from topaz.module import ClassDef from topaz.modules.comparable import Comparable from topaz.objects.objectobject import W_Object class W_SymbolObject(W_Object): _immutable_fields_ = ["symbol"] classdef = ClassDef("Symbol", W_Object.classdef) classdef.include_module(Comparable) def __init__(self, spa...
from topaz.module import ClassDef from topaz.modules.comparable import Comparable from topaz.objects.objectobject import W_Object class W_SymbolObject(W_Object): _immutable_fields_ = ["symbol"] classdef = ClassDef("Symbol", W_Object.classdef) classdef.include_module(Comparable) def __init__(self, spa...
50,417
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/objects/threadobject.py
28,30
7,53
method_subscript_assign
W_ThreadObject
30,33
30,33
class W_ThreadObject(W_Object): classdef = ClassDef("Thread", W_Object.classdef) def __init__(self, space): W_Object.__init__(self, space) # TODO: This should be a map dict. self.local_storage = {} def __deepcopy__(self, memo): obj = super(W_ThreadObject, self).__deepcopy__...
class W_ThreadObject(W_Object): classdef = ClassDef("Thread", W_Object.classdef) def __init__(self, space): W_Object.__init__(self, space) # TODO: This should be a map dict. self.local_storage = {} def __deepcopy__(self, memo): obj = super(W_ThreadObject, self).__deepcopy__...
self.local_storage[key] = w_value return w_value
self.local_storage[key] = w_value return w_value
5
519
24
543
import copy from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_ThreadObject(W_Object): classdef = ClassDef("Thread", W_Object.classdef) def __init__(self, space): W_Object.__init__(self, space) # TODO: This should be a map dict. self.local_stora...
import copy from topaz.module import ClassDef from topaz.objects.objectobject import W_Object class W_ThreadObject(W_Object): classdef = ClassDef("Thread", W_Object.classdef) def __init__(self, space): W_Object.__init__(self, space) # TODO: This should be a map dict. self.local_stora...
50,418
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz
/home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/tools/make_release.py
9,10
1,30
main
10,28
10,28
import os import sys import tarfile PROJECT_ROOT = os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir) def main(argv): FILL_FUNC_BODYif __name__ == "__main__": main(sys.argv[1:])
import os import sys import tarfile PROJECT_ROOT = os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir) def main(argv): FILL_FUNC_BODYif __name__ == "__main__": main(sys.argv[1:])
target = argv[0] t = tarfile.open(target, mode="w:bz2") for name in [ "bin/topaz.exe" if sys.platform == "win32" else "bin/topaz", "lib-ruby", "lib-topaz", "AUTHORS.rst", "LICENSE", "README.rst" ]: t.add(os.path.join(PROJECT_ROOT, name), arcname="t...
target = argv[0] t = tarfile.open(target, mode="w:bz2") for name in [ "bin/topaz.exe" if sys.platform == "win32" else "bin/topaz", "lib-ruby", "lib-topaz", "AUTHORS.rst", "LICENSE", "README.rst" ]: t.add(os.path.join(PROJECT_ROOT, name), arcname="t...
45
92
214
306
import os import sys import tarfile PROJECT_ROOT = os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir) def main(argv): FILL_FUNC_BODYif __name__ == "__main__": main(sys.argv[1:])
import os import sys import tarfile PROJECT_ROOT = os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir) def main(argv): FILL_FUNC_BODYif __name__ == "__main__": main(sys.argv[1:])
50,507
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx/smplx/joint_names.py
291,293
272,321
from_smplh
Body
296,298
293,298
class Body: """ Class for storing a single body pose. """ def __init__(self, joints, joint_names): assert joints.ndim > 1 assert joints.shape[0] == len(joint_names) self.joints = {} for i, j in enumerate(joint_names): self.joints[j] = joints[i] @staticme...
class Body: """ Class for storing a single body pose. """ def __init__(self, joints, joint_names): assert joints.ndim > 1 assert joints.shape[0] == len(joint_names) self.joints = {} for i, j in enumerate(joint_names): self.joints[j] = joints[i] @staticme...
return Body(joints, SMPLH_JOINT_NAMES)
""" Create a Body object from SMPLH joints. """ return Body(joints, SMPLH_JOINT_NAMES)
3
413
22
435
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
50,509
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx/smplx/utils.py
120,121
1,127
rot_mat_to_euler
121,127
121,127
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# Calculates rotation matrix to euler angles # Careful for extreme cases of eular angles like [0.0, pi, 0.0] sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] + rot_mats[:, 1, 0] * rot_mats[:, 1, 0]) return torch.atan2(-rot_mats[:, 2, 0], sy)
# Calculates rotation matrix to euler angles # Careful for extreme cases of eular angles like [0.0, pi, 0.0] sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] + rot_mats[:, 1, 0] * rot_mats[:, 1, 0]) return torch.atan2(-rot_mats[:, 2, 0], sy)
41
1,081
129
1,210
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
50,510
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx/smplx/utils.py
38,39
26,57
get
ModelOutput
39,41
39,41
@dataclass class ModelOutput: vertices: Optional[Tensor] = None joints: Optional[Tensor] = None full_pose: Optional[Tensor] = None global_orient: Optional[Tensor] = None transl: Optional[Tensor] = None v_shaped: Optional[Tensor] = None def __getitem__(self, key): return getattr(self...
@dataclass class ModelOutput: vertices: Optional[Tensor] = None joints: Optional[Tensor] = None full_pose: Optional[Tensor] = None global_orient: Optional[Tensor] = None transl: Optional[Tensor] = None v_shaped: Optional[Tensor] = None def __getitem__(self, key): return getattr(self...
return getattr(self, key, default)
return getattr(self, key, default)
4
253
15
268
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
50,511
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx/smplx/vertex_joint_selector.py
73,74
29,81
forward
VertexJointSelector
74,81
74,81
class VertexJointSelector(nn.Module): def __init__(self, vertex_ids=None, use_hands=True, use_feet_keypoints=True, **kwargs): super(VertexJointSelector, self).__init__() extra_joints_idxs = [] face_keyp_idxs = np.array([ vertex_ids['nose'], ...
class VertexJointSelector(nn.Module): def __init__(self, vertex_ids=None, use_hands=True, use_feet_keypoints=True, **kwargs): super(VertexJointSelector, self).__init__() extra_joints_idxs = [] face_keyp_idxs = np.array([ vertex_ids['nose'], ...
extra_joints = torch.index_select(vertices, 1, self.extra_joints_idxs.to(torch.long)) #The '.to(torch.long)'. # added to make the trace work in c++, ...
extra_joints = torch.index_select(vertices, 1, self.extra_joints_idxs.to(torch.long)) #The '.to(torch.long)'. # added to make the trace work in c++, ...
41
507
134
641
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
50,512
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx/tools/merge_smplh_mano.py
29,31
1,102
merge_models
31,78
31,78
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
if smplh_fn.endswith('.pkl'): with open(smplh_fn, 'rb') as body_file: body_data = pickle.load(body_file, encoding='latin1') elif smplh_fn.endswith('.npz'): body_data_np = np.load(smplh_fn) body_data = {} for key in body_data_np: body_data[key] = body_data...
if smplh_fn.endswith('.pkl'): with open(smplh_fn, 'rb') as body_file: body_data = pickle.load(body_file, encoding='latin1') elif smplh_fn.endswith('.npz'): body_data_np = np.load(smplh_fn) body_data = {} for key in body_data_np: body_data[key] = body_data...
120
664
639
1,303
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
50,513
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx/transfer_model/losses/utils.py
19,20
1,28
get_reduction_method
20,28
20,28
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
if reduction == 'mean': return torch.mean elif reduction == 'sum': return torch.sum elif reduction == 'none': return lambda x: x else: raise ValueError('Unknown reduction method: {}'.format(reduction))
if reduction == 'mean': return torch.mean elif reduction == 'sum': return torch.sum elif reduction == 'none': return lambda x: x else: raise ValueError('Unknown reduction method: {}'.format(reduction))
26
255
75
330
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
50,514
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx/transfer_model/utils/metrics.py
21,22
1,26
v2v
22,26
22,26
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
if torch.is_tensor(x): return (x - y).pow(2).sum(dim=-1).sqrt().mean() else: return np.sqrt(np.power(x - y, 2)).sum(axis=-1).mean()
if torch.is_tensor(x): return (x - y).pow(2).sum(dim=-1).sqrt().mean() else: return np.sqrt(np.power(x - y, 2)).sum(axis=-1).mean()
12
256
70
326
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
50,515
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx/transfer_model/utils/np_utils.py
23,24
1,35
rel_change
24,27
24,27
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
return (prev_val - curr_val) / max([np.abs(prev_val), np.abs(curr_val), 1])
return (prev_val - curr_val) / max([np.abs(prev_val), np.abs(curr_val), 1])
8
363
41
404
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
50,516
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx
/home/hieuvd/dung_repo/raw/stars_03/vchoutas_smplx/smplx/transfer_model/utils/torch_utils.py
21,22
1,25
from_torch
22,25
22,25
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
if torch.is_tensor(x): x = x.detach().cpu().numpy() return x.astype(dtype)
if torch.is_tensor(x): x = x.detach().cpu().numpy() return x.astype(dtype)
7
264
41
305
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
50,517
/home/hieuvd/dung_repo/raw/stars_03/wapiflapi_binglide/binglide
/home/hieuvd/dung_repo/raw/stars_03/wapiflapi_binglide/binglide/binglide/levelers.py
32,34
1,61
lvl_cumul256proj_NDS
34,61
34,61
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from functools import reduce from operator import itemgetter, mul import numpy as np from binglide.renderers import Renderer @Renderer.register_leveler(None) def lvl_256proj(dst, data, shape): l = np.amin(data) h = np.amax(data) print("leveling: %s %s" % ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from functools import reduce from operator import itemgetter, mul import numpy as np from binglide.renderers import Renderer @Renderer.register_leveler(None) def lvl_256proj(dst, data, shape): l = np.amin(data) h = np.amax(data) print("leveling: %s %s" % ...
print("leveling %s" % (shape,)) print("\tsorting. %d / %d = %d%%" % ( len(data), reduce(mul, shape), len(data) * 100 / reduce(mul, shape))) tgrams = sorted(data.items(), key=itemgetter(1)) print("\tdone sorting.") hist = np.zeros(shape) nbtg = float(sum(t[1] for t in ...
print("leveling %s" % (shape,)) print("\tsorting. %d / %d = %d%%" % ( len(data), reduce(mul, shape), len(data) * 100 / reduce(mul, shape))) tgrams = sorted(data.items(), key=itemgetter(1)) print("\tdone sorting.") hist = np.zeros(shape) nbtg = float(sum(t[1] for t in ...
73
290
255
545
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from functools import reduce from operator import itemgetter, mul import numpy as np from binglide.renderers import Renderer @Renderer.register_leveler(None) def lvl_256proj(dst, data, shape): l = np.amin(data) h = np.amax(data) print("leveling: %s %s" % ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from functools import reduce from operator import itemgetter, mul import numpy as np from binglide.renderers import Renderer @Renderer.register_leveler(None) def lvl_256proj(dst, data, shape): l = np.amin(data) h = np.amax(data) print("leveling: %s %s" % ...
50,518
/home/hieuvd/dung_repo/raw/stars_03/wapiflapi_binglide/binglide
/home/hieuvd/dung_repo/raw/stars_03/wapiflapi_binglide/binglide/binglide/mixers.py
13,14
8,20
get_coefs
ChannelMixer
14,16
14,16
class ChannelMixer(object): def __init__(self, reds=False, greens=False, blues=False, alpha=False): self.channels = [i for i, v in enumerate((reds, greens, blues, alpha)) if v] def get_coefs(self): FILL_FUNC_BODY def __call__(self, colored, data, coefs): for c in self.channels: ...
class ChannelMixer(object): def __init__(self, reds=False, greens=False, blues=False, alpha=False): self.channels = [i for i, v in enumerate((reds, greens, blues, alpha)) if v] def get_coefs(self): FILL_FUNC_BODY def __call__(self, colored, data, coefs): for c in self.channels: ...
return [float(c in self.channels) for c in range(4)]
return [float(c in self.channels) for c in range(4)]
8
133
23
156
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np from binglide.renderers import Renderer class ChannelMixer(object): def __init__(self, reds=False, greens=False, blues=False, alpha=False): self.channels = [i for i, v in enumerate((reds, greens, blues, alpha)) if v] def get_coefs(se...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np from binglide.renderers import Renderer class ChannelMixer(object): def __init__(self, reds=False, greens=False, blues=False, alpha=False): self.channels = [i for i, v in enumerate((reds, greens, blues, alpha)) if v] def get_coefs(se...
50,519
/home/hieuvd/dung_repo/raw/stars_03/wapiflapi_binglide/binglide
/home/hieuvd/dung_repo/raw/stars_03/wapiflapi_binglide/binglide/binglide/painters.py
51,53
1,76
paint_asciiposx
53,76
53,76
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np from binglide.renderers import Renderer @Renderer.register_painter(None) def paint_values(colored, data, mixers, coefs): for mixer in mixers: mixer(colored, data, coefs) return colored @Renderer.register_painter(None) def paint_ascii(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np from binglide.renderers import Renderer @Renderer.register_painter(None) def paint_values(colored, data, mixers, coefs): for mixer in mixers: mixer(colored, data, coefs) return colored @Renderer.register_painter(None) def paint_ascii(...
ndata = np.zeros(data.shape) print(data.shape) if len(data.shape) == 3: l, h = 0x20 * data.shape[0] // 256, 0x7e * data.shape[0] // 256 ndata[l:h, 0:-1, 0:-1] += data[l:h, 0:-1, 0:-1] * 0.33 l, h = 0x20 * data.shape[1] // 256, 0x7e * data.shape[1] // 256 ndata[0:-1, l:h, 0:...
ndata = np.zeros(data.shape) print(data.shape) if len(data.shape) == 3: l, h = 0x20 * data.shape[0] // 256, 0x7e * data.shape[0] // 256 ndata[l:h, 0:-1, 0:-1] += data[l:h, 0:-1, 0:-1] * 0.33 l, h = 0x20 * data.shape[1] // 256, 0x7e * data.shape[1] // 256 ndata[0:-1, l:h, 0:...
136
717
514
1,231
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np from binglide.renderers import Renderer @Renderer.register_painter(None) def paint_values(colored, data, mixers, coefs): for mixer in mixers: mixer(colored, data, coefs) return colored @Renderer.register_painter(None) def paint_ascii(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np from binglide.renderers import Renderer @Renderer.register_painter(None) def paint_values(colored, data, mixers, coefs): for mixer in mixers: mixer(colored, data, coefs) return colored @Renderer.register_painter(None) def paint_ascii(...
50,520
/home/hieuvd/dung_repo/raw/stars_03/wapiflapi_binglide/binglide
/home/hieuvd/dung_repo/raw/stars_03/wapiflapi_binglide/binglide/binglide/projectors.py
12,14
1,80
proj_scanline
14,43
14,43
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import operator from functools import reduce from math import floor, ceil import numpy as np from binglide.renderers import Renderer @Renderer.register_projector((("1D", "2D", "3D"), ("1D", "2D", "3D"))) def proj_scanline(dst, data, shape): FILL_FUNC_BODYdef proj_scanl...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import operator from functools import reduce from math import floor, ceil import numpy as np from binglide.renderers import Renderer @Renderer.register_projector((("1D", "2D", "3D"), ("1D", "2D", "3D"))) def proj_scanline(dst, data, shape): FILL_FUNC_BODYdef proj_scanl...
# We get colored data. Carefull for the extra dimension. # Shape doesnt have RGBA dimension. size = data.size / 4 # Ignore RGBA values. ratio = size / reduce(operator.mul, shape) ratio = pow(ratio, 1/len(shape)) rshape_c = [int(ceil(ratio * x)) for x in shape] rshape = [int(ratio * x) fo...
# We get colored data. Carefull for the extra dimension. # Shape doesnt have RGBA dimension. size = data.size / 4 # Ignore RGBA values. ratio = size / reduce(operator.mul, shape) ratio = pow(ratio, 1/len(shape)) rshape_c = [int(ceil(ratio * x)) for x in shape] rshape = [int(ratio * x) fo...
106
503
296
799
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import operator from functools import reduce from math import floor, ceil import numpy as np from binglide.renderers import Renderer @Renderer.register_projector((("1D", "2D", "3D"), ("1D", "2D", "3D"))) def proj_scanline(dst, data, shape): FILL_FUNC_BODYdef proj_scanl...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import operator from functools import reduce from math import floor, ceil import numpy as np from binglide.renderers import Renderer @Renderer.register_projector((("1D", "2D", "3D"), ("1D", "2D", "3D"))) def proj_scanline(dst, data, shape): FILL_FUNC_BODYdef proj_scanl...
50,521
/home/hieuvd/dung_repo/raw/stars_03/wapiflapi_binglide/binglide
/home/hieuvd/dung_repo/raw/stars_03/wapiflapi_binglide/binglide/binglide/utils.py
2,3
1,4
ddim_from_shape
3,4
3,4
def ddim_from_shape(shape): FILL_FUNC_BODY
def ddim_from_shape(shape): FILL_FUNC_BODY
return "%dD" % len(shape)
return "%dD" % len(shape)
4
22
13
35
def ddim_from_shape(shape): FILL_FUNC_BODY
def ddim_from_shape(shape): FILL_FUNC_BODY
50,523
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff/kubedifflib/_diff.py
41,42
33,52
to_text
Difference
42,52
42,52
class Difference(object): """An observed difference.""" def __init__(self, message, path, *args): self.message = message self.path = path self.args = args def to_text(self, kind=''): FILL_FUNC_BODY
class Difference(object): """An observed difference.""" def __init__(self, message, path, *args): self.message = message self.path = path self.args = args def to_text(self, kind=''): FILL_FUNC_BODY
if kind.startswith('Secret.') and len(self.args) == 2: message = self.message % (mask(self.args[0]), mask(self.args[1])) else: message = self.message % self.args if self.path is None: return message return '%s: %s' % (self.path, message)
if kind.startswith('Secret.') and len(self.args) == 2: message = self.message % (mask(self.args[0]), mask(self.args[1])) else: message = self.message % self.args if self.path is None: return message return '%s: %s' % (self.path, message)
30
75
106
181
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import sys import subprocess import os import operator import numbers import json import difflib import collections fro...
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import sys import subprocess import os import operator import numbers import json import difflib import collections fro...
50,524
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff/kubedifflib/_diff.py
250,251
243,257
diff
JSONPrinter
251,253
251,253
class JSONPrinter(object): def __init__(self): self.data = collections.defaultdict(list) def add(self, path, kube_obj): pass def diff(self, path, difference): FILL_FUNC_BODY def finish(self): print(json.dumps(self.data, sort_keys=True, indent=2, separators=(',', ': ')))
class JSONPrinter(object): def __init__(self): self.data = collections.defaultdict(list) def add(self, path, kube_obj): pass def diff(self, path, difference): FILL_FUNC_BODY def finish(self): print(json.dumps(self.data, sort_keys=True, indent=2, separators=(',', ': ')))
self.data[path].append(difference.to_text())
self.data[path].append(difference.to_text())
1
111
20
131
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import sys import subprocess import os import operator import numbers import json import difflib import collections fro...
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import sys import subprocess import os import operator import numbers import json import difflib import collections fro...
50,525
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff/kubedifflib/_diff.py
231,232
216,243
diff
QuietTextPrinter
232,239
232,239
class QuietTextPrinter(object): """Only output if there's a difference.""" def __init__(self, stream=None): self._stream = stream if stream else sys.stdout self._current = None def _write(self, msg, *args): self._stream.write(msg % args) self._stream.write('\n') sel...
class QuietTextPrinter(object): """Only output if there's a difference.""" def __init__(self, stream=None): self._stream = stream if stream else sys.stdout self._current = None def _write(self, msg, *args): self._stream.write(msg % args) self._stream.write('\n') sel...
if self._current: self._write('## %s (%s)', self._current.namespaced_name, self._current.kind) else: self._write('## UNKNOWN') self._write('') self._write('%s', difference.to_text(self._current.kind))
if self._current: self._write('## %s (%s)', self._current.namespaced_name, self._current.kind) else: self._write('## UNKNOWN') self._write('') self._write('%s', difference.to_text(self._current.kind))
13
158
89
247
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import sys import subprocess import os import operator import numbers import json import difflib import collections fro...
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import sys import subprocess import os import operator import numbers import json import difflib import collections fro...
50,526
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff/kubedifflib/_diff.py
209,210
205,216
diff
StdoutPrinter
210,212
210,212
class StdoutPrinter(object): def add(self, _, kube_obj): print("Checking %s '%s'" % (kube_obj.kind, kube_obj.namespaced_name)) def diff(self, _, difference): FILL_FUNC_BODY def finish(self): pass
class StdoutPrinter(object): def add(self, _, kube_obj): print("Checking %s '%s'" % (kube_obj.kind, kube_obj.namespaced_name)) def diff(self, _, difference): FILL_FUNC_BODY def finish(self): pass
print(" *** " + difference.to_text())
print(" *** " + difference.to_text())
5
87
16
103
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import sys import subprocess import os import operator import numbers import json import difflib import collections fro...
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import sys import subprocess import os import operator import numbers import json import difflib import collections fro...
50,527
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff/kubedifflib/_images.py
55,56
1,107
get_differing_images
65,89
56,89
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import os import attr from future.utils import viewitems from builtins import object from builtin...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import os import attr from future.utils import viewitems from builtins import object from builtin...
source_objs = frozenset(source_env) target_objs = frozenset(target_env) # XXX: What about missing objects? diffs = {} for obj in source_objs & target_objs: source_images = list(map(Image.parse, sorted(iter_images(source_env[obj])))) target_images = list(map(Image.parse, sorted(iter_i...
"""Return the images that differ between Kubernetes environments. :param Dict[KubeObject, Dict] source_env: The Kubernetes objects in the source environment. :param Dict[KubeObject, Dict] target_env: The Kubernetes objects in the target environment. :return: A dictionary mapping image n...
108
659
343
1,002
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import os import attr from future.utils import viewitems from builtins import object from builtin...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import os import attr from future.utils import viewitems from builtins import object from builtin...
50,528
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff/kubedifflib/_images.py
45,47
39,55
parse
Image
47,55
47,55
@attr.s class Image(object): """A Docker image name.""" name = attr.ib() label = attr.ib() @classmethod def parse(cls, image_name): FILL_FUNC_BODY
@attr.s class Image(object): """A Docker image name.""" name = attr.ib() label = attr.ib() @classmethod def parse(cls, image_name): FILL_FUNC_BODY
try: [name, label] = image_name.split(':', 1) except ValueError: name = image_name label = "latest" return cls(name, label)
try: [name, label] = image_name.split(':', 1) except ValueError: name = image_name label = "latest" return cls(name, label)
17
63
63
126
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import os import attr from future.utils import viewitems from builtins import object from builtin...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from ._kube import ( KubeObject, iter_files, ) import yaml import os import attr from future.utils import viewitems from builtins import object from builtin...
50,529
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff/kubedifflib/_kube.py
13,14
1,91
iter_files
21,31
14,31
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) import logging import yaml import subprocess import os import attr from builtins import object def iter_files(paths): FILL_FUNC_BODY@attr.s class KubeObject(object): """A Kubernete...
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) import logging import yaml import subprocess import os import attr from builtins import object def iter_files(paths): """Yield absolute paths to all the files in 'paths'. 'pat...
# XXX: Copied from service/monitoring/lint for path in paths: if os.path.isfile(path): yield path else: for root, _, filenames in os.walk(path): for filename in filenames: yield os.path.join(root, filename)
"""Yield absolute paths to all the files in 'paths'. 'paths' is expected to be an iterable of paths to files or directories. Paths to files are yielded as is, paths to directories are recursed into. Equivalent to ``find "$paths[@]" -type f``. """ # XXX: Copied from service/monitoring/lint ...
27
916
92
1,008
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) import logging import yaml import subprocess import os import attr from builtins import object def iter_files(paths): FILL_FUNC_BODY@attr.s class KubeObject(object): """A Kubernete...
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) import logging import yaml import subprocess import os import attr from builtins import object def iter_files(paths): """Yield absolute paths to all the files in 'paths'. 'pat...
50,530
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff
/home/hieuvd/dung_repo/raw/stars_03/weaveworks_kubediff/kubediff/kubedifflib/_kube.py
76,77
31,91
get_from_cluster
KubeObject
83,91
77,91
@attr.s class KubeObject(object): """A Kubernetes object.""" namespace = attr.ib() kind = attr.ib() name = attr.ib() data = attr.ib() @classmethod def from_dict(cls, data, namespace=""): """Construct a 'KubeObject' from a dictionary of Kubernetes data. :param dict data: Ku...
@attr.s class KubeObject(object): """A Kubernetes object.""" namespace = attr.ib() kind = attr.ib() name = attr.ib() data = attr.ib() @classmethod def from_dict(cls, data, namespace=""): """Construct a 'KubeObject' from a dictionary of Kubernetes data. :param dict data: Ku...
args = ["--namespace=%s" % self.namespace, "-o=yaml"] if kubeconfig is not None: args.append("--kubeconfig=%s" % kubeconfig) if context is not None: args.append("--context=%s" % context) running = subprocess.check_output(["kubectl", "get"] + args + [self.kind, se...
"""Fetch data for this object from a Kubernetes cluster. :param str kubeconfig: Path to a Kubernetes configuration file. If None, fetches data from the default cluster. :return: A dict of data for this Kubernetes object. """ args = ["--namespace=%s" % self.namespace,...
34
638
137
775
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) import logging import yaml import subprocess import os import attr from builtins import object def iter_files(paths): """Yield absolute paths to all the files in 'paths'. 'pat...
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) import logging import yaml import subprocess import os import attr from builtins import object def iter_files(paths): """Yield absolute paths to all the files in 'paths'. 'pat...
50,542
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/annotation.py
82,83
23,107
save_annotation
Annotation
83,107
83,107
class Annotation: def __init__(self, image_path, label_path): img_folder, img_name = os.path.split(image_path) self.description = 'ISAT' self.img_folder = img_folder self.img_name = img_name self.label_path = label_path self.note = '' image = np.array(Image.o...
class Annotation: def __init__(self, image_path, label_path): img_folder, img_name = os.path.split(image_path) self.description = 'ISAT' self.img_folder = img_folder self.img_name = img_name self.label_path = label_path self.note = '' image = np.array(Image.o...
dataset = {} dataset['info'] = {} dataset['info']['description'] = self.description dataset['info']['folder'] = self.img_folder dataset['info']['name'] = self.img_name dataset['info']['width'] = self.width dataset['info']['height'] = self.height dataset['i...
dataset = {} dataset['info'] = {} dataset['info']['description'] = self.description dataset['info']['folder'] = self.img_folder dataset['info']['name'] = self.img_name dataset['info']['width'] = self.width dataset['info']['height'] = self.height dataset['i...
72
708
281
989
# -*- coding: utf-8 -*- # @Author : LG import os from PIL import Image import numpy as np from json import load, dump from typing import List class Object: def __init__(self, category:str, group:int, segmentation, area, layer, bbox, iscrowd=0, note=''): self.category = category self.group = grou...
# -*- coding: utf-8 -*- # @Author : LG import os from PIL import Image import numpy as np from json import load, dump from typing import List class Object: def __init__(self, category:str, group:int, segmentation, area, layer, bbox, iscrowd=0, note=''): self.category = category self.group = grou...
50,543
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/configs.py
25,26
1,58
save_config
26,31
26,31
import yaml from enum import Enum import os ISAT_ROOT = os.path.split(os.path.abspath(__file__))[0] SOFTWARE_CONFIG_FILE = os.path.join(ISAT_ROOT, 'software.yaml') CONFIG_FILE = os.path.join(ISAT_ROOT, 'isat.yaml') CHECKPOINT_PATH = os.path.join(ISAT_ROOT, 'checkpoints') os.makedirs(os.path.join(CHECKPOINT_PATH, 'tmp...
import yaml from enum import Enum import os ISAT_ROOT = os.path.split(os.path.abspath(__file__))[0] SOFTWARE_CONFIG_FILE = os.path.join(ISAT_ROOT, 'software.yaml') CONFIG_FILE = os.path.join(ISAT_ROOT, 'isat.yaml') CHECKPOINT_PATH = os.path.join(ISAT_ROOT, 'checkpoints') os.makedirs(os.path.join(CHECKPOINT_PATH, 'tmp...
s = yaml.dump(cfg) with open(file, 'w') as f: f.write(s) return True
s = yaml.dump(cfg) with open(file, 'w') as f: f.write(s) return True
11
534
42
576
import yaml from enum import Enum import os ISAT_ROOT = os.path.split(os.path.abspath(__file__))[0] SOFTWARE_CONFIG_FILE = os.path.join(ISAT_ROOT, 'software.yaml') CONFIG_FILE = os.path.join(ISAT_ROOT, 'isat.yaml') CHECKPOINT_PATH = os.path.join(ISAT_ROOT, 'checkpoints') os.makedirs(os.path.join(CHECKPOINT_PATH, 'tmp...
import yaml from enum import Enum import os ISAT_ROOT = os.path.split(os.path.abspath(__file__))[0] SOFTWARE_CONFIG_FILE = os.path.join(ISAT_ROOT, 'software.yaml') CONFIG_FILE = os.path.join(ISAT_ROOT, 'isat.yaml') CHECKPOINT_PATH = os.path.join(ISAT_ROOT, 'checkpoints') os.makedirs(os.path.join(CHECKPOINT_PATH, 'tmp...
50,545
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/main.py
14,15
1,23
main
15,20
15,20
# -*- coding: utf-8 -*- # @Author : LG # import os from PyQt5 import QtWidgets from ISAT.widgets.mainwindow import MainWindow import sys # ubuntu18.04装其他应用时,环境崩了。。。qtapp初始化后,torch调用cuda会卡死,但先调用下cuda就不会卡死。 import torch torch.cuda.is_available() # (知道怎么处理该问题,请反馈下 T.T) def main(): FILL_FUNC_BODYif __name__ == '__main_...
# -*- coding: utf-8 -*- # @Author : LG # import os from PyQt5 import QtWidgets from ISAT.widgets.mainwindow import MainWindow import sys # ubuntu18.04装其他应用时,环境崩了。。。qtapp初始化后,torch调用cuda会卡死,但先调用下cuda就不会卡死。 import torch torch.cuda.is_available() # (知道怎么处理该问题,请反馈下 T.T) def main(): FILL_FUNC_BODYif __name__ == '__main_...
app = QtWidgets.QApplication(['']) mainwindow = MainWindow() mainwindow.show() sys.exit(app.exec_())
app = QtWidgets.QApplication(['']) mainwindow = MainWindow() mainwindow.show() sys.exit(app.exec_())
8
164
44
208
# -*- coding: utf-8 -*- # @Author : LG # import os from PyQt5 import QtWidgets from ISAT.widgets.mainwindow import MainWindow import sys # ubuntu18.04装其他应用时,环境崩了。。。qtapp初始化后,torch调用cuda会卡死,但先调用下cuda就不会卡死。 import torch torch.cuda.is_available() # (知道怎么处理该问题,请反馈下 T.T) def main(): FILL_FUNC_BODYif __name__ == '__main_...
# -*- coding: utf-8 -*- # @Author : LG # import os from PyQt5 import QtWidgets from ISAT.widgets.mainwindow import MainWindow import sys # ubuntu18.04装其他应用时,环境崩了。。。qtapp初始化后,torch调用cuda会卡死,但先调用下cuda就不会卡死。 import torch torch.cuda.is_available() # (知道怎么处理该问题,请反馈下 T.T) def main(): FILL_FUNC_BODYif __name__ == '__main_...
50,547
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/scripts/labelme.py
51,52
10,124
_save_one_labelme_json
LABELME
52,88
52,88
class LABELME(ISAT): def __init__(self): self.keep_crowd = True def read_from_LABELME(self, json_root): self.annos.clear() self.cates = () json_files = [file for file in os.listdir(json_root) if file.endswith('.json')] pbar = tqdm.tqdm(json_files) for file in p...
class LABELME(ISAT): def __init__(self): self.keep_crowd = True def read_from_LABELME(self, json_root): self.annos.clear() self.cates = () json_files = [file for file in os.listdir(json_root) if file.endswith('.json')] pbar = tqdm.tqdm(json_files) for file in p...
labelme_anno = {} labelme_anno['version'] = "5.2.0.post4 | ISAT to LabelMe" labelme_anno['imagePath'] = anno.info.name labelme_anno['imageData'] = None labelme_anno['imageHeight'] = anno.info.height labelme_anno['imageWidth'] = anno.info.width labelme_anno['flags'...
labelme_anno = {} labelme_anno['version'] = "5.2.0.post4 | ISAT to LabelMe" labelme_anno['imagePath'] = anno.info.name labelme_anno['imageData'] = None labelme_anno['imageHeight'] = anno.info.height labelme_anno['imageWidth'] = anno.info.width labelme_anno['flags'...
98
940
386
1,326
# -*- coding: utf-8 -*- # @Author : LG from ISAT.scripts.isat import ISAT from json import dump, load import tqdm import os class LABELME(ISAT): def __init__(self): self.keep_crowd = True def read_from_LABELME(self, json_root): self.annos.clear() self.cates = () json_files ...
# -*- coding: utf-8 -*- # @Author : LG from ISAT.scripts.isat import ISAT from json import dump, load import tqdm import os class LABELME(ISAT): def __init__(self): self.keep_crowd = True def read_from_LABELME(self, json_root): self.annos.clear() self.cates = () json_files ...
50,548
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/scripts/voc.py
39,40
13,87
_save_one_voc_png
VOC
40,81
40,81
class VOC(ISAT): def __init__(self): self.keep_crowd = True self.is_instance = False def save_to_voc(self, png_root): os.makedirs(png_root, exist_ok=True) # cmap cmap = imgviz.label_colormap() category_index_dict = {} with open(os.path.join(png_root, 'c...
class VOC(ISAT): def __init__(self): self.keep_crowd = True self.is_instance = False def save_to_voc(self, png_root): os.makedirs(png_root, exist_ok=True) # cmap cmap = imgviz.label_colormap() category_index_dict = {} with open(os.path.join(png_root, 'c...
info = anno.info objects = anno.objs img_name = info.name width = info.width height = info.height depth = info.depth note = info.note img = np.zeros(shape=(height, width), dtype=np.uint8) objects = sorted(objects, key=lambda obj:obj.layer) ...
info = anno.info objects = anno.objs img_name = info.name width = info.width height = info.height depth = info.depth note = info.note img = np.zeros(shape=(height, width), dtype=np.uint8) objects = sorted(objects, key=lambda obj:obj.layer) ...
143
433
480
913
# -*- coding: utf-8 -*- # @Author : LG from ISAT.scripts.isat import ISAT import tqdm import numpy as np from PIL import Image import imgviz from skimage.draw.draw import polygon import os class VOC(ISAT): def __init__(self): self.keep_crowd = True self.is_instance = False def save_to_voc(...
# -*- coding: utf-8 -*- # @Author : LG from ISAT.scripts.isat import ISAT import tqdm import numpy as np from PIL import Image import imgviz from skimage.draw.draw import polygon import os class VOC(ISAT): def __init__(self): self.keep_crowd = True self.is_instance = False def save_to_voc(...
50,549
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/scripts/voc_detection.py
27,28
10,121
_save_one_voc_xml
VOCDetect
28,121
28,121
class VOCDetect(ISAT): def __init__(self): self.keep_crowd = True def save_to_XML(self, xml_root): os.makedirs(xml_root, exist_ok=True) pbar = tqdm.tqdm(self.annos.items()) for name_without_suffix, anno in pbar: xml_path = os.path.join(xml_root, name_without_suffix ...
class VOCDetect(ISAT): def __init__(self): self.keep_crowd = True def save_to_XML(self, xml_root): os.makedirs(xml_root, exist_ok=True) pbar = tqdm.tqdm(self.annos.items()) for name_without_suffix, anno in pbar: xml_path = os.path.join(xml_root, name_without_suffix ...
annotation = ET.Element('annotation') tree = ET.ElementTree(annotation) folder = ET.Element('folder') folder.text = '{}'.format(anno.info.folder) annotation.append(folder) filename = ET.Element('filename') filename.text = '{}'.format(anno.info.name) annot...
annotation = ET.Element('annotation') tree = ET.ElementTree(annotation) folder = ET.Element('folder') folder.text = '{}'.format(anno.info.folder) annotation.append(folder) filename = ET.Element('filename') filename.text = '{}'.format(anno.info.name) annot...
222
239
995
1,234
# -*- coding: utf-8 -*- # @Author : LG from ISAT.scripts.isat import ISAT from xml.etree import ElementTree as ET import tqdm import os class VOCDetect(ISAT): def __init__(self): self.keep_crowd = True def save_to_XML(self, xml_root): os.makedirs(xml_root, exist_ok=True) pbar = tqd...
# -*- coding: utf-8 -*- # @Author : LG from ISAT.scripts.isat import ISAT from xml.etree import ElementTree as ET import tqdm import os class VOCDetect(ISAT): def __init__(self): self.keep_crowd = True def save_to_XML(self, xml_root): os.makedirs(xml_root, exist_ok=True) pbar = tqd...
50,552
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/build_sam.py
20,21
1,125
build_sam_vit_h
21,30
21,30
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
image_encoder = _build_sam_encoder( encoder_embed_dim=1280, encoder_depth=32, encoder_num_heads=16, encoder_global_attn_indexes=[7, 15, 23, 31] ) return _build_sam(image_encoder, checkpoint)
image_encoder = _build_sam_encoder( encoder_embed_dim=1280, encoder_depth=32, encoder_num_heads=16, encoder_global_attn_indexes=[7, 15, 23, 31] ) return _build_sam(image_encoder, checkpoint)
14
1,188
106
1,294
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
50,553
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/common.py
67,74
1,119
resize
74,88
74,88
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Type class MLPBlock(nn.Module): ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Type class MLPBlock(nn.Module): ...
if mode in ["bilinear", "bicubic"]: return F.interpolate( x, size=size, scale_factor=scale_factor, mode=mode, align_corners=align_corners, ) elif mode in ["nearest", "area"]: return F.interpolate(x, size=size, scale_factor=scale...
if mode in ["bilinear", "bicubic"]: return F.interpolate( x, size=size, scale_factor=scale_factor, mode=mode, align_corners=align_corners, ) elif mode in ["nearest", "area"]: return F.interpolate(x, size=size, scale_factor=scale...
28
1,190
149
1,339
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Type class MLPBlock(nn.Module): ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Type class MLPBlock(nn.Module): ...
50,554
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/common.py
39,40
32,47
forward
LayerNorm2d
40,47
40,47
class LayerNorm2d(nn.Module): def __init__(self, num_channels: int, eps: float = 1e-6) -> None: super().__init__() self.weight = nn.Parameter(torch.ones(num_channels)) self.bias = nn.Parameter(torch.zeros(num_channels)) self.eps = eps def forward(self, x: torch.Tensor) -> torch....
class LayerNorm2d(nn.Module): def __init__(self, num_channels: int, eps: float = 1e-6) -> None: super().__init__() self.weight = nn.Parameter(torch.ones(num_channels)) self.bias = nn.Parameter(torch.zeros(num_channels)) self.eps = eps def forward(self, x: torch.Tensor) -> torch....
u = x.mean(1, keepdim=True) s = (x - u).pow(2).mean(1, keepdim=True) x = (x - u) / torch.sqrt(s + self.eps) x = self.weight[:, None, None] * x + self.bias[:, None, None] return x
u = x.mean(1, keepdim=True) s = (x - u).pow(2).mean(1, keepdim=True) x = (x - u) / torch.sqrt(s + self.eps) x = self.weight[:, None, None] * x + self.bias[:, None, None] return x
32
135
97
232
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Type class MLPBlock(nn.Module): ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Type class MLPBlock(nn.Module): ...
50,555
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/common.py
26,27
14,32
forward
MLPBlock
27,32
27,32
class MLPBlock(nn.Module): def __init__( self, embedding_dim: int, mlp_dim: int, act: Type[nn.Module] = nn.GELU, ) -> None: super().__init__() self.lin1 = nn.Linear(embedding_dim, mlp_dim) self.lin2 = nn.Linear(mlp_dim, embedding_dim) self.act = ac...
class MLPBlock(nn.Module): def __init__( self, embedding_dim: int, mlp_dim: int, act: Type[nn.Module] = nn.GELU, ) -> None: super().__init__() self.lin1 = nn.Linear(embedding_dim, mlp_dim) self.lin2 = nn.Linear(mlp_dim, embedding_dim) self.act = ac...
return self.lin2(self.act(self.lin1(x))) # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
return self.lin2(self.act(self.lin1(x))) # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
13
155
138
293
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Type class MLPBlock(nn.Module): ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Type class MLPBlock(nn.Module): ...
50,556
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/common.py
115,116
106,119
forward
OpSequential
116,119
116,119
class OpSequential(nn.Module): def __init__(self, op_list): super(OpSequential, self).__init__() valid_op_list = [] for op in op_list: if op is not None: valid_op_list.append(op) self.op_list = nn.ModuleList(valid_op_list) def forward(self, x: torch.T...
class OpSequential(nn.Module): def __init__(self, op_list): super(OpSequential, self).__init__() valid_op_list = [] for op in op_list: if op is not None: valid_op_list.append(op) self.op_list = nn.ModuleList(valid_op_list) def forward(self, x: torch.T...
for op in self.op_list: x = op(x) return x
for op in self.op_list: x = op(x) return x
9
130
25
155
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Type class MLPBlock(nn.Module): ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Type class MLPBlock(nn.Module): ...
50,557
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/common.py
102,103
88,106
forward
UpSampleLayer
103,106
103,106
class UpSampleLayer(nn.Module): def __init__( self, mode="bicubic", size=None, factor=2, align_corners=False, ): super(UpSampleLayer, self).__init__() self.mode = mode self.size = val2list(size, 2) if size is not None else None ...
class UpSampleLayer(nn.Module): def __init__( self, mode="bicubic", size=None, factor=2, align_corners=False, ): super(UpSampleLayer, self).__init__() self.mode = mode self.size = val2list(size, 2) if size is not None else None ...
return resize(x, self.size, self.factor, self.mode, self.align_corners)
return resize(x, self.size, self.factor, self.mode, self.align_corners)
6
161
31
192
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Type class MLPBlock(nn.Module): ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Type class MLPBlock(nn.Module): ...
50,559
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/image_encoder.py
224,225
185,243
forward
Attention
225,243
225,243
class Attention(nn.Module): """Multi-head Attention block with relative position embeddings.""" def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = True, use_rel_pos: bool = False, rel_pos_zero_init: bool = True, input_size: Optional[Tuple[...
class Attention(nn.Module): """Multi-head Attention block with relative position embeddings.""" def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = True, use_rel_pos: bool = False, rel_pos_zero_init: bool = True, input_size: Optional[Tuple[...
B, H, W, _ = x.shape # qkv with shape (3, B, nHead, H * W, C) qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # q, k, v with shape (B * nHead, H * W, C) q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) attn = (q * self.s...
B, H, W, _ = x.shape # qkv with shape (3, B, nHead, H * W, C) qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # q, k, v with shape (B * nHead, H * W, C) q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) attn = (q * self.s...
99
516
341
857
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
50,560
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/image_encoder.py
166,167
119,185
forward
Block
167,185
167,185
class Block(nn.Module): """Transformer blocks with support of window attention and residual propagation blocks""" def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = True, norm_layer: Type[nn.Module] = nn.LayerNorm, act_...
class Block(nn.Module): """Transformer blocks with support of window attention and residual propagation blocks""" def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = True, norm_layer: Type[nn.Module] = nn.LayerNorm, act_...
shortcut = x x = self.norm1(x) # Window partition if self.window_size > 0: H, W = x.shape[1], x.shape[2] x, pad_hw = window_partition(x, self.window_size) x = self.attn(x) # Reverse window partition if self.window_size > 0: x =...
shortcut = x x = self.norm1(x) # Window partition if self.window_size > 0: H, W = x.shape[1], x.shape[2] x, pad_hw = window_partition(x, self.window_size) x = self.attn(x) # Reverse window partition if self.window_size > 0: x =...
53
615
178
793
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
50,561
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/image_encoder.py
106,107
17,119
forward
ImageEncoderViT
107,119
107,119
class ImageEncoderViT(nn.Module): def __init__( self, img_size: int = 1024, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 4.0, out_chans: int = 256, qkv_bias: boo...
class ImageEncoderViT(nn.Module): def __init__( self, img_size: int = 1024, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 4.0, out_chans: int = 256, qkv_bias: boo...
x = self.patch_embed(x) if self.pos_embed is not None: x = x + self.pos_embed for blk in self.blocks: x = blk(x) x = self.neck(x.permute(0, 3, 1, 2)) return x
x = self.patch_embed(x) if self.pos_embed is not None: x = x + self.pos_embed for blk in self.blocks: x = blk(x) x = self.neck(x.permute(0, 3, 1, 2)) return x
28
1,041
101
1,142
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
50,562
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/image_encoder.py
391,392
364,396
forward
PatchEmbed
392,396
392,396
class PatchEmbed(nn.Module): """ Image to Patch Embedding. """ def __init__( self, kernel_size: Tuple[int, int] = (16, 16), stride: Tuple[int, int] = (16, 16), padding: Tuple[int, int] = (0, 0), in_chans: int = 3, embed_dim: int = 768, ) -> None: ...
class PatchEmbed(nn.Module): """ Image to Patch Embedding. """ def __init__( self, kernel_size: Tuple[int, int] = (16, 16), stride: Tuple[int, int] = (16, 16), padding: Tuple[int, int] = (0, 0), in_chans: int = 3, embed_dim: int = 768, ) -> None: ...
x = self.proj(x) # B C H W -> B H W C x = x.permute(0, 2, 3, 1) return x
x = self.proj(x) # B C H W -> B H W C x = x.permute(0, 2, 3, 1) return x
21
301
52
353
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
50,563
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/mask_decoder.py
176,177
159,182
forward
MLP
177,182
177,182
class MLP(nn.Module): def __init__( self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False, ) -> None: super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) ...
class MLP(nn.Module): def __init__( self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False, ) -> None: super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) ...
for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) if self.sigmoid_output: x = F.sigmoid(x) return x
for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) if self.sigmoid_output: x = F.sigmoid(x) return x
23
189
75
264
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from torch.nn import functional as F from typing import List, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from torch.nn import functional as F from typing import List, Tuple, Type from .common...
50,564
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/mask_decoder.py
71,79
16,159
forward
MaskDecoder
94,117
79,117
class MaskDecoder(nn.Module): def __init__( self, *, transformer_dim: int, transformer: nn.Module, num_multimask_outputs: int = 3, activation: Type[nn.Module] = nn.GELU, iou_head_depth: int = 3, iou_head_hidden_dim: int = 256, ) -> None: ""...
class MaskDecoder(nn.Module): def __init__( self, *, transformer_dim: int, transformer: nn.Module, num_multimask_outputs: int = 3, activation: Type[nn.Module] = nn.GELU, iou_head_depth: int = 3, iou_head_hidden_dim: int = 256, ) -> None: ""...
masks, iou_pred = self.predict_masks( image_embeddings=image_embeddings, image_pe=image_pe, sparse_prompt_embeddings=sparse_prompt_embeddings, dense_prompt_embeddings=dense_prompt_embeddings, ) # Select the correct mask or masks for output ...
""" Predict masks given image and prompt embeddings. Arguments: image_embeddings (torch.Tensor): the embeddings from the image encoder image_pe (torch.Tensor): positional encoding with the shape of image_embeddings sparse_prompt_embeddings (torch.Tensor): the embed...
61
1,610
257
1,867
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from torch.nn import functional as F from typing import List, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from torch.nn import functional as F from typing import List, Tuple, Type from .common...
50,565
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/prompt_encoder.py
196,197
182,227
_pe_encoding
PositionEmbeddingRandom
198,206
197,206
class PositionEmbeddingRandom(nn.Module): """ Positional encoding using random spatial frequencies. """ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: super().__init__() if scale is None or scale <= 0.0: scale = 1.0 self.register_...
class PositionEmbeddingRandom(nn.Module): """ Positional encoding using random spatial frequencies. """ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: super().__init__() if scale is None or scale <= 0.0: scale = 1.0 self.register_...
# assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape coords = 2 * coords - 1 coords = coords.to(self.positional_encoding_gaussian_matrix.dtype) coords = coords @ self.positional_encoding_gaussian_matrix coords = 2 * np.pi * coords # outputs d_1 x .....
"""Positionally encode points that are normalized to [0,1].""" # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape coords = 2 * coords - 1 coords = coords.to(self.positional_encoding_gaussian_matrix.dtype) coords = coords @ self.positional_encoding_gaussia...
54
558
156
714
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from torch import nn from typing import Any, Optional, Tuple, Type from .common import L...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from torch import nn from typing import Any, Optional, Tuple, Type from .common import L...
50,568
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/rep_vit.py
273,275
264,290
fuse
BN_Linear
275,290
275,290
class BN_Linear(torch.nn.Sequential): def __init__(self, a, b, bias=True, std=0.02): super().__init__() self.add_module('bn', torch.nn.BatchNorm1d(a)) self.add_module('l', torch.nn.Linear(a, b, bias=bias)) trunc_normal_(self.l.weight, std=std) if bias: torch.nn.in...
class BN_Linear(torch.nn.Sequential): def __init__(self, a, b, bias=True, std=0.02): super().__init__() self.add_module('bn', torch.nn.BatchNorm1d(a)) self.add_module('l', torch.nn.Linear(a, b, bias=bias)) trunc_normal_(self.l.weight, std=std) if bias: torch.nn.in...
bn, l = self._modules.values() w = bn.weight / (bn.running_var + bn.eps) ** 0.5 b = bn.bias - self.bn.running_mean * \ self.bn.weight / (bn.running_var + bn.eps) ** 0.5 w = l.weight * w[None, :] if l.bias is None: b = b @ self.l.weight.T else: ...
bn, l = self._modules.values() w = bn.weight / (bn.running_var + bn.eps) ** 0.5 b = bn.bias - self.bn.running_mean * \ self.bn.weight / (bn.running_var + bn.eps) ** 0.5 w = l.weight * w[None, :] if l.bias is None: b = b @ self.l.weight.T else: ...
60
165
227
392
import torch.nn as nn from .common import LayerNorm2d, UpSampleLayer, OpSequential __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT'] m1_cfgs = [ # k, t, c, SE, HS, s [3, 2, 48, 1, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 96, 0, 0, 2], [3, 2, 96, 1, 0, 1], [3, 2,...
import torch.nn as nn from .common import LayerNorm2d, UpSampleLayer, OpSequential __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT'] m1_cfgs = [ # k, t, c, SE, HS, s [3, 2, 48, 1, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 96, 0, 0, 2], [3, 2, 96, 1, 0, 1], [3, 2,...
50,569
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/rep_vit.py
138,140
128,154
fuse
Conv2d_BN
140,154
140,154
class Conv2d_BN(torch.nn.Sequential): def __init__(self, a, b, ks=1, stride=1, pad=0, dilation=1, groups=1, bn_weight_init=1, resolution=-10000): super().__init__() self.add_module('c', torch.nn.Conv2d( a, b, ks, stride, pad, dilation, groups, bias=False)) self.a...
class Conv2d_BN(torch.nn.Sequential): def __init__(self, a, b, ks=1, stride=1, pad=0, dilation=1, groups=1, bn_weight_init=1, resolution=-10000): super().__init__() self.add_module('c', torch.nn.Conv2d( a, b, ks, stride, pad, dilation, groups, bias=False)) self.a...
c, bn = self._modules.values() w = bn.weight / (bn.running_var + bn.eps) ** 0.5 w = c.weight * w[:, None, None, None] b = bn.bias - bn.running_mean * bn.weight / \ (bn.running_var + bn.eps) ** 0.5 m = torch.nn.Conv2d(w.size(1) * self.c.groups, w.size( 0), ...
c, bn = self._modules.values() w = bn.weight / (bn.running_var + bn.eps) ** 0.5 w = c.weight * w[:, None, None, None] b = bn.bias - bn.running_mean * bn.weight / \ (bn.running_var + bn.eps) ** 0.5 m = torch.nn.Conv2d(w.size(1) * self.c.groups, w.size( 0), ...
52
219
233
452
import torch.nn as nn from .common import LayerNorm2d, UpSampleLayer, OpSequential __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT'] m1_cfgs = [ # k, t, c, SE, HS, s [3, 2, 48, 1, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 96, 0, 0, 2], [3, 2, 96, 1, 0, 1], [3, 2,...
import torch.nn as nn from .common import LayerNorm2d, UpSampleLayer, OpSequential __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT'] m1_cfgs = [ # k, t, c, SE, HS, s [3, 2, 48, 1, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 96, 0, 0, 2], [3, 2, 96, 1, 0, 1], [3, 2,...
50,570
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/rep_vit.py
197,199
187,220
fuse
RepVGGDW
199,220
199,220
class RepVGGDW(torch.nn.Module): def __init__(self, ed) -> None: super().__init__() self.conv = Conv2d_BN(ed, ed, 3, 1, 1, groups=ed) self.conv1 = Conv2d_BN(ed, ed, 1, 1, 0, groups=ed) self.dim = ed def forward(self, x): return self.conv(x) + self.conv1(x) + x @torc...
class RepVGGDW(torch.nn.Module): def __init__(self, ed) -> None: super().__init__() self.conv = Conv2d_BN(ed, ed, 3, 1, 1, groups=ed) self.conv1 = Conv2d_BN(ed, ed, 1, 1, 0, groups=ed) self.dim = ed def forward(self, x): return self.conv(x) + self.conv1(x) + x @torc...
conv = self.conv.fuse() conv1 = self.conv1.fuse() conv_w = conv.weight conv_b = conv.bias conv1_w = conv1.weight conv1_b = conv1.bias conv1_w = torch.nn.functional.pad(conv1_w, [1, 1, 1, 1]) identity = torch.nn.functional.pad(torch.ones(conv1_w.shape[0]...
conv = self.conv.fuse() conv1 = self.conv1.fuse() conv_w = conv.weight conv_b = conv.bias conv1_w = conv1.weight conv1_b = conv1.bias conv1_w = torch.nn.functional.pad(conv1_w, [1, 1, 1, 1]) identity = torch.nn.functional.pad(torch.ones(conv1_w.shape[0]...
52
161
266
427
import torch.nn as nn from .common import LayerNorm2d, UpSampleLayer, OpSequential __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT'] m1_cfgs = [ # k, t, c, SE, HS, s [3, 2, 48, 1, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 96, 0, 0, 2], [3, 2, 96, 1, 0, 1], [3, 2,...
import torch.nn as nn from .common import LayerNorm2d, UpSampleLayer, OpSequential __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT'] m1_cfgs = [ # k, t, c, SE, HS, s [3, 2, 48, 1, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 96, 0, 0, 2], [3, 2, 96, 1, 0, 1], [3, 2,...
50,571
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/rep_vit.py
339,340
290,358
forward
RepViT
340,358
340,358
class RepViT(nn.Module): arch_settings = { 'm1': m1_cfgs, 'm2': m2_cfgs, 'm3': m3_cfgs } def __init__(self, arch, img_size=1024, upsample_mode='bicubic'): super(RepViT, self).__init__() # setting of inverted residual blocks self.cfgs = self.arch_settings[arch...
class RepViT(nn.Module): arch_settings = { 'm1': m1_cfgs, 'm2': m2_cfgs, 'm3': m3_cfgs } def __init__(self, arch, img_size=1024, upsample_mode='bicubic'): super(RepViT, self).__init__() # setting of inverted residual blocks self.cfgs = self.arch_settings[arch...
counter = 0 output_dict = dict() # patch_embed x = self.features[0](x) output_dict['stem'] = x # stages for idx, f in enumerate(self.features[1:]): x = f(x) if idx in self.stage_idx: output_dict[f'stage{counter}'] = x ...
counter = 0 output_dict = dict() # patch_embed x = self.features[0](x) output_dict['stem'] = x # stages for idx, f in enumerate(self.features[1:]): x = f(x) if idx in self.stage_idx: output_dict[f'stage{counter}'] = x ...
44
760
174
934
import torch.nn as nn from .common import LayerNorm2d, UpSampleLayer, OpSequential __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT'] m1_cfgs = [ # k, t, c, SE, HS, s [3, 2, 48, 1, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 96, 0, 0, 2], [3, 2, 96, 1, 0, 1], [3, 2,...
import torch.nn as nn from .common import LayerNorm2d, UpSampleLayer, OpSequential __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT'] m1_cfgs = [ # k, t, c, SE, HS, s [3, 2, 48, 1, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 96, 0, 0, 2], [3, 2, 96, 1, 0, 1], [3, 2,...
50,572
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/rep_vit.py
257,258
220,261
forward
RepViTBlock
258,261
258,261
class RepViTBlock(nn.Module): def __init__(self, inp, hidden_dim, oup, kernel_size, stride, use_se, use_hs, skip_downsample=False): super(RepViTBlock, self).__init__() assert stride in [1, 2] self.identity = stride == 1 and inp == oup assert (hidden_dim == 2 * inp) if strid...
class RepViTBlock(nn.Module): def __init__(self, inp, hidden_dim, oup, kernel_size, stride, use_se, use_hs, skip_downsample=False): super(RepViTBlock, self).__init__() assert stride in [1, 2] self.identity = stride == 1 and inp == oup assert (hidden_dim == 2 * inp) if strid...
return self.channel_mixer(self.token_mixer(x))
return self.channel_mixer(self.token_mixer(x))
2
568
24
592
import torch.nn as nn from .common import LayerNorm2d, UpSampleLayer, OpSequential __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT'] m1_cfgs = [ # k, t, c, SE, HS, s [3, 2, 48, 1, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 96, 0, 0, 2], [3, 2, 96, 1, 0, 1], [3, 2,...
import torch.nn as nn from .common import LayerNorm2d, UpSampleLayer, OpSequential __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT'] m1_cfgs = [ # k, t, c, SE, HS, s [3, 2, 48, 1, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 96, 0, 0, 2], [3, 2, 96, 1, 0, 1], [3, 2,...
50,573
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/rep_vit.py
167,169
154,187
fuse
Residual
169,187
169,187
class Residual(torch.nn.Module): def __init__(self, m, drop=0.): super().__init__() self.m = m self.drop = drop def forward(self, x): if self.training and self.drop > 0: return x + self.m(x) * torch.rand(x.size(0), 1, 1, 1, ...
class Residual(torch.nn.Module): def __init__(self, m, drop=0.): super().__init__() self.m = m self.drop = drop def forward(self, x): if self.training and self.drop > 0: return x + self.m(x) * torch.rand(x.size(0), 1, 1, 1, ...
if isinstance(self.m, Conv2d_BN): m = self.m.fuse() assert (m.groups == m.in_channels) identity = torch.ones(m.weight.shape[0], m.weight.shape[1], 1, 1) identity = torch.nn.functional.pad(identity, [1, 1, 1, 1]) m.weight += identity.to(m.weight.device)...
if isinstance(self.m, Conv2d_BN): m = self.m.fuse() assert (m.groups == m.in_channels) identity = torch.ones(m.weight.shape[0], m.weight.shape[1], 1, 1) identity = torch.nn.functional.pad(identity, [1, 1, 1, 1]) m.weight += identity.to(m.weight.device)...
59
173
272
445
import torch.nn as nn from .common import LayerNorm2d, UpSampleLayer, OpSequential __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT'] m1_cfgs = [ # k, t, c, SE, HS, s [3, 2, 48, 1, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 96, 0, 0, 2], [3, 2, 96, 1, 0, 1], [3, 2,...
import torch.nn as nn from .common import LayerNorm2d, UpSampleLayer, OpSequential __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT'] m1_cfgs = [ # k, t, c, SE, HS, s [3, 2, 48, 1, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 48, 0, 0, 1], [3, 2, 96, 0, 0, 2], [3, 2, 96, 1, 0, 1], [3, 2,...
50,574
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/transformer.py
208,209
185,241
_separate_heads
Attention
209,213
209,213
class Attention(nn.Module): """ An attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and values. """ def __init__( self, embedding_dim: int, num_heads: int, downsample_rate: int = 1, ) -> None: super(...
class Attention(nn.Module): """ An attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and values. """ def __init__( self, embedding_dim: int, num_heads: int, downsample_rate: int = 1, ) -> None: super(...
b, n, c = x.shape x = x.reshape(b, n, num_heads, c // num_heads) return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
b, n, c = x.shape x = x.reshape(b, n, num_heads, c // num_heads) return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
24
684
73
757
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
50,575
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/transformer.py
151,154
109,185
forward
TwoWayAttentionBlock
154,185
154,185
class TwoWayAttentionBlock(nn.Module): def __init__( self, embedding_dim: int, num_heads: int, mlp_dim: int = 2048, activation: Type[nn.Module] = nn.ReLU, attention_downsample_rate: int = 2, skip_first_layer_pe: bool = False, ) -> None: """ ...
class TwoWayAttentionBlock(nn.Module): def __init__( self, embedding_dim: int, num_heads: int, mlp_dim: int = 2048, activation: Type[nn.Module] = nn.ReLU, attention_downsample_rate: int = 2, skip_first_layer_pe: bool = False, ) -> None: """ ...
# Self attention block if self.skip_first_layer_pe: queries = self.self_attn(q=queries, k=queries, v=queries) else: q = queries + query_pe attn_out = self.self_attn(q=q, k=q, v=queries) queries = queries + attn_out queries = self.norm1(quer...
# Self attention block if self.skip_first_layer_pe: queries = self.self_attn(q=queries, k=queries, v=queries) else: q = queries + query_pe attn_out = self.self_attn(q=q, k=q, v=queries) queries = queries + attn_out queries = self.norm1(quer...
111
552
361
913
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
50,576
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/modeling/transformer.py
62,68
16,109
forward
TwoWayTransformer
81,109
68,109
class TwoWayTransformer(nn.Module): def __init__( self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Module] = nn.ReLU, attention_downsample_rate: int = 2, ) -> None: """ A transformer decoder that atten...
class TwoWayTransformer(nn.Module): def __init__( self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Module] = nn.ReLU, attention_downsample_rate: int = 2, ) -> None: """ A transformer decoder that atten...
# BxCxHxW -> BxHWxC == B x N_image_tokens x C bs, c, h, w = image_embedding.shape image_embedding = image_embedding.flatten(2).permute(0, 2, 1) image_pe = image_pe.flatten(2).permute(0, 2, 1) # Prepare queries queries = point_embedding keys = image_embedding ...
""" Args: image_embedding (torch.Tensor): image to attend to. Should be shape B x embedding_dim x h x w for any h and w. image_pe (torch.Tensor): the positional encoding to add to the image. Must have the same shape as image_embedding. point_embeddin...
93
675
320
995
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
50,578
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/utils/coreml.py
42,49
7,65
forward
SamCoreMLModel
49,65
49,65
class SamCoreMLModel(nn.Module): """ This model should not be called directly, but is used in CoreML export. """ def __init__( self, model: Sam, use_stability_score: bool = False ) -> None: super().__init__() self.mask_decoder = model.mask_decoder sel...
class SamCoreMLModel(nn.Module): """ This model should not be called directly, but is used in CoreML export. """ def __init__( self, model: Sam, use_stability_score: bool = False ) -> None: super().__init__() self.mask_decoder = model.mask_decoder sel...
sparse_embedding = self._embed_points(point_coords, point_labels) dense_embedding = self.model.prompt_encoder.no_mask_embed.weight.reshape(1, -1, 1, 1) masks, scores = self.model.mask_decoder.predict_masks( image_embeddings=image_embeddings, image_pe=self.model.prompt_en...
sparse_embedding = self._embed_points(point_coords, point_labels) dense_embedding = self.model.prompt_encoder.no_mask_embed.weight.reshape(1, -1, 1, 1) masks, scores = self.model.mask_decoder.predict_masks( image_embeddings=image_embeddings, image_pe=self.model.prompt_en...
31
492
226
718
import torch import torch.nn as nn from ..modeling import Sam from .amg import calculate_stability_score class SamCoreMLModel(nn.Module): """ This model should not be called directly, but is used in CoreML export. """ def __init__( self, model: Sam, use_stability_score: bool =...
import torch import torch.nn as nn from ..modeling import Sam from .amg import calculate_stability_score class SamCoreMLModel(nn.Module): """ This model should not be called directly, but is used in CoreML export. """ def __init__( self, model: Sam, use_stability_score: bool =...
50,579
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/edge_sam/utils/transforms.py
93,95
16,103
get_preprocess_shape
ResizeLongestSide
98,103
95,103
class ResizeLongestSide: """ Resizes images to the longest side 'target_length', as well as provides methods for resizing coordinates and boxes. Provides methods for transforming both numpy array and batched torch tensors. """ def __init__(self, target_length: int) -> None: self.target_...
class ResizeLongestSide: """ Resizes images to the longest side 'target_length', as well as provides methods for resizing coordinates and boxes. Provides methods for transforming both numpy array and batched torch tensors. """ def __init__(self, target_length: int) -> None: self.target_...
scale = long_side_length * 1.0 / max(oldh, oldw) newh, neww = oldh * scale, oldw * scale neww = int(neww + 0.5) newh = int(newh + 0.5) return (newh, neww)
""" Compute the output size given input size and target long side length. """ scale = long_side_length * 1.0 / max(oldh, oldw) newh, neww = oldh * scale, oldw * scale neww = int(neww + 0.5) newh = int(newh + 0.5) return (newh, neww)
30
1,123
83
1,206
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from torch.nn import functional as F from torchvision.transforms.functional import resize,...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from torch.nn import functional as F from torchvision.transforms.functional import resize,...
50,581
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/build_sam.py
47,48
1,160
build_sam_vit_t
48,96
48,96
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
prompt_embed_dim = 256 image_size = 1024 vit_patch_size = 16 image_embedding_size = image_size // vit_patch_size mobile_sam = Sam( image_encoder=TinyViT(img_size=1024, in_chans=3, num_classes=1000, embed_dims=[64, 128, 160, 320], depths=[2, 2, 6, 2], ...
prompt_embed_dim = 256 image_size = 1024 vit_patch_size = 16 image_embedding_size = image_size // vit_patch_size mobile_sam = Sam( image_encoder=TinyViT(img_size=1024, in_chans=3, num_classes=1000, embed_dims=[64, 128, 160, 320], depths=[2, 2, 6, 2], ...
88
1,137
635
1,772
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
50,582
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/modeling/common.py
38,39
31,44
forward
LayerNorm2d
39,44
39,44
class LayerNorm2d(nn.Module): def __init__(self, num_channels: int, eps: float = 1e-6) -> None: super().__init__() self.weight = nn.Parameter(torch.ones(num_channels)) self.bias = nn.Parameter(torch.zeros(num_channels)) self.eps = eps def forward(self, x: torch.Tensor) -> torch....
class LayerNorm2d(nn.Module): def __init__(self, num_channels: int, eps: float = 1e-6) -> None: super().__init__() self.weight = nn.Parameter(torch.ones(num_channels)) self.bias = nn.Parameter(torch.zeros(num_channels)) self.eps = eps def forward(self, x: torch.Tensor) -> torch....
u = x.mean(1, keepdim=True) s = (x - u).pow(2).mean(1, keepdim=True) x = (x - u) / torch.sqrt(s + self.eps) x = self.weight[:, None, None] * x + self.bias[:, None, None] return x
u = x.mean(1, keepdim=True) s = (x - u).pow(2).mean(1, keepdim=True) x = (x - u) / torch.sqrt(s + self.eps) x = self.weight[:, None, None] * x + self.bias[:, None, None] return x
32
135
93
228
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from typing import Type class MLPBlock(nn.Module): def __init__( self, ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from typing import Type class MLPBlock(nn.Module): def __init__( self, ...
50,583
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/modeling/common.py
25,26
13,31
forward
MLPBlock
26,31
26,31
class MLPBlock(nn.Module): def __init__( self, embedding_dim: int, mlp_dim: int, act: Type[nn.Module] = nn.GELU, ) -> None: super().__init__() self.lin1 = nn.Linear(embedding_dim, mlp_dim) self.lin2 = nn.Linear(mlp_dim, embedding_dim) self.act = ac...
class MLPBlock(nn.Module): def __init__( self, embedding_dim: int, mlp_dim: int, act: Type[nn.Module] = nn.GELU, ) -> None: super().__init__() self.lin1 = nn.Linear(embedding_dim, mlp_dim) self.lin2 = nn.Linear(mlp_dim, embedding_dim) self.act = ac...
return self.lin2(self.act(self.lin1(x))) # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
return self.lin2(self.act(self.lin1(x))) # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
13
155
138
293
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from typing import Type class MLPBlock(nn.Module): def __init__( self, ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from typing import Type class MLPBlock(nn.Module): def __init__( self, ...
50,585
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/modeling/image_encoder.py
224,225
185,243
forward
Attention
225,243
225,243
class Attention(nn.Module): """Multi-head Attention block with relative position embeddings.""" def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = True, use_rel_pos: bool = False, rel_pos_zero_init: bool = True, input_size: Optional[Tuple[...
class Attention(nn.Module): """Multi-head Attention block with relative position embeddings.""" def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = True, use_rel_pos: bool = False, rel_pos_zero_init: bool = True, input_size: Optional[Tuple[...
B, H, W, _ = x.shape # qkv with shape (3, B, nHead, H * W, C) qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # q, k, v with shape (B * nHead, H * W, C) q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) attn = (q * self.s...
B, H, W, _ = x.shape # qkv with shape (3, B, nHead, H * W, C) qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # q, k, v with shape (B * nHead, H * W, C) q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) attn = (q * self.s...
99
516
341
857
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
50,586
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/modeling/image_encoder.py
166,167
119,185
forward
Block
167,185
167,185
class Block(nn.Module): """Transformer blocks with support of window attention and residual propagation blocks""" def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = True, norm_layer: Type[nn.Module] = nn.LayerNorm, act_...
class Block(nn.Module): """Transformer blocks with support of window attention and residual propagation blocks""" def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = True, norm_layer: Type[nn.Module] = nn.LayerNorm, act_...
shortcut = x x = self.norm1(x) # Window partition if self.window_size > 0: H, W = x.shape[1], x.shape[2] x, pad_hw = window_partition(x, self.window_size) x = self.attn(x) # Reverse window partition if self.window_size > 0: x =...
shortcut = x x = self.norm1(x) # Window partition if self.window_size > 0: H, W = x.shape[1], x.shape[2] x, pad_hw = window_partition(x, self.window_size) x = self.attn(x) # Reverse window partition if self.window_size > 0: x =...
53
615
178
793
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
50,587
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/modeling/image_encoder.py
106,107
17,119
forward
ImageEncoderViT
107,119
107,119
class ImageEncoderViT(nn.Module): def __init__( self, img_size: int = 1024, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 4.0, out_chans: int = 256, qkv_bias: boo...
class ImageEncoderViT(nn.Module): def __init__( self, img_size: int = 1024, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 4.0, out_chans: int = 256, qkv_bias: boo...
x = self.patch_embed(x) if self.pos_embed is not None: x = x + self.pos_embed for blk in self.blocks: x = blk(x) x = self.neck(x.permute(0, 3, 1, 2)) return x
x = self.patch_embed(x) if self.pos_embed is not None: x = x + self.pos_embed for blk in self.blocks: x = blk(x) x = self.neck(x.permute(0, 3, 1, 2)) return x
28
1,041
101
1,142
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
50,588
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/modeling/image_encoder.py
391,392
364,396
forward
PatchEmbed
392,396
392,396
class PatchEmbed(nn.Module): """ Image to Patch Embedding. """ def __init__( self, kernel_size: Tuple[int, int] = (16, 16), stride: Tuple[int, int] = (16, 16), padding: Tuple[int, int] = (0, 0), in_chans: int = 3, embed_dim: int = 768, ) -> None: ...
class PatchEmbed(nn.Module): """ Image to Patch Embedding. """ def __init__( self, kernel_size: Tuple[int, int] = (16, 16), stride: Tuple[int, int] = (16, 16), padding: Tuple[int, int] = (0, 0), in_chans: int = 3, embed_dim: int = 768, ) -> None: ...
x = self.proj(x) # B C H W -> B H W C x = x.permute(0, 2, 3, 1) return x
x = self.proj(x) # B C H W -> B H W C x = x.permute(0, 2, 3, 1) return x
21
301
52
353
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
50,589
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/modeling/mask_decoder.py
171,172
154,177
forward
MLP
172,177
172,177
class MLP(nn.Module): def __init__( self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False, ) -> None: super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) ...
class MLP(nn.Module): def __init__( self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False, ) -> None: super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) ...
for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) if self.sigmoid_output: x = F.sigmoid(x) return x
for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) if self.sigmoid_output: x = F.sigmoid(x) return x
23
189
75
264
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from torch.nn import functional as F from typing import List, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from torch.nn import functional as F from typing import List, Tuple, Type from .common...
50,590
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/modeling/mask_decoder.py
112,119
16,154
predict_masks
MaskDecoder
120,154
119,154
class MaskDecoder(nn.Module): def __init__( self, *, transformer_dim: int, transformer: nn.Module, num_multimask_outputs: int = 3, activation: Type[nn.Module] = nn.GELU, iou_head_depth: int = 3, iou_head_hidden_dim: int = 256, ) -> None: ""...
class MaskDecoder(nn.Module): def __init__( self, *, transformer_dim: int, transformer: nn.Module, num_multimask_outputs: int = 3, activation: Type[nn.Module] = nn.GELU, iou_head_depth: int = 3, iou_head_hidden_dim: int = 256, ) -> None: ""...
# Concatenate output tokens output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0) output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1) tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) # Expan...
"""Predicts masks. See 'forward' for more details.""" # Concatenate output tokens output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0) output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1) tokens = torch.cat((out...
147
1,201
617
1,818
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from torch.nn import functional as F from typing import List, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from torch.nn import functional as F from typing import List, Tuple, Type from .common...
50,591
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/modeling/prompt_encoder.py
206,207
182,227
forward
PositionEmbeddingRandom
208,219
207,219
class PositionEmbeddingRandom(nn.Module): """ Positional encoding using random spatial frequencies. """ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: super().__init__() if scale is None or scale <= 0.0: scale = 1.0 self.register_...
class PositionEmbeddingRandom(nn.Module): """ Positional encoding using random spatial frequencies. """ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: super().__init__() if scale is None or scale <= 0.0: scale = 1.0 self.register_...
h, w = size device: Any = self.positional_encoding_gaussian_matrix.device grid = torch.ones((h, w), device=device, dtype=torch.float32) y_embed = grid.cumsum(dim=0) - 0.5 x_embed = grid.cumsum(dim=1) - 0.5 y_embed = y_embed / h x_embed = x_embed / w pe = ...
"""Generate positional encoding for a grid of the specified size.""" h, w = size device: Any = self.positional_encoding_gaussian_matrix.device grid = torch.ones((h, w), device=device, dtype=torch.float32) y_embed = grid.cumsum(dim=0) - 0.5 x_embed = grid.cumsum(dim=1) - 0...
49
535
182
717
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from torch import nn from typing import Any, Optional, Tuple, Type from .common import L...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from torch import nn from typing import Any, Optional, Tuple, Type from .common import L...
50,593
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/modeling/transformer.py
208,209
185,241
_separate_heads
Attention
209,213
209,213
class Attention(nn.Module): """ An attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and values. """ def __init__( self, embedding_dim: int, num_heads: int, downsample_rate: int = 1, ) -> None: super(...
class Attention(nn.Module): """ An attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and values. """ def __init__( self, embedding_dim: int, num_heads: int, downsample_rate: int = 1, ) -> None: super(...
b, n, c = x.shape x = x.reshape(b, n, num_heads, c // num_heads) return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
b, n, c = x.shape x = x.reshape(b, n, num_heads, c // num_heads) return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
24
684
73
757
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
50,594
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/modeling/transformer.py
151,154
109,185
forward
TwoWayAttentionBlock
154,185
154,185
class TwoWayAttentionBlock(nn.Module): def __init__( self, embedding_dim: int, num_heads: int, mlp_dim: int = 2048, activation: Type[nn.Module] = nn.ReLU, attention_downsample_rate: int = 2, skip_first_layer_pe: bool = False, ) -> None: """ ...
class TwoWayAttentionBlock(nn.Module): def __init__( self, embedding_dim: int, num_heads: int, mlp_dim: int = 2048, activation: Type[nn.Module] = nn.ReLU, attention_downsample_rate: int = 2, skip_first_layer_pe: bool = False, ) -> None: """ ...
# Self attention block if self.skip_first_layer_pe: queries = self.self_attn(q=queries, k=queries, v=queries) else: q = queries + query_pe attn_out = self.self_attn(q=q, k=q, v=queries) queries = queries + attn_out queries = self.norm1(quer...
# Self attention block if self.skip_first_layer_pe: queries = self.self_attn(q=queries, k=queries, v=queries) else: q = queries + query_pe attn_out = self.self_attn(q=q, k=q, v=queries) queries = queries + attn_out queries = self.norm1(quer...
111
552
361
913
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
50,595
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/modeling/transformer.py
62,68
16,109
forward
TwoWayTransformer
81,109
68,109
class TwoWayTransformer(nn.Module): def __init__( self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Module] = nn.ReLU, attention_downsample_rate: int = 2, ) -> None: """ A transformer decoder that atten...
class TwoWayTransformer(nn.Module): def __init__( self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Module] = nn.ReLU, attention_downsample_rate: int = 2, ) -> None: """ A transformer decoder that atten...
# BxCxHxW -> BxHWxC == B x N_image_tokens x C bs, c, h, w = image_embedding.shape image_embedding = image_embedding.flatten(2).permute(0, 2, 1) image_pe = image_pe.flatten(2).permute(0, 2, 1) # Prepare queries queries = point_embedding keys = image_embedding ...
""" Args: image_embedding (torch.Tensor): image to attend to. Should be shape B x embedding_dim x h x w for any h and w. image_pe (torch.Tensor): the positional encoding to add to the image. Must have the same shape as image_embedding. point_embeddin...
93
675
320
995
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
50,597
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/mobile_sam/utils/transforms.py
67,70
16,103
apply_coords_torch
ResizeLongestSide
74,83
70,83
class ResizeLongestSide: """ Resizes images to the longest side 'target_length', as well as provides methods for resizing coordinates and boxes. Provides methods for transforming both numpy array and batched torch tensors. """ def __init__(self, target_length: int) -> None: self.target_...
class ResizeLongestSide: """ Resizes images to the longest side 'target_length', as well as provides methods for resizing coordinates and boxes. Provides methods for transforming both numpy array and batched torch tensors. """ def __init__(self, target_length: int) -> None: self.target_...
old_h, old_w = original_size new_h, new_w = self.get_preprocess_shape( original_size[0], original_size[1], self.target_length ) coords = deepcopy(coords).to(torch.float) coords[..., 0] = coords[..., 0] * (new_w / old_w) coords[..., 1] = coords[..., 1] * (new_h...
""" Expects a torch tensor with length 2 in the last dimension. Requires the original image size in (H, W) format. """ old_h, old_w = original_size new_h, new_w = self.get_preprocess_shape( original_size[0], original_size[1], self.target_length ) ...
35
1,065
145
1,210
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from torch.nn import functional as F from torchvision.transforms.functional import resize,...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from torch.nn import functional as F from torchvision.transforms.functional import resize,...
50,599
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/segment_anything/build_sam.py
14,15
1,108
build_sam_vit_h
15,24
15,24
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
return _build_sam( encoder_embed_dim=1280, encoder_depth=32, encoder_num_heads=16, encoder_global_attn_indexes=[7, 15, 23, 31], checkpoint=checkpoint, )
return _build_sam( encoder_embed_dim=1280, encoder_depth=32, encoder_num_heads=16, encoder_global_attn_indexes=[7, 15, 23, 31], checkpoint=checkpoint, )
11
1,014
91
1,105
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
50,600
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/segment_anything/modeling/common.py
38,39
31,44
forward
LayerNorm2d
39,44
39,44
class LayerNorm2d(nn.Module): def __init__(self, num_channels: int, eps: float = 1e-6) -> None: super().__init__() self.weight = nn.Parameter(torch.ones(num_channels)) self.bias = nn.Parameter(torch.zeros(num_channels)) self.eps = eps def forward(self, x: torch.Tensor) -> torch....
class LayerNorm2d(nn.Module): def __init__(self, num_channels: int, eps: float = 1e-6) -> None: super().__init__() self.weight = nn.Parameter(torch.ones(num_channels)) self.bias = nn.Parameter(torch.zeros(num_channels)) self.eps = eps def forward(self, x: torch.Tensor) -> torch....
u = x.mean(1, keepdim=True) s = (x - u).pow(2).mean(1, keepdim=True) x = (x - u) / torch.sqrt(s + self.eps) x = self.weight[:, None, None] * x + self.bias[:, None, None] return x
u = x.mean(1, keepdim=True) s = (x - u).pow(2).mean(1, keepdim=True) x = (x - u) / torch.sqrt(s + self.eps) x = self.weight[:, None, None] * x + self.bias[:, None, None] return x
32
135
93
228
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from typing import Type class MLPBlock(nn.Module): def __init__( self, ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from typing import Type class MLPBlock(nn.Module): def __init__( self, ...
50,601
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/segment_anything/modeling/common.py
25,26
13,31
forward
MLPBlock
26,31
26,31
class MLPBlock(nn.Module): def __init__( self, embedding_dim: int, mlp_dim: int, act: Type[nn.Module] = nn.GELU, ) -> None: super().__init__() self.lin1 = nn.Linear(embedding_dim, mlp_dim) self.lin2 = nn.Linear(mlp_dim, embedding_dim) self.act = ac...
class MLPBlock(nn.Module): def __init__( self, embedding_dim: int, mlp_dim: int, act: Type[nn.Module] = nn.GELU, ) -> None: super().__init__() self.lin1 = nn.Linear(embedding_dim, mlp_dim) self.lin2 = nn.Linear(mlp_dim, embedding_dim) self.act = ac...
return self.lin2(self.act(self.lin1(x))) # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
return self.lin2(self.act(self.lin1(x))) # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
13
155
138
293
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from typing import Type class MLPBlock(nn.Module): def __init__( self, ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from typing import Type class MLPBlock(nn.Module): def __init__( self, ...
50,603
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/segment_anything/modeling/image_encoder.py
224,225
185,243
forward
Attention
225,243
225,243
class Attention(nn.Module): """Multi-head Attention block with relative position embeddings.""" def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = True, use_rel_pos: bool = False, rel_pos_zero_init: bool = True, input_size: Optional[Tuple[...
class Attention(nn.Module): """Multi-head Attention block with relative position embeddings.""" def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = True, use_rel_pos: bool = False, rel_pos_zero_init: bool = True, input_size: Optional[Tuple[...
B, H, W, _ = x.shape # qkv with shape (3, B, nHead, H * W, C) qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # q, k, v with shape (B * nHead, H * W, C) q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) attn = (q * self.s...
B, H, W, _ = x.shape # qkv with shape (3, B, nHead, H * W, C) qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # q, k, v with shape (B * nHead, H * W, C) q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) attn = (q * self.s...
99
516
341
857
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
50,604
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/segment_anything/modeling/image_encoder.py
166,167
119,185
forward
Block
167,185
167,185
class Block(nn.Module): """Transformer blocks with support of window attention and residual propagation blocks""" def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = True, norm_layer: Type[nn.Module] = nn.LayerNorm, act_...
class Block(nn.Module): """Transformer blocks with support of window attention and residual propagation blocks""" def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = True, norm_layer: Type[nn.Module] = nn.LayerNorm, act_...
shortcut = x x = self.norm1(x) # Window partition if self.window_size > 0: H, W = x.shape[1], x.shape[2] x, pad_hw = window_partition(x, self.window_size) x = self.attn(x) # Reverse window partition if self.window_size > 0: x =...
shortcut = x x = self.norm1(x) # Window partition if self.window_size > 0: H, W = x.shape[1], x.shape[2] x, pad_hw = window_partition(x, self.window_size) x = self.attn(x) # Reverse window partition if self.window_size > 0: x =...
53
615
178
793
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
50,605
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/segment_anything/modeling/image_encoder.py
106,107
17,119
forward
ImageEncoderViT
107,119
107,119
class ImageEncoderViT(nn.Module): def __init__( self, img_size: int = 1024, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 4.0, out_chans: int = 256, qkv_bias: boo...
class ImageEncoderViT(nn.Module): def __init__( self, img_size: int = 1024, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 4.0, out_chans: int = 256, qkv_bias: boo...
x = self.patch_embed(x) if self.pos_embed is not None: x = x + self.pos_embed for blk in self.blocks: x = blk(x) x = self.neck(x.permute(0, 3, 1, 2)) return x
x = self.patch_embed(x) if self.pos_embed is not None: x = x + self.pos_embed for blk in self.blocks: x = blk(x) x = self.neck(x.permute(0, 3, 1, 2)) return x
28
1,041
101
1,142
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
50,606
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/segment_anything/modeling/image_encoder.py
391,392
364,396
forward
PatchEmbed
392,396
392,396
class PatchEmbed(nn.Module): """ Image to Patch Embedding. """ def __init__( self, kernel_size: Tuple[int, int] = (16, 16), stride: Tuple[int, int] = (16, 16), padding: Tuple[int, int] = (0, 0), in_chans: int = 3, embed_dim: int = 768, ) -> None: ...
class PatchEmbed(nn.Module): """ Image to Patch Embedding. """ def __init__( self, kernel_size: Tuple[int, int] = (16, 16), stride: Tuple[int, int] = (16, 16), padding: Tuple[int, int] = (0, 0), in_chans: int = 3, embed_dim: int = 768, ) -> None: ...
x = self.proj(x) # B C H W -> B H W C x = x.permute(0, 2, 3, 1) return x
x = self.proj(x) # B C H W -> B H W C x = x.permute(0, 2, 3, 1) return x
21
301
52
353
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
50,607
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/segment_anything/modeling/mask_decoder.py
171,172
154,177
forward
MLP
172,177
172,177
class MLP(nn.Module): def __init__( self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False, ) -> None: super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) ...
class MLP(nn.Module): def __init__( self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False, ) -> None: super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) ...
for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) if self.sigmoid_output: x = F.sigmoid(x) return x
for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) if self.sigmoid_output: x = F.sigmoid(x) return x
23
189
75
264
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from torch.nn import functional as F from typing import List, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from torch.nn import functional as F from typing import List, Tuple, Type from .common...
50,608
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/segment_anything/modeling/mask_decoder.py
71,79
16,154
forward
MaskDecoder
94,112
79,112
class MaskDecoder(nn.Module): def __init__( self, *, transformer_dim: int, transformer: nn.Module, num_multimask_outputs: int = 3, activation: Type[nn.Module] = nn.GELU, iou_head_depth: int = 3, iou_head_hidden_dim: int = 256, ) -> None: ""...
class MaskDecoder(nn.Module): def __init__( self, *, transformer_dim: int, transformer: nn.Module, num_multimask_outputs: int = 3, activation: Type[nn.Module] = nn.GELU, iou_head_depth: int = 3, iou_head_hidden_dim: int = 256, ) -> None: ""...
masks, iou_pred = self.predict_masks( image_embeddings=image_embeddings, image_pe=image_pe, sparse_prompt_embeddings=sparse_prompt_embeddings, dense_prompt_embeddings=dense_prompt_embeddings, ) # Select the correct mask or masks for output ...
""" Predict masks given image and prompt embeddings. Arguments: image_embeddings (torch.Tensor): the embeddings from the image encoder image_pe (torch.Tensor): positional encoding with the shape of image_embeddings sparse_prompt_embeddings (torch.Tensor): the embed...
45
1,601
201
1,802
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from torch.nn import functional as F from typing import List, Tuple, Type from .common...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from torch.nn import functional as F from typing import List, Tuple, Type from .common...
50,609
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/segment_anything/modeling/prompt_encoder.py
219,222
182,227
forward_with_coords
PositionEmbeddingRandom
223,227
222,227
class PositionEmbeddingRandom(nn.Module): """ Positional encoding using random spatial frequencies. """ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: super().__init__() if scale is None or scale <= 0.0: scale = 1.0 self.register_...
class PositionEmbeddingRandom(nn.Module): """ Positional encoding using random spatial frequencies. """ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: super().__init__() if scale is None or scale <= 0.0: scale = 1.0 self.register_...
coords = coords_input.clone() coords[:, :, 0] = coords[:, :, 0] / image_size[1] coords[:, :, 1] = coords[:, :, 1] / image_size[0] return self._pe_encoding(coords.to(torch.float)) # B x N x C
"""Positionally encode points that are not normalized to [0,1].""" coords = coords_input.clone() coords[:, :, 0] = coords[:, :, 0] / image_size[1] coords[:, :, 1] = coords[:, :, 1] / image_size[0] return self._pe_encoding(coords.to(torch.float)) # B x N x C
29
612
98
710
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from torch import nn from typing import Any, Optional, Tuple, Type from .common import L...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from torch import nn from typing import Any, Optional, Tuple, Type from .common import L...
50,611
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/segment_anything/modeling/transformer.py
213,214
185,241
_recombine_heads
Attention
214,218
214,218
class Attention(nn.Module): """ An attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and values. """ def __init__( self, embedding_dim: int, num_heads: int, downsample_rate: int = 1, ) -> None: super(...
class Attention(nn.Module): """ An attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and values. """ def __init__( self, embedding_dim: int, num_heads: int, downsample_rate: int = 1, ) -> None: super(...
b, n_heads, n_tokens, c_per_head = x.shape x = x.transpose(1, 2) return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C
b, n_heads, n_tokens, c_per_head = x.shape x = x.transpose(1, 2) return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C
22
679
78
757
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
50,612
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything
/home/hieuvd/dung_repo/raw/stars_03/yatengLG_ISAT_with_segment_anything/ISAT_with_segment_anything/ISAT/segment_any/segment_anything/modeling/transformer.py
151,154
109,185
forward
TwoWayAttentionBlock
154,185
154,185
class TwoWayAttentionBlock(nn.Module): def __init__( self, embedding_dim: int, num_heads: int, mlp_dim: int = 2048, activation: Type[nn.Module] = nn.ReLU, attention_downsample_rate: int = 2, skip_first_layer_pe: bool = False, ) -> None: """ ...
class TwoWayAttentionBlock(nn.Module): def __init__( self, embedding_dim: int, num_heads: int, mlp_dim: int = 2048, activation: Type[nn.Module] = nn.ReLU, attention_downsample_rate: int = 2, skip_first_layer_pe: bool = False, ) -> None: """ ...
# Self attention block if self.skip_first_layer_pe: queries = self.self_attn(q=queries, k=queries, v=queries) else: q = queries + query_pe attn_out = self.self_attn(q=q, k=q, v=queries) queries = queries + attn_out queries = self.norm1(quer...
# Self attention block if self.skip_first_layer_pe: queries = self.self_attn(q=queries, k=queries, v=queries) else: q = queries + query_pe attn_out = self.self_attn(q=q, k=q, v=queries) queries = queries + attn_out queries = self.norm1(quer...
111
552
361
913
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...