Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
parse_requirements
(fname='requirements.txt', with_version=True)
Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: ...
Parse the package dependencies listed in a requirements file but strips specific versioning information.
def parse_requirements(fname='requirements.txt', with_version=True): """Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs ...
[ "def", "parse_requirements", "(", "fname", "=", "'requirements.txt'", ",", "with_version", "=", "True", ")", ":", "import", "sys", "from", "os", ".", "path", "import", "exists", "import", "re", "require_fpath", "=", "fname", "def", "parse_line", "(", "line", ...
[ 23, 0 ]
[ 98, 19 ]
python
en
['en', 'en', 'en']
True
DataParallelPlugin.reduce
(self, tensor, *args, **kwargs)
Reduces a tensor from all parallel processes to one aggregated tensor. Args: tensor: the tensor to sync and reduce *args: ignored for DP **kwargs: ignored for DP Return: reduced value, except when the input was not a tensor the output remains is...
Reduces a tensor from all parallel processes to one aggregated tensor.
def reduce(self, tensor, *args, **kwargs): """ Reduces a tensor from all parallel processes to one aggregated tensor. Args: tensor: the tensor to sync and reduce *args: ignored for DP **kwargs: ignored for DP Return: reduced value, except...
[ "def", "reduce", "(", "self", ",", "tensor", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "tensor", ",", "Result", ")", ":", "tensor", ".", "dp_reduce", "(", ")", "elif", "isinstance", "(", "tensor", ",", "torch", "...
[ 33, 4 ]
[ 51, 21 ]
python
en
['en', 'error', 'th']
False
test_top_down_simple_head
()
Test simple head.
Test simple head.
def test_top_down_simple_head(): """Test simple head.""" with pytest.raises(TypeError): # extra _ = TopDownSimpleHead(out_channels=3, in_channels=512, extra=[]) # test num deconv layers with pytest.raises(ValueError): _ = TopDownSimpleHead( out_channels=3, in_channel...
[ "def", "test_top_down_simple_head", "(", ")", ":", "with", "pytest", ".", "raises", "(", "TypeError", ")", ":", "# extra", "_", "=", "TopDownSimpleHead", "(", "out_channels", "=", "3", ",", "in_channels", "=", "512", ",", "extra", "=", "[", "]", ")", "# ...
[ 8, 0 ]
[ 88, 23 ]
python
en
['en', 'et', 'en']
True
test_top_down_multistage_head
()
Test multistage head.
Test multistage head.
def test_top_down_multistage_head(): """Test multistage head.""" with pytest.raises(TypeError): # the number of layers should match _ = TopDownMultiStageHead( out_channels=3, in_channels=512, num_stages=1, extra=[]) # test num deconv layers with pytest.raises(ValueError): ...
[ "def", "test_top_down_multistage_head", "(", ")", ":", "with", "pytest", ".", "raises", "(", "TypeError", ")", ":", "# the number of layers should match", "_", "=", "TopDownMultiStageHead", "(", "out_channels", "=", "3", ",", "in_channels", "=", "512", ",", "num_s...
[ 91, 0 ]
[ 177, 23 ]
python
en
['en', 'et', 'en']
True
test_top_down_msmu_head
()
Test multi-stage multi-unit head.
Test multi-stage multi-unit head.
def test_top_down_msmu_head(): """Test multi-stage multi-unit head.""" with pytest.raises(AssertionError): # inputs should be list head = TopDownMSMUHead( out_shape=(64, 48), unit_channels=256, num_stages=2, num_units=2) input_shape = (1, 256, 32, 32) inputs = _demo_i...
[ "def", "test_top_down_msmu_head", "(", ")", ":", "with", "pytest", ".", "raises", "(", "AssertionError", ")", ":", "# inputs should be list", "head", "=", "TopDownMSMUHead", "(", "out_shape", "=", "(", "64", ",", "48", ")", ",", "unit_channels", "=", "256", ...
[ 180, 0 ]
[ 239, 23 ]
python
en
['en', 'et', 'en']
True
_demo_inputs
(input_shape=(1, 3, 64, 64))
Create a superset of inputs needed to run backbone. Args: input_shape (tuple): input batch dimensions. Default: (1, 3, 64, 64). Returns: Random input tensor with the size of input_shape.
Create a superset of inputs needed to run backbone.
def _demo_inputs(input_shape=(1, 3, 64, 64)): """Create a superset of inputs needed to run backbone. Args: input_shape (tuple): input batch dimensions. Default: (1, 3, 64, 64). Returns: Random input tensor with the size of input_shape. """ inps = np.random.random(input_s...
[ "def", "_demo_inputs", "(", "input_shape", "=", "(", "1", ",", "3", ",", "64", ",", "64", ")", ")", ":", "inps", "=", "np", ".", "random", ".", "random", "(", "input_shape", ")", "inps", "=", "torch", ".", "FloatTensor", "(", "inps", ")", "return",...
[ 242, 0 ]
[ 253, 15 ]
python
en
['en', 'en', 'en']
True
_decode_line
(line, encoding=None)
Decode bytes from binary input streams. Defaults to decoding from 'latin1'. That differs from the behavior of np.compat.asunicode that decodes from 'ascii'. Parameters ---------- line : str or bytes Line to be decoded. Returns ------- decoded_line : unicode Unicode i...
Decode bytes from binary input streams.
def _decode_line(line, encoding=None): """Decode bytes from binary input streams. Defaults to decoding from 'latin1'. That differs from the behavior of np.compat.asunicode that decodes from 'ascii'. Parameters ---------- line : str or bytes Line to be decoded. Returns -------...
[ "def", "_decode_line", "(", "line", ",", "encoding", "=", "None", ")", ":", "if", "type", "(", "line", ")", "is", "bytes", ":", "if", "encoding", "is", "None", ":", "line", "=", "line", ".", "decode", "(", "'latin1'", ")", "else", ":", "line", "=",...
[ 19, 0 ]
[ 42, 15 ]
python
en
['en', 'en', 'en']
True
_is_string_like
(obj)
Check whether obj behaves like a string.
Check whether obj behaves like a string.
def _is_string_like(obj): """ Check whether obj behaves like a string. """ try: obj + '' except (TypeError, ValueError): return False return True
[ "def", "_is_string_like", "(", "obj", ")", ":", "try", ":", "obj", "+", "''", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "False", "return", "True" ]
[ 45, 0 ]
[ 53, 15 ]
python
en
['en', 'error', 'th']
False
_is_bytes_like
(obj)
Check whether obj behaves like a bytes object.
Check whether obj behaves like a bytes object.
def _is_bytes_like(obj): """ Check whether obj behaves like a bytes object. """ try: obj + b'' except (TypeError, ValueError): return False return True
[ "def", "_is_bytes_like", "(", "obj", ")", ":", "try", ":", "obj", "+", "b''", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "False", "return", "True" ]
[ 56, 0 ]
[ 64, 15 ]
python
en
['en', 'error', 'th']
False
_to_filehandle
(fname, flag='r', return_opened=False)
Returns the filehandle corresponding to a string or a file. If the string ends in '.gz', the file is automatically unzipped. Parameters ---------- fname : string, filehandle Name of the file whose filehandle must be returned. flag : string, optional Flag indicating the status o...
Returns the filehandle corresponding to a string or a file. If the string ends in '.gz', the file is automatically unzipped.
def _to_filehandle(fname, flag='r', return_opened=False): """ Returns the filehandle corresponding to a string or a file. If the string ends in '.gz', the file is automatically unzipped. Parameters ---------- fname : string, filehandle Name of the file whose filehandle must be returned....
[ "def", "_to_filehandle", "(", "fname", ",", "flag", "=", "'r'", ",", "return_opened", "=", "False", ")", ":", "if", "_is_string_like", "(", "fname", ")", ":", "if", "fname", ".", "endswith", "(", "'.gz'", ")", ":", "import", "gzip", "fhd", "=", "gzip",...
[ 67, 0 ]
[ 98, 14 ]
python
en
['en', 'error', 'th']
False
has_nested_fields
(ndtype)
Returns whether one or several fields of a dtype are nested. Parameters ---------- ndtype : dtype Data-type of a structured array. Raises ------ AttributeError If `ndtype` does not have a `names` attribute. Examples -------- >>> dt = np.dtype([('name', 'S4'), ...
Returns whether one or several fields of a dtype are nested.
def has_nested_fields(ndtype): """ Returns whether one or several fields of a dtype are nested. Parameters ---------- ndtype : dtype Data-type of a structured array. Raises ------ AttributeError If `ndtype` does not have a `names` attribute. Examples -------- ...
[ "def", "has_nested_fields", "(", "ndtype", ")", ":", "for", "name", "in", "ndtype", ".", "names", "or", "(", ")", ":", "if", "ndtype", "[", "name", "]", ".", "names", "is", "not", "None", ":", "return", "True", "return", "False" ]
[ 101, 0 ]
[ 125, 16 ]
python
en
['en', 'error', 'th']
False
flatten_dtype
(ndtype, flatten_base=False)
Unpack a structured data-type by collapsing nested fields and/or fields with a shape. Note that the field names are lost. Parameters ---------- ndtype : dtype The datatype to collapse flatten_base : bool, optional If True, transform a field with a shape into several fields....
Unpack a structured data-type by collapsing nested fields and/or fields with a shape.
def flatten_dtype(ndtype, flatten_base=False): """ Unpack a structured data-type by collapsing nested fields and/or fields with a shape. Note that the field names are lost. Parameters ---------- ndtype : dtype The datatype to collapse flatten_base : bool, optional If Tru...
[ "def", "flatten_dtype", "(", "ndtype", ",", "flatten_base", "=", "False", ")", ":", "names", "=", "ndtype", ".", "names", "if", "names", "is", "None", ":", "if", "flatten_base", ":", "return", "[", "ndtype", ".", "base", "]", "*", "int", "(", "np", "...
[ 128, 0 ]
[ 172, 20 ]
python
en
['en', 'error', 'th']
False
str2bool
(value)
Tries to transform a string supposed to represent a boolean to a boolean. Parameters ---------- value : str The string that is transformed to a boolean. Returns ------- boolval : bool The boolean representation of `value`. Raises ------ ValueError If t...
Tries to transform a string supposed to represent a boolean to a boolean.
def str2bool(value): """ Tries to transform a string supposed to represent a boolean to a boolean. Parameters ---------- value : str The string that is transformed to a boolean. Returns ------- boolval : bool The boolean representation of `value`. Raises ------...
[ "def", "str2bool", "(", "value", ")", ":", "value", "=", "value", ".", "upper", "(", ")", "if", "value", "==", "'TRUE'", ":", "return", "True", "elif", "value", "==", "'FALSE'", ":", "return", "False", "else", ":", "raise", "ValueError", "(", "\"Invali...
[ 433, 0 ]
[ 466, 43 ]
python
en
['en', 'error', 'th']
False
easy_dtype
(ndtype, names=None, defaultfmt="f%i", **validationargs)
Convenience function to create a `np.dtype` object. The function processes the input `dtype` and matches it with the given names. Parameters ---------- ndtype : var Definition of the dtype. Can be any string or dictionary recognized by the `np.dtype` function, or a sequence of...
Convenience function to create a `np.dtype` object.
def easy_dtype(ndtype, names=None, defaultfmt="f%i", **validationargs): """ Convenience function to create a `np.dtype` object. The function processes the input `dtype` and matches it with the given names. Parameters ---------- ndtype : var Definition of the dtype. Can be any strin...
[ "def", "easy_dtype", "(", "ndtype", ",", "names", "=", "None", ",", "defaultfmt", "=", "\"f%i\"", ",", "*", "*", "validationargs", ")", ":", "try", ":", "ndtype", "=", "np", ".", "dtype", "(", "ndtype", ")", "except", "TypeError", ":", "validate", "=",...
[ 883, 0 ]
[ 957, 17 ]
python
en
['en', 'error', 'th']
False
LineSplitter.autostrip
(self, method)
Wrapper to strip each member of the output of `method`. Parameters ---------- method : function Function that takes a single argument and returns a sequence of strings. Returns ------- wrapped : function The result of wrappin...
Wrapper to strip each member of the output of `method`.
def autostrip(self, method): """ Wrapper to strip each member of the output of `method`. Parameters ---------- method : function Function that takes a single argument and returns a sequence of strings. Returns ------- wrapped : fu...
[ "def", "autostrip", "(", "self", ",", "method", ")", ":", "return", "lambda", "input", ":", "[", "_", ".", "strip", "(", ")", "for", "_", "in", "method", "(", "input", ")", "]" ]
[ 191, 4 ]
[ 209, 63 ]
python
en
['en', 'error', 'th']
False
LineSplitter._delimited_splitter
(self, line)
Chop off comments, strip, and split at delimiter.
Chop off comments, strip, and split at delimiter.
def _delimited_splitter(self, line): """Chop off comments, strip, and split at delimiter. """ if self.comments is not None: line = line.split(self.comments)[0] line = line.strip(" \r\n") if not line: return [] return line.split(self.delimiter)
[ "def", "_delimited_splitter", "(", "self", ",", "line", ")", ":", "if", "self", ".", "comments", "is", "not", "None", ":", "line", "=", "line", ".", "split", "(", "self", ".", "comments", ")", "[", "0", "]", "line", "=", "line", ".", "strip", "(", ...
[ 241, 4 ]
[ 248, 41 ]
python
en
['en', 'en', 'en']
True
NameValidator.validate
(self, names, defaultfmt="f%i", nbfields=None)
Validate a list of strings as field names for a structured array. Parameters ---------- names : sequence of str Strings to be validated. defaultfmt : str, optional Default format string, used if validating a given string reduces its length to...
Validate a list of strings as field names for a structured array.
def validate(self, names, defaultfmt="f%i", nbfields=None): """ Validate a list of strings as field names for a structured array. Parameters ---------- names : sequence of str Strings to be validated. defaultfmt : str, optional Default format stri...
[ "def", "validate", "(", "self", ",", "names", ",", "defaultfmt", "=", "\"f%i\"", ",", "nbfields", "=", "None", ")", ":", "# Initial checks ..............", "if", "(", "names", "is", "None", ")", ":", "if", "(", "nbfields", "is", "None", ")", ":", "return...
[ 358, 4 ]
[ 426, 36 ]
python
en
['en', 'error', 'th']
False
StringConverter._getdtype
(cls, val)
Returns the dtype of the input variable.
Returns the dtype of the input variable.
def _getdtype(cls, val): """Returns the dtype of the input variable.""" return np.array(val).dtype
[ "def", "_getdtype", "(", "cls", ",", "val", ")", ":", "return", "np", ".", "array", "(", "val", ")", ".", "dtype" ]
[ 564, 4 ]
[ 566, 34 ]
python
en
['en', 'en', 'en']
True
StringConverter._getsubdtype
(cls, val)
Returns the type of the dtype of the input variable.
Returns the type of the dtype of the input variable.
def _getsubdtype(cls, val): """Returns the type of the dtype of the input variable.""" return np.array(val).dtype.type
[ "def", "_getsubdtype", "(", "cls", ",", "val", ")", ":", "return", "np", ".", "array", "(", "val", ")", ".", "dtype", ".", "type" ]
[ 570, 4 ]
[ 572, 39 ]
python
en
['en', 'en', 'en']
True
StringConverter._dtypeortype
(cls, dtype)
Returns dtype for datetime64 and type of dtype otherwise.
Returns dtype for datetime64 and type of dtype otherwise.
def _dtypeortype(cls, dtype): """Returns dtype for datetime64 and type of dtype otherwise.""" if dtype.type == np.datetime64: return dtype return dtype.type
[ "def", "_dtypeortype", "(", "cls", ",", "dtype", ")", ":", "if", "dtype", ".", "type", "==", "np", ".", "datetime64", ":", "return", "dtype", "return", "dtype", ".", "type" ]
[ 580, 4 ]
[ 584, 25 ]
python
en
['en', 'en', 'en']
True
StringConverter.upgrade_mapper
(cls, func, default=None)
Upgrade the mapper of a StringConverter by adding a new function and its corresponding default. The input function (or sequence of functions) and its associated default value (if any) is inserted in penultimate position of the mapper. The corresponding type is estimated from the dtype of the ...
Upgrade the mapper of a StringConverter by adding a new function and its corresponding default.
def upgrade_mapper(cls, func, default=None): """ Upgrade the mapper of a StringConverter by adding a new function and its corresponding default. The input function (or sequence of functions) and its associated default value (if any) is inserted in penultimate position of the mapper. The co...
[ "def", "upgrade_mapper", "(", "cls", ",", "func", ",", "default", "=", "None", ")", ":", "# Func is a single functions", "if", "hasattr", "(", "func", ",", "'__call__'", ")", ":", "cls", ".", "_mapper", ".", "insert", "(", "-", "1", ",", "(", "cls", "....
[ 588, 4 ]
[ 626, 73 ]
python
en
['en', 'error', 'th']
False
StringConverter.upgrade
(self, value)
Find the best converter for a given string, and return the result. The supplied string `value` is converted by testing different converters in order. First the `func` method of the `StringConverter` instance is tried, if this fails other available converters are tried. The ord...
Find the best converter for a given string, and return the result.
def upgrade(self, value): """ Find the best converter for a given string, and return the result. The supplied string `value` is converted by testing different converters in order. First the `func` method of the `StringConverter` instance is tried, if this fails other available ...
[ "def", "upgrade", "(", "self", ",", "value", ")", ":", "self", ".", "_checked", "=", "True", "try", ":", "return", "self", ".", "_strict_call", "(", "value", ")", "except", "ValueError", ":", "# Raise an exception if we locked the converter...", "if", "self", ...
[ 750, 4 ]
[ 793, 38 ]
python
en
['en', 'error', 'th']
False
StringConverter.update
(self, func, default=None, testing_value=None, missing_values='', locked=False)
Set StringConverter attributes directly. Parameters ---------- func : function Conversion function. default : any, optional Value to return by default, that is, when the string to be converted is flagged as missing. If not given, ...
Set StringConverter attributes directly.
def update(self, func, default=None, testing_value=None, missing_values='', locked=False): """ Set StringConverter attributes directly. Parameters ---------- func : function Conversion function. default : any, optional Value to retu...
[ "def", "update", "(", "self", ",", "func", ",", "default", "=", "None", ",", "testing_value", "=", "None", ",", "missing_values", "=", "''", ",", "locked", "=", "False", ")", ":", "self", ".", "func", "=", "func", "self", ".", "_locked", "=", "locked...
[ 825, 4 ]
[ 880, 54 ]
python
en
['en', 'error', 'th']
False
seterr
(all=None, divide=None, over=None, under=None, invalid=None)
Set how floating-point errors are handled. Note that operations on integer scalar types (such as `int16`) are handled like floating point, and are affected by these settings. Parameters ---------- all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Set treatment for al...
Set how floating-point errors are handled.
def seterr(all=None, divide=None, over=None, under=None, invalid=None): """ Set how floating-point errors are handled. Note that operations on integer scalar types (such as `int16`) are handled like floating point, and are affected by these settings. Parameters ---------- all : {'ignore', ...
[ "def", "seterr", "(", "all", "=", "None", ",", "divide", "=", "None", ",", "over", "=", "None", ",", "under", "=", "None", ",", "invalid", "=", "None", ")", ":", "pyvals", "=", "umath", ".", "geterrobj", "(", ")", "old", "=", "geterr", "(", ")", ...
[ 39, 0 ]
[ 135, 14 ]
python
en
['en', 'error', 'th']
False
geterr
()
Get the current way of handling floating-point errors. Returns ------- res : dict A dictionary with keys "divide", "over", "under", and "invalid", whose values are from the strings "ignore", "print", "log", "warn", "raise", and "call". The keys represent possible floating-point...
Get the current way of handling floating-point errors.
def geterr(): """ Get the current way of handling floating-point errors. Returns ------- res : dict A dictionary with keys "divide", "over", "under", and "invalid", whose values are from the strings "ignore", "print", "log", "warn", "raise", and "call". The keys represent po...
[ "def", "geterr", "(", ")", ":", "maskvalue", "=", "umath", ".", "geterrobj", "(", ")", "[", "1", "]", "mask", "=", "7", "res", "=", "{", "}", "val", "=", "(", "maskvalue", ">>", "SHIFT_DIVIDEBYZERO", ")", "&", "mask", "res", "[", "'divide'", "]", ...
[ 139, 0 ]
[ 186, 14 ]
python
en
['en', 'error', 'th']
False
setbufsize
(size)
Set the size of the buffer used in ufuncs. Parameters ---------- size : int Size of buffer.
Set the size of the buffer used in ufuncs.
def setbufsize(size): """ Set the size of the buffer used in ufuncs. Parameters ---------- size : int Size of buffer. """ if size > 10e6: raise ValueError("Buffer size, %s, is too big." % size) if size < 5: raise ValueError("Buffer size, %s, is too small." % siz...
[ "def", "setbufsize", "(", "size", ")", ":", "if", "size", ">", "10e6", ":", "raise", "ValueError", "(", "\"Buffer size, %s, is too big.\"", "%", "size", ")", "if", "size", "<", "5", ":", "raise", "ValueError", "(", "\"Buffer size, %s, is too small.\"", "%", "s...
[ 190, 0 ]
[ 211, 14 ]
python
en
['en', 'error', 'th']
False
getbufsize
()
Return the size of the buffer used in ufuncs. Returns ------- getbufsize : int Size of ufunc buffer in bytes.
Return the size of the buffer used in ufuncs.
def getbufsize(): """ Return the size of the buffer used in ufuncs. Returns ------- getbufsize : int Size of ufunc buffer in bytes. """ return umath.geterrobj()[0]
[ "def", "getbufsize", "(", ")", ":", "return", "umath", ".", "geterrobj", "(", ")", "[", "0", "]" ]
[ 215, 0 ]
[ 225, 31 ]
python
en
['en', 'error', 'th']
False
seterrcall
(func)
Set the floating-point error callback function or log object. There are two ways to capture floating-point error messages. The first is to set the error-handler to 'call', using `seterr`. Then, set the function to call using this function. The second is to set the error-handler to 'log', using ...
Set the floating-point error callback function or log object.
def seterrcall(func): """ Set the floating-point error callback function or log object. There are two ways to capture floating-point error messages. The first is to set the error-handler to 'call', using `seterr`. Then, set the function to call using this function. The second is to set the e...
[ "def", "seterrcall", "(", "func", ")", ":", "if", "func", "is", "not", "None", "and", "not", "isinstance", "(", "func", ",", "collections_abc", ".", "Callable", ")", ":", "if", "not", "hasattr", "(", "func", ",", "'write'", ")", "or", "not", "isinstanc...
[ 229, 0 ]
[ 318, 14 ]
python
en
['en', 'error', 'th']
False
geterrcall
()
Return the current callback function used on floating-point errors. When the error handling for a floating-point error (one of "divide", "over", "under", or "invalid") is set to 'call' or 'log', the function that is called or the log instance that is written to is returned by `geterrcall`. This fu...
Return the current callback function used on floating-point errors.
def geterrcall(): """ Return the current callback function used on floating-point errors. When the error handling for a floating-point error (one of "divide", "over", "under", or "invalid") is set to 'call' or 'log', the function that is called or the log instance that is written to is returned by ...
[ "def", "geterrcall", "(", ")", ":", "return", "umath", ".", "geterrobj", "(", ")", "[", "2", "]" ]
[ 322, 0 ]
[ 364, 31 ]
python
en
['en', 'error', 'th']
False
test_pico_recipes_page_successfully
(client)
Retrieve /pico_recipes page successfully.
Retrieve /pico_recipes page successfully.
def test_pico_recipes_page_successfully(client): """Retrieve /pico_recipes page successfully.""" rv = client.get('/pico_recipes') assert '200' in rv.status
[ "def", "test_pico_recipes_page_successfully", "(", "client", ")", ":", "rv", "=", "client", ".", "get", "(", "'/pico_recipes'", ")", "assert", "'200'", "in", "rv", ".", "status" ]
[ 11, 0 ]
[ 15, 29 ]
python
en
['fr', 'sk', 'en']
False
test_zymatic_recipes_page_successfully
(client)
Retrieve /zymatic_recipes page successfully.
Retrieve /zymatic_recipes page successfully.
def test_zymatic_recipes_page_successfully(client): """Retrieve /zymatic_recipes page successfully.""" rv = client.get('/zymatic_recipes') assert '200' in rv.status
[ "def", "test_zymatic_recipes_page_successfully", "(", "client", ")", ":", "rv", "=", "client", ".", "get", "(", "'/zymatic_recipes'", ")", "assert", "'200'", "in", "rv", ".", "status" ]
[ 18, 0 ]
[ 22, 29 ]
python
en
['en', 'en', 'en']
True
test_zseries_recipes_page_successfully
(client)
Retrieve /zseries_recipes page successfully.
Retrieve /zseries_recipes page successfully.
def test_zseries_recipes_page_successfully(client): """Retrieve /zseries_recipes page successfully.""" rv = client.get('/zseries_recipes') assert '200' in rv.status
[ "def", "test_zseries_recipes_page_successfully", "(", "client", ")", ":", "rv", "=", "client", ".", "get", "(", "'/zseries_recipes'", ")", "assert", "'200'", "in", "rv", ".", "status" ]
[ 25, 0 ]
[ 29, 29 ]
python
en
['fr', 'en', 'en']
True
test_brew_history_page_successfully
(client)
Retrieve /brew_history page successfully.
Retrieve /brew_history page successfully.
def test_brew_history_page_successfully(client): """Retrieve /brew_history page successfully.""" rv = client.get('/brew_history') assert '200' in rv.status
[ "def", "test_brew_history_page_successfully", "(", "client", ")", ":", "rv", "=", "client", ".", "get", "(", "'/brew_history'", ")", "assert", "'200'", "in", "rv", ".", "status" ]
[ 32, 0 ]
[ 36, 29 ]
python
en
['en', 'en', 'en']
True
test_ferm_history_page_successfully
(client)
Retrieve /ferm_history page successfully.
Retrieve /ferm_history page successfully.
def test_ferm_history_page_successfully(client): """Retrieve /ferm_history page successfully.""" rv = client.get('/ferm_history') assert '200' in rv.status
[ "def", "test_ferm_history_page_successfully", "(", "client", ")", ":", "rv", "=", "client", ".", "get", "(", "'/ferm_history'", ")", "assert", "'200'", "in", "rv", ".", "status" ]
[ 39, 0 ]
[ 43, 29 ]
python
en
['en', 'en', 'en']
True
ConfusionMatrix.update
(self, preds: torch.Tensor, target: torch.Tensor)
Update state with predictions and targets. Args: preds: Predictions from model target: Ground truth values
Update state with predictions and targets.
def update(self, preds: torch.Tensor, target: torch.Tensor): """ Update state with predictions and targets. Args: preds: Predictions from model target: Ground truth values """ confmat = _confusion_matrix_update(preds, target, self.num_classes, self.thresh...
[ "def", "update", "(", "self", ",", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ")", ":", "confmat", "=", "_confusion_matrix_update", "(", "preds", ",", "target", ",", "self", ".", "num_classes", ",", "self", ".", "...
[ 98, 4 ]
[ 107, 31 ]
python
en
['en', 'error', 'th']
False
ConfusionMatrix.compute
(self)
Computes confusion matrix
Computes confusion matrix
def compute(self) -> torch.Tensor: """ Computes confusion matrix """ return _confusion_matrix_compute(self.confmat, self.normalize)
[ "def", "compute", "(", "self", ")", "->", "torch", ".", "Tensor", ":", "return", "_confusion_matrix_compute", "(", "self", ".", "confmat", ",", "self", ".", "normalize", ")" ]
[ 109, 4 ]
[ 113, 70 ]
python
en
['en', 'error', 'th']
False
getctype
(var)
Determines C type
Determines C type
def getctype(var): """ Determines C type """ ctype = 'void' if isfunction(var): if 'result' in var: a = var['result'] else: a = var['name'] if a in var['vars']: return getctype(var['vars'][a]) else: errmess('getctype: fu...
[ "def", "getctype", "(", "var", ")", ":", "ctype", "=", "'void'", "if", "isfunction", "(", "var", ")", ":", "if", "'result'", "in", "var", ":", "a", "=", "var", "[", "'result'", "]", "else", ":", "a", "=", "var", "[", "'name'", "]", "if", "a", "...
[ 237, 0 ]
[ 283, 16 ]
python
en
['en', 'error', 'th']
False
sign2map
(a, var)
varname,ctype,atype init,init.r,init.i,pytype vardebuginfo,vardebugshowvalue,varshowvalue varrfromat intent
varname,ctype,atype init,init.r,init.i,pytype vardebuginfo,vardebugshowvalue,varshowvalue varrfromat intent
def sign2map(a, var): """ varname,ctype,atype init,init.r,init.i,pytype vardebuginfo,vardebugshowvalue,varshowvalue varrfromat intent """ global lcb_map, cb_map out_a = a if isintent_out(var): for k in var['intent']: if k[:4] == 'out=': out_a =...
[ "def", "sign2map", "(", "a", ",", "var", ")", ":", "global", "lcb_map", ",", "cb_map", "out_a", "=", "a", "if", "isintent_out", "(", "var", ")", ":", "for", "k", "in", "var", "[", "'intent'", "]", ":", "if", "k", "[", ":", "4", "]", "==", "'out...
[ 503, 0 ]
[ 605, 14 ]
python
en
['en', 'error', 'th']
False
routsign2map
(rout)
name,NAME,begintitle,endtitle rname,ctype,rformat routdebugshowvalue
name,NAME,begintitle,endtitle rname,ctype,rformat routdebugshowvalue
def routsign2map(rout): """ name,NAME,begintitle,endtitle rname,ctype,rformat routdebugshowvalue """ global lcb_map name = rout['name'] fname = getfortranname(rout) ret = {'name': name, 'texname': name.replace('_', '\\_'), 'name_lower': name.lower(), ...
[ "def", "routsign2map", "(", "rout", ")", ":", "global", "lcb_map", "name", "=", "rout", "[", "'name'", "]", "fname", "=", "getfortranname", "(", "rout", ")", "ret", "=", "{", "'name'", ":", "name", ",", "'texname'", ":", "name", ".", "replace", "(", ...
[ 608, 0 ]
[ 686, 14 ]
python
en
['en', 'error', 'th']
False
modsign2map
(m)
modulename
modulename
def modsign2map(m): """ modulename """ if ismodule(m): ret = {'f90modulename': m['name'], 'F90MODULENAME': m['name'].upper(), 'texf90modulename': m['name'].replace('_', '\\_')} else: ret = {'modulename': m['name'], 'MODULENAME': m['name']....
[ "def", "modsign2map", "(", "m", ")", ":", "if", "ismodule", "(", "m", ")", ":", "ret", "=", "{", "'f90modulename'", ":", "m", "[", "'name'", "]", ",", "'F90MODULENAME'", ":", "m", "[", "'name'", "]", ".", "upper", "(", ")", ",", "'texf90modulename'",...
[ 689, 0 ]
[ 715, 14 ]
python
en
['en', 'error', 'th']
False
cb_routsign2map
(rout, um)
name,begintitle,endtitle,argname ctype,rctype,maxnofargs,nofoptargs,returncptr
name,begintitle,endtitle,argname ctype,rctype,maxnofargs,nofoptargs,returncptr
def cb_routsign2map(rout, um): """ name,begintitle,endtitle,argname ctype,rctype,maxnofargs,nofoptargs,returncptr """ ret = {'name': 'cb_%s_in_%s' % (rout['name'], um), 'returncptr': ''} if isintent_callback(rout): if '_' in rout['name']: F_FUNC = 'F_FUNC_US' ...
[ "def", "cb_routsign2map", "(", "rout", ",", "um", ")", ":", "ret", "=", "{", "'name'", ":", "'cb_%s_in_%s'", "%", "(", "rout", "[", "'name'", "]", ",", "um", ")", ",", "'returncptr'", ":", "''", "}", "if", "isintent_callback", "(", "rout", ")", ":", ...
[ 735, 0 ]
[ 814, 14 ]
python
en
['en', 'error', 'th']
False
HookResultStore.run_latest_batch_metrics_with_func_name
(self, func_name, *args, **kwargs)
This function used cache_ref and cache_result to optimize loading metrics Context: As we update the logger_connector metrics on every `self.log` call, and it can be pretty time consuming, especially when logging outside batch loop. HookResultStore keeps track of its latest added resul...
This function used cache_ref and cache_result to optimize loading metrics
def run_latest_batch_metrics_with_func_name(self, func_name, *args, **kwargs) -> List[Dict]: """ This function used cache_ref and cache_result to optimize loading metrics Context: As we update the logger_connector metrics on every `self.log` call, and it can be pretty time consuming, es...
[ "def", "run_latest_batch_metrics_with_func_name", "(", "self", ",", "func_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "List", "[", "Dict", "]", ":", "return", "[", "self", ".", "get_latest_from_func_name", "(", "self", ".", "_latest_ref", "[...
[ 82, 4 ]
[ 95, 9 ]
python
en
['en', 'error', 'th']
False
HookResultStore.auto_reduce_results_on_epoch_end
(self)
This function is called to reduce `self._internals` Result object. The reduced Result object will be saved into `self._internals_reduced` The `self._internals` stored Result objects will be deleted to save memory.
This function is called to reduce `self._internals` Result object. The reduced Result object will be saved into `self._internals_reduced` The `self._internals` stored Result objects will be deleted to save memory.
def auto_reduce_results_on_epoch_end(self) -> None: """ This function is called to reduce `self._internals` Result object. The reduced Result object will be saved into `self._internals_reduced` The `self._internals` stored Result objects will be deleted to save memory. """ ...
[ "def", "auto_reduce_results_on_epoch_end", "(", "self", ")", "->", "None", ":", "if", "self", ".", "has_reduced", ":", "return", "for", "dl_idx", "in", "range", "(", "self", ".", "num_dataloaders", ")", ":", "epoch_metrics", "=", "self", ".", "_internals", "...
[ 153, 4 ]
[ 200, 31 ]
python
en
['en', 'error', 'th']
False
EpochResultStore.info
(self)
This function provides necessary parameters to properly configure HookResultStore obj
This function provides necessary parameters to properly configure HookResultStore obj
def info(self): """ This function provides necessary parameters to properly configure HookResultStore obj """ model_ref = self.trainer.lightning_module return { "batch_idx": self.trainer.batch_idx, "fx_name": model_ref._current_hook_fx_name or model_ref._c...
[ "def", "info", "(", "self", ")", ":", "model_ref", "=", "self", ".", "trainer", ".", "lightning_module", "return", "{", "\"batch_idx\"", ":", "self", ".", "trainer", ".", "batch_idx", ",", "\"fx_name\"", ":", "model_ref", ".", "_current_hook_fx_name", "or", ...
[ 233, 4 ]
[ 248, 9 ]
python
en
['en', 'error', 'th']
False
EpochResultStore.reset_model
(self)
This function is used to reset model state at the end of the capture
This function is used to reset model state at the end of the capture
def reset_model(self): """ This function is used to reset model state at the end of the capture """ model_ref = self.trainer.lightning_module model_ref._results = Result() model_ref._current_hook_fx_name = None model_ref._current_fx_name = ''
[ "def", "reset_model", "(", "self", ")", ":", "model_ref", "=", "self", ".", "trainer", ".", "lightning_module", "model_ref", ".", "_results", "=", "Result", "(", ")", "model_ref", ".", "_current_hook_fx_name", "=", "None", "model_ref", ".", "_current_fx_name", ...
[ 250, 4 ]
[ 257, 39 ]
python
en
['en', 'error', 'th']
False
EpochResultStore.cache_result
(self)
This function is called after every hook and store the result object
This function is called after every hook and store the result object
def cache_result(self) -> None: """ This function is called after every hook and store the result object """ with self.trainer.profiler.profile("cache_result"): model_ref = self.trainer.lightning_module # extract hook results hook_result = mod...
[ "def", "cache_result", "(", "self", ")", "->", "None", ":", "with", "self", ".", "trainer", ".", "profiler", ".", "profile", "(", "\"cache_result\"", ")", ":", "model_ref", "=", "self", ".", "trainer", ".", "lightning_module", "# extract hook results", "hook_r...
[ 259, 4 ]
[ 295, 30 ]
python
en
['en', 'error', 'th']
False
EpochResultStore.update_logger_connector
(self)
This function is called every time we capture a hook It automatically updates the logger_connector followings: - progress_bar_metrics with pbar_metrics - logged_metrics with log_metrics - callback_metrics with progress_bar_metrics + logged_metrics
This function is called every time we capture a hook It automatically updates the logger_connector followings: - progress_bar_metrics with pbar_metrics - logged_metrics with log_metrics - callback_metrics with progress_bar_metrics + logged_metrics
def update_logger_connector(self) -> Tuple[Dict, Dict]: """ This function is called every time we capture a hook It automatically updates the logger_connector followings: - progress_bar_metrics with pbar_metrics - logged_metrics with log_metrics - callback_...
[ "def", "update_logger_connector", "(", "self", ")", "->", "Tuple", "[", "Dict", ",", "Dict", "]", ":", "logger_connector", "=", "self", ".", "trainer", ".", "logger_connector", "callback_metrics", "=", "{", "}", "batch_pbar_metrics", "=", "{", "}", "batch_log_...
[ 297, 4 ]
[ 349, 52 ]
python
en
['en', 'error', 'th']
False
EpochResultStore.__call__
( self, fx_name: str, dl_idx: Optional[int] = None, opt_idx: Optional[int] = None, batch_idx: Optional[int] = None, split_idx: Optional[int] = None, reduced: bool = False, )
This function is an helper to access stored data It access data from the HookResultStore. Please, check its data structure for better understanding Data can be accessed with the following chains: IF REDUCED: * IF accessing a fx_name defined in batch training loop:...
This function is an helper to access stored data
def __call__( self, fx_name: str, dl_idx: Optional[int] = None, opt_idx: Optional[int] = None, batch_idx: Optional[int] = None, split_idx: Optional[int] = None, reduced: bool = False, ): """ This function is an helper to access stored data ...
[ "def", "__call__", "(", "self", ",", "fx_name", ":", "str", ",", "dl_idx", ":", "Optional", "[", "int", "]", "=", "None", ",", "opt_idx", ":", "Optional", "[", "int", "]", "=", "None", ",", "batch_idx", ":", "Optional", "[", "int", "]", "=", "None"...
[ 418, 4 ]
[ 483, 21 ]
python
en
['en', 'error', 'th']
False
test_multiple_loggers_pickle
(tmpdir)
Verify that pickling trainer with multiple loggers works.
Verify that pickling trainer with multiple loggers works.
def test_multiple_loggers_pickle(tmpdir): """Verify that pickling trainer with multiple loggers works.""" logger1 = CustomLogger() logger2 = CustomLogger() trainer = Trainer(logger=[logger1, logger2], ) pkl_bytes = pickle.dumps(trainer) trainer2 = pickle.loads(pkl_bytes) trainer2.logger.lo...
[ "def", "test_multiple_loggers_pickle", "(", "tmpdir", ")", ":", "logger1", "=", "CustomLogger", "(", ")", "logger2", "=", "CustomLogger", "(", ")", "trainer", "=", "Trainer", "(", "logger", "=", "[", "logger1", ",", "logger2", "]", ",", ")", "pkl_bytes", "...
[ 153, 0 ]
[ 165, 60 ]
python
en
['en', 'en', 'en']
True
test_with_accumulate_grad_batches
()
Checks if the logging is performed once for `accumulate_grad_batches` steps.
Checks if the logging is performed once for `accumulate_grad_batches` steps.
def test_with_accumulate_grad_batches(): """Checks if the logging is performed once for `accumulate_grad_batches` steps.""" class StoreHistoryLogger(CustomLogger): def __init__(self): super().__init__() self.history = {} @rank_zero_only def log_metrics(self, me...
[ "def", "test_with_accumulate_grad_batches", "(", ")", ":", "class", "StoreHistoryLogger", "(", "CustomLogger", ")", ":", "def", "__init__", "(", "self", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "history", "=", "{", "}", "@", "...
[ 204, 0 ]
[ 227, 95 ]
python
en
['en', 'en', 'en']
True
CustomLogger.save_dir
(self)
Return the root directory where experiment logs get saved, or `None` if the logger does not save data locally.
Return the root directory where experiment logs get saved, or `None` if the logger does not save data locally.
def save_dir(self) -> Optional[str]: """ Return the root directory where experiment logs get saved, or `None` if the logger does not save data locally. """ return None
[ "def", "save_dir", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "None" ]
[ 80, 4 ]
[ 85, 19 ]
python
en
['en', 'error', 'th']
False
largest
(max)
Returns the highest number fizzbuzz wihtin the max limit, if there is none, return -1
Returns the highest number fizzbuzz wihtin the max limit, if there is none, return -1
def largest(max) -> int: """ Returns the highest number fizzbuzz wihtin the max limit, if there is none, return -1 """ while max >0: if max % 3 == 0 and max % 5 == 0: return max max-= 1 return -1
[ "def", "largest", "(", "max", ")", "->", "int", ":", "while", "max", ">", "0", ":", "if", "max", "%", "3", "==", "0", "and", "max", "%", "5", "==", "0", ":", "return", "max", "max", "-=", "1", "return", "-", "1" ]
[ 0, 0 ]
[ 8, 13 ]
python
en
['en', 'error', 'th']
False
LightningModule.current_epoch
(self)
The current epoch
The current epoch
def current_epoch(self) -> int: """The current epoch""" return self.trainer.current_epoch if self.trainer else 0
[ "def", "current_epoch", "(", "self", ")", "->", "int", ":", "return", "self", ".", "trainer", ".", "current_epoch", "if", "self", ".", "trainer", "else", "0" ]
[ 127, 4 ]
[ 129, 64 ]
python
en
['en', 'en', 'en']
True
LightningModule.global_step
(self)
Total training batches seen across all epochs
Total training batches seen across all epochs
def global_step(self) -> int: """Total training batches seen across all epochs""" return self.trainer.global_step if self.trainer else 0
[ "def", "global_step", "(", "self", ")", "->", "int", ":", "return", "self", ".", "trainer", ".", "global_step", "if", "self", ".", "trainer", "else", "0" ]
[ 132, 4 ]
[ 134, 62 ]
python
en
['en', 'en', 'en']
True
LightningModule.global_rank
(self)
The index of the current process across all nodes and devices.
The index of the current process across all nodes and devices.
def global_rank(self) -> int: """ The index of the current process across all nodes and devices. """ return self.trainer.global_rank if self.trainer else 0
[ "def", "global_rank", "(", "self", ")", "->", "int", ":", "return", "self", ".", "trainer", ".", "global_rank", "if", "self", ".", "trainer", "else", "0" ]
[ 137, 4 ]
[ 139, 62 ]
python
en
['en', 'en', 'en']
True
LightningModule.local_rank
(self)
The index of the current process within a single node.
The index of the current process within a single node.
def local_rank(self) -> int: """ The index of the current process within a single node. """ return self.trainer.local_rank if self.trainer else 0
[ "def", "local_rank", "(", "self", ")", "->", "int", ":", "return", "self", ".", "trainer", ".", "local_rank", "if", "self", ".", "trainer", "else", "0" ]
[ 142, 4 ]
[ 144, 61 ]
python
en
['en', 'en', 'en']
True
LightningModule.on_gpu
(self)
True if your model is currently running on GPUs. Useful to set flags around the LightningModule for different CPU vs GPU behavior.
True if your model is currently running on GPUs. Useful to set flags around the LightningModule for different CPU vs GPU behavior.
def on_gpu(self): """ True if your model is currently running on GPUs. Useful to set flags around the LightningModule for different CPU vs GPU behavior. """ return self.device.type == "cuda"
[ "def", "on_gpu", "(", "self", ")", ":", "return", "self", ".", "device", ".", "type", "==", "\"cuda\"" ]
[ 159, 4 ]
[ 164, 41 ]
python
en
['en', 'error', 'th']
False
LightningModule.automatic_optimization
(self)
If False you are responsible for calling .backward, .step, zero_grad.
If False you are responsible for calling .backward, .step, zero_grad.
def automatic_optimization(self) -> bool: """ If False you are responsible for calling .backward, .step, zero_grad. """ return self._automatic_optimization
[ "def", "automatic_optimization", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_automatic_optimization" ]
[ 167, 4 ]
[ 171, 43 ]
python
en
['en', 'error', 'th']
False
LightningModule.logger
(self)
Reference to the logger object in the Trainer.
Reference to the logger object in the Trainer.
def logger(self): """ Reference to the logger object in the Trainer. """ return self.trainer.logger if self.trainer else None
[ "def", "logger", "(", "self", ")", ":", "return", "self", ".", "trainer", ".", "logger", "if", "self", ".", "trainer", "else", "None" ]
[ 182, 4 ]
[ 184, 60 ]
python
en
['en', 'en', 'en']
True
LightningModule.print
(self, *args, **kwargs)
r""" Prints only from process 0. Use this in any distributed mode to log only once. Args: *args: The thing to print. The same as for Python's built-in print function. **kwargs: The same as for Python's built-in print function. Example:: def forward(self, x)...
r""" Prints only from process 0. Use this in any distributed mode to log only once.
def print(self, *args, **kwargs) -> None: r""" Prints only from process 0. Use this in any distributed mode to log only once. Args: *args: The thing to print. The same as for Python's built-in print function. **kwargs: The same as for Python's built-in print function. ...
[ "def", "print", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "self", ".", "trainer", ".", "is_global_zero", ":", "progress_bar", "=", "self", ".", "trainer", ".", "progress_bar_callback", "if", "progress_bar", "is...
[ 192, 4 ]
[ 211, 38 ]
python
cy
['en', 'cy', 'hi']
False
LightningModule.log
( self, name: str, value: Any, prog_bar: bool = False, logger: bool = True, on_step: Optional[bool] = None, on_epoch: Optional[bool] = None, reduce_fx: Callable = torch.mean, tbptt_reduce_fx: Callable = torch.mean, tbptt_pad_token: int = 0,...
Log a key, value Example:: self.log('train_loss', loss) The default behavior per hook is as follows .. csv-table:: ``*`` also applies to the test loop :header: "LightningMoule Hook", "on_step", "on_epoch", "prog_bar", "logger" :widths: 20, 10, 10, 1...
Log a key, value
def log( self, name: str, value: Any, prog_bar: bool = False, logger: bool = True, on_step: Optional[bool] = None, on_epoch: Optional[bool] = None, reduce_fx: Callable = torch.mean, tbptt_reduce_fx: Callable = torch.mean, tbptt_pad_token: i...
[ "def", "log", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Any", ",", "prog_bar", ":", "bool", "=", "False", ",", "logger", ":", "bool", "=", "True", ",", "on_step", ":", "Optional", "[", "bool", "]", "=", "None", ",", "on_epoch", ":...
[ 213, 4 ]
[ 311, 13 ]
python
en
['en', 'error', 'th']
False
LightningModule.log_dict
( self, dictionary: dict, prog_bar: bool = False, logger: bool = True, on_step: Optional[bool] = None, on_epoch: Optional[bool] = None, reduce_fx: Callable = torch.mean, tbptt_reduce_fx: Callable = torch.mean, tbptt_pad_token: int = 0, enab...
Log a dictonary of values at once Example:: values = {'loss': loss, 'acc': acc, ..., 'metric_n': metric_n} self.log_dict(values) Args: dictionary: key value pairs (str, tensors) prog_bar: if True logs to the progress base logger: if...
Log a dictonary of values at once
def log_dict( self, dictionary: dict, prog_bar: bool = False, logger: bool = True, on_step: Optional[bool] = None, on_epoch: Optional[bool] = None, reduce_fx: Callable = torch.mean, tbptt_reduce_fx: Callable = torch.mean, tbptt_pad_token: int = 0, ...
[ "def", "log_dict", "(", "self", ",", "dictionary", ":", "dict", ",", "prog_bar", ":", "bool", "=", "False", ",", "logger", ":", "bool", "=", "True", ",", "on_step", ":", "Optional", "[", "bool", "]", "=", "None", ",", "on_epoch", ":", "Optional", "["...
[ 313, 4 ]
[ 365, 13 ]
python
en
['en', 'error', 'th']
False
LightningModule.write_prediction
( self, name: str, value: Union[torch.Tensor, List[torch.Tensor]], filename: str = 'predictions.pt' )
Write predictions to disk using ``torch.save`` Example:: self.write_prediction('pred', torch.tensor(...), filename='my_predictions.pt') Args: name: a string indicating the name to save the predictions under value: the predictions, either a single :class:`~...
Write predictions to disk using ``torch.save``
def write_prediction( self, name: str, value: Union[torch.Tensor, List[torch.Tensor]], filename: str = 'predictions.pt' ): """ Write predictions to disk using ``torch.save`` Example:: self.write_prediction('pred', torch.tensor(...), filename='my_predictions.pt') ...
[ "def", "write_prediction", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Union", "[", "torch", ".", "Tensor", ",", "List", "[", "torch", ".", "Tensor", "]", "]", ",", "filename", ":", "str", "=", "'predictions.pt'", ")", ":", "self", ".",...
[ 367, 4 ]
[ 387, 87 ]
python
en
['en', 'error', 'th']
False
LightningModule.write_prediction_dict
(self, predictions_dict: Dict[str, Any], filename: str = 'predictions.pt')
Write a dictonary of predictions to disk at once using ``torch.save`` Example:: pred_dict = {'pred1': torch.tensor(...), 'pred2': torch.tensor(...)} self.write_prediction_dict(pred_dict) Args: predictions_dict: dict containing predictions, where each predi...
Write a dictonary of predictions to disk at once using ``torch.save``
def write_prediction_dict(self, predictions_dict: Dict[str, Any], filename: str = 'predictions.pt'): """ Write a dictonary of predictions to disk at once using ``torch.save`` Example:: pred_dict = {'pred1': torch.tensor(...), 'pred2': torch.tensor(...)} self.write_predi...
[ "def", "write_prediction_dict", "(", "self", ",", "predictions_dict", ":", "Dict", "[", "str", ",", "Any", "]", ",", "filename", ":", "str", "=", "'predictions.pt'", ")", ":", "for", "k", ",", "v", "in", "predictions_dict", ".", "items", "(", ")", ":", ...
[ 389, 4 ]
[ 408, 49 ]
python
en
['en', 'error', 'th']
False
LightningModule.all_gather
( self, data: Union[torch.Tensor, Dict, List, Tuple], group: Optional[Any] = None, sync_grads: bool = False, )
r""" Allows users to call ``self.all_gather()`` from the LightningModule, thus making the ```all_gather``` operation accelerator agnostic. ```all_gather``` is a function provided by accelerators to gather a tensor from several distributed processes Args: tensor: int...
r""" Allows users to call ``self.all_gather()`` from the LightningModule, thus making the ```all_gather``` operation accelerator agnostic.
def all_gather( self, data: Union[torch.Tensor, Dict, List, Tuple], group: Optional[Any] = None, sync_grads: bool = False, ): r""" Allows users to call ``self.all_gather()`` from the LightningModule, thus making the ```all_gather``` operation accelerator agnos...
[ "def", "all_gather", "(", "self", ",", "data", ":", "Union", "[", "torch", ".", "Tensor", ",", "Dict", ",", "List", ",", "Tuple", "]", ",", "group", ":", "Optional", "[", "Any", "]", "=", "None", ",", "sync_grads", ":", "bool", "=", "False", ",", ...
[ 436, 4 ]
[ 462, 66 ]
python
cy
['en', 'cy', 'hi']
False
LightningModule.forward
(self, *args, **kwargs)
r""" Same as :meth:`torch.nn.Module.forward()`, however in Lightning you want this to define the operations you want to use for prediction (i.e.: on a server or as a feature extractor). Normally you'd call ``self()`` from your :meth:`training_step` method. This makes it easy to write a ...
r""" Same as :meth:`torch.nn.Module.forward()`, however in Lightning you want this to define the operations you want to use for prediction (i.e.: on a server or as a feature extractor).
def forward(self, *args, **kwargs): r""" Same as :meth:`torch.nn.Module.forward()`, however in Lightning you want this to define the operations you want to use for prediction (i.e.: on a server or as a feature extractor). Normally you'd call ``self()`` from your :meth:`training_step` me...
[ "def", "forward", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", ")", ".", "forward", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 464, 4 ]
[ 514, 47 ]
python
cy
['en', 'cy', 'hi']
False
LightningModule.training_step
(self, *args, **kwargs)
r""" Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger. Args: batch (:class:`~torch.Tensor` | (:class:`~torch.Tensor`, ...) | [:class:`~torch.Tensor`, ...]): The output of your :class:`~torch.utils.data.Data...
r""" Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.
def training_step(self, *args, **kwargs): r""" Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger. Args: batch (:class:`~torch.Tensor` | (:class:`~torch.Tensor`, ...) | [:class:`~torch.Tensor`, ...]): ...
[ "def", "training_step", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "rank_zero_warn", "(", "\"`training_step` must be implemented to be used with the Lightning Trainer\"", ")" ]
[ 516, 4 ]
[ 580, 99 ]
python
cy
['en', 'cy', 'hi']
False
LightningModule.training_step_end
(self, *args, **kwargs)
Use this when training with dp or ddp2 because :meth:`training_step` will operate on only part of the batch. However, this is still optional and only needed for things like softmax or NCE loss. Note: If you later switch to ddp or some other mode, this will still be called ...
Use this when training with dp or ddp2 because :meth:`training_step` will operate on only part of the batch. However, this is still optional and only needed for things like softmax or NCE loss.
def training_step_end(self, *args, **kwargs): """ Use this when training with dp or ddp2 because :meth:`training_step` will operate on only part of the batch. However, this is still optional and only needed for things like softmax or NCE loss. Note: If you later swit...
[ "def", "training_step_end", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":" ]
[ 582, 4 ]
[ 642, 11 ]
python
en
['en', 'error', 'th']
False
LightningModule.training_epoch_end
(self, outputs: List[Any])
Called at the end of the training epoch with the outputs of all training steps. Use this in case you need to do something with all the outputs for every training_step. .. code-block:: python # the pseudocode for these calls train_outs = [] for train_batch i...
Called at the end of the training epoch with the outputs of all training steps. Use this in case you need to do something with all the outputs for every training_step.
def training_epoch_end(self, outputs: List[Any]) -> None: """ Called at the end of the training epoch with the outputs of all training steps. Use this in case you need to do something with all the outputs for every training_step. .. code-block:: python # the pseudocode for ...
[ "def", "training_epoch_end", "(", "self", ",", "outputs", ":", "List", "[", "Any", "]", ")", "->", "None", ":" ]
[ 644, 4 ]
[ 683, 11 ]
python
en
['en', 'error', 'th']
False
LightningModule.validation_step
(self, *args, **kwargs)
r""" Operates on a single batch of data from the validation set. In this step you'd might generate examples or calculate anything of interest like accuracy. .. code-block:: python # the pseudocode for these calls val_outs = [] for val_batch in val_data: ...
r""" Operates on a single batch of data from the validation set. In this step you'd might generate examples or calculate anything of interest like accuracy.
def validation_step(self, *args, **kwargs): r""" Operates on a single batch of data from the validation set. In this step you'd might generate examples or calculate anything of interest like accuracy. .. code-block:: python # the pseudocode for these calls val_o...
[ "def", "validation_step", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":" ]
[ 685, 4 ]
[ 767, 11 ]
python
cy
['en', 'cy', 'hi']
False
LightningModule.validation_step_end
(self, *args, **kwargs)
Use this when validating with dp or ddp2 because :meth:`validation_step` will operate on only part of the batch. However, this is still optional and only needed for things like softmax or NCE loss. Note: If you later switch to ddp or some other mode, this will still be call...
Use this when validating with dp or ddp2 because :meth:`validation_step` will operate on only part of the batch. However, this is still optional and only needed for things like softmax or NCE loss.
def validation_step_end(self, *args, **kwargs): """ Use this when validating with dp or ddp2 because :meth:`validation_step` will operate on only part of the batch. However, this is still optional and only needed for things like softmax or NCE loss. Note: If you late...
[ "def", "validation_step_end", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":" ]
[ 769, 4 ]
[ 821, 11 ]
python
en
['en', 'error', 'th']
False
LightningModule.validation_epoch_end
(self, outputs: List[Any])
Called at the end of the validation epoch with the outputs of all validation steps. .. code-block:: python # the pseudocode for these calls val_outs = [] for val_batch in val_data: out = validation_step(val_batch) val_outs.append(out...
Called at the end of the validation epoch with the outputs of all validation steps.
def validation_epoch_end(self, outputs: List[Any]) -> None: """ Called at the end of the validation epoch with the outputs of all validation steps. .. code-block:: python # the pseudocode for these calls val_outs = [] for val_batch in val_data: ...
[ "def", "validation_epoch_end", "(", "self", ",", "outputs", ":", "List", "[", "Any", "]", ")", "->", "None", ":" ]
[ 823, 4 ]
[ 866, 11 ]
python
en
['en', 'error', 'th']
False
LightningModule.test_step
(self, *args, **kwargs)
r""" Operates on a single batch of data from the test set. In this step you'd normally generate examples or calculate anything of interest such as accuracy. .. code-block:: python # the pseudocode for these calls test_outs = [] for test_batch in test...
r""" Operates on a single batch of data from the test set. In this step you'd normally generate examples or calculate anything of interest such as accuracy.
def test_step(self, *args, **kwargs): r""" Operates on a single batch of data from the test set. In this step you'd normally generate examples or calculate anything of interest such as accuracy. .. code-block:: python # the pseudocode for these calls tes...
[ "def", "test_step", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":" ]
[ 868, 4 ]
[ 942, 11 ]
python
cy
['en', 'cy', 'hi']
False
LightningModule.test_step_end
(self, *args, **kwargs)
Use this when testing with dp or ddp2 because :meth:`test_step` will operate on only part of the batch. However, this is still optional and only needed for things like softmax or NCE loss. Note: If you later switch to ddp or some other mode, this will still be called ...
Use this when testing with dp or ddp2 because :meth:`test_step` will operate on only part of the batch. However, this is still optional and only needed for things like softmax or NCE loss.
def test_step_end(self, *args, **kwargs): """ Use this when testing with dp or ddp2 because :meth:`test_step` will operate on only part of the batch. However, this is still optional and only needed for things like softmax or NCE loss. Note: If you later switch to ddp...
[ "def", "test_step_end", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":" ]
[ 944, 4 ]
[ 996, 11 ]
python
en
['en', 'error', 'th']
False
LightningModule.test_epoch_end
(self, outputs: List[Any])
Called at the end of a test epoch with the output of all test steps. .. code-block:: python # the pseudocode for these calls test_outs = [] for test_batch in test_data: out = test_step(test_batch) test_outs.append(out) te...
Called at the end of a test epoch with the output of all test steps.
def test_epoch_end(self, outputs: List[Any]) -> None: """ Called at the end of a test epoch with the output of all test steps. .. code-block:: python # the pseudocode for these calls test_outs = [] for test_batch in test_data: out = test_step...
[ "def", "test_epoch_end", "(", "self", ",", "outputs", ":", "List", "[", "Any", "]", ")", "->", "None", ":" ]
[ 998, 4 ]
[ 1047, 11 ]
python
en
['en', 'error', 'th']
False
LightningModule.predict
(self, batch: Any, batch_idx: int, dataloader_idx: Optional[int] = None)
Use this function with trainer.predict(...). Override if you need to add any processing logic.
Use this function with trainer.predict(...). Override if you need to add any processing logic.
def predict(self, batch: Any, batch_idx: int, dataloader_idx: Optional[int] = None): """ Use this function with trainer.predict(...). Override if you need to add any processing logic. """ return self(batch)
[ "def", "predict", "(", "self", ",", "batch", ":", "Any", ",", "batch_idx", ":", "int", ",", "dataloader_idx", ":", "Optional", "[", "int", "]", "=", "None", ")", ":", "return", "self", "(", "batch", ")" ]
[ 1049, 4 ]
[ 1053, 26 ]
python
en
['en', 'error', 'th']
False
LightningModule.configure_callbacks
(self)
Configure model-specific callbacks. When the model gets attached, e.g., when ``.fit()`` or ``.test()`` gets called, the list returned here will be merged with the list of callbacks passed to the Trainer's ``callbacks`` argument. If a callback returned here has the same type as one or se...
Configure model-specific callbacks. When the model gets attached, e.g., when ``.fit()`` or ``.test()`` gets called, the list returned here will be merged with the list of callbacks passed to the Trainer's ``callbacks`` argument. If a callback returned here has the same type as one or se...
def configure_callbacks(self): """ Configure model-specific callbacks. When the model gets attached, e.g., when ``.fit()`` or ``.test()`` gets called, the list returned here will be merged with the list of callbacks passed to the Trainer's ``callbacks`` argument. If a callback re...
[ "def", "configure_callbacks", "(", "self", ")", ":", "return", "[", "]" ]
[ 1055, 4 ]
[ 1079, 17 ]
python
en
['en', 'error', 'th']
False
LightningModule.configure_optimizers
(self)
r""" Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you'd need one. But in the case of GANs or similar you might have multiple. Return: Any of these 6 options. - Single optimizer. - List or Tuple - List of optimizer...
r""" Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you'd need one. But in the case of GANs or similar you might have multiple.
def configure_optimizers(self): r""" Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you'd need one. But in the case of GANs or similar you might have multiple. Return: Any of these 6 options. - Single optimizer. ...
[ "def", "configure_optimizers", "(", "self", ")", ":", "rank_zero_warn", "(", "\"`configure_optimizers` must be implemented to be used with the Lightning Trainer\"", ")" ]
[ 1081, 4 ]
[ 1197, 106 ]
python
cy
['en', 'cy', 'hi']
False
LightningModule.manual_backward
(self, loss: Tensor, optimizer: Optional[Optimizer] = None, *args, **kwargs)
Call this directly from your training_step when doing optimizations manually. By using this we can ensure that all the proper scaling when using 16-bit etc has been done for you This function forwards all args to the .backward() call as well. .. tip:: In manual mode we still automatic...
Call this directly from your training_step when doing optimizations manually. By using this we can ensure that all the proper scaling when using 16-bit etc has been done for you
def manual_backward(self, loss: Tensor, optimizer: Optional[Optimizer] = None, *args, **kwargs) -> None: """ Call this directly from your training_step when doing optimizations manually. By using this we can ensure that all the proper scaling when using 16-bit etc has been done for you ...
[ "def", "manual_backward", "(", "self", ",", "loss", ":", "Tensor", ",", "optimizer", ":", "Optional", "[", "Optimizer", "]", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "optimizer", "is", "not", "None", ":", ...
[ 1199, 4 ]
[ 1232, 45 ]
python
en
['en', 'error', 'th']
False
LightningModule.backward
(self, loss: Tensor, optimizer: Optimizer, optimizer_idx: int, *args, **kwargs)
Override backward with your own implementation if you need to. Args: loss: Loss is already scaled by accumulated grads optimizer: Current optimizer being used optimizer_idx: Index of the current optimizer being used Called to perform backward step. ...
Override backward with your own implementation if you need to.
def backward(self, loss: Tensor, optimizer: Optimizer, optimizer_idx: int, *args, **kwargs) -> None: """ Override backward with your own implementation if you need to. Args: loss: Loss is already scaled by accumulated grads optimizer: Current optimizer being used ...
[ "def", "backward", "(", "self", ",", "loss", ":", "Tensor", ",", "optimizer", ":", "Optimizer", ",", "optimizer_idx", ":", "int", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "self", ".", "trainer", ".", "train_loop", ".",...
[ 1234, 4 ]
[ 1254, 42 ]
python
en
['en', 'error', 'th']
False
LightningModule.toggle_optimizer
(self, optimizer: Optimizer, optimizer_idx: int)
Makes sure only the gradients of the current optimizer's parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup. .. note:: Only called when using multiple optimizers Override for your own behavior It works with ``untoggle_opti...
Makes sure only the gradients of the current optimizer's parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
def toggle_optimizer(self, optimizer: Optimizer, optimizer_idx: int): """ Makes sure only the gradients of the current optimizer's parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup. .. note:: Only called when using multiple optimize...
[ "def", "toggle_optimizer", "(", "self", ",", "optimizer", ":", "Optimizer", ",", "optimizer_idx", ":", "int", ")", ":", "# Iterate over all optimizer parameters to preserve their `requires_grad` information", "# in case these are pre-defined during `configure_optimizers`", "param_req...
[ 1256, 4 ]
[ 1289, 67 ]
python
en
['en', 'error', 'th']
False
LightningModule.untoggle_optimizer
(self, optimizer_idx: int)
.. note:: Only called when using multiple optimizers Override for your own behavior Args: optimizer_idx: Current optimizer idx in training_loop
.. note:: Only called when using multiple optimizers
def untoggle_optimizer(self, optimizer_idx: int): """ .. note:: Only called when using multiple optimizers Override for your own behavior Args: optimizer_idx: Current optimizer idx in training_loop """ for opt_idx, opt in enumerate(self.optimizers(use_pl_opt...
[ "def", "untoggle_optimizer", "(", "self", ",", "optimizer_idx", ":", "int", ")", ":", "for", "opt_idx", ",", "opt", "in", "enumerate", "(", "self", ".", "optimizers", "(", "use_pl_optimizer", "=", "False", ")", ")", ":", "if", "optimizer_idx", "!=", "opt_i...
[ 1291, 4 ]
[ 1307, 43 ]
python
en
['en', 'error', 'th']
False
LightningModule.optimizer_step
( self, epoch: int = None, batch_idx: int = None, optimizer: Optimizer = None, optimizer_idx: int = None, optimizer_closure: Optional[Callable] = None, on_tpu: bool = None, using_native_amp: bool = None, using_lbfgs: bool = None, )
r""" Override this method to adjust the default way the :class:`~pytorch_lightning.trainer.trainer.Trainer` calls each optimizer. By default, Lightning calls ``step()`` and ``zero_grad()`` as shown in the example once per optimizer. Warning: If you are overriding thi...
r""" Override this method to adjust the default way the :class:`~pytorch_lightning.trainer.trainer.Trainer` calls each optimizer. By default, Lightning calls ``step()`` and ``zero_grad()`` as shown in the example once per optimizer.
def optimizer_step( self, epoch: int = None, batch_idx: int = None, optimizer: Optimizer = None, optimizer_idx: int = None, optimizer_closure: Optional[Callable] = None, on_tpu: bool = None, using_native_amp: bool = None, using_lbfgs: bool = None, ...
[ "def", "optimizer_step", "(", "self", ",", "epoch", ":", "int", "=", "None", ",", "batch_idx", ":", "int", "=", "None", ",", "optimizer", ":", "Optimizer", "=", "None", ",", "optimizer_idx", ":", "int", "=", "None", ",", "optimizer_closure", ":", "Option...
[ 1309, 4 ]
[ 1390, 49 ]
python
cy
['en', 'cy', 'hi']
False
LightningModule.tbptt_split_batch
(self, batch: Tensor, split_size: int)
r""" When using truncated backpropagation through time, each batch must be split along the time dimension. Lightning handles this by default, but for custom behavior override this function. Args: batch: Current batch split_size: The size of the split Ret...
r""" When using truncated backpropagation through time, each batch must be split along the time dimension. Lightning handles this by default, but for custom behavior override this function.
def tbptt_split_batch(self, batch: Tensor, split_size: int) -> list: r""" When using truncated backpropagation through time, each batch must be split along the time dimension. Lightning handles this by default, but for custom behavior override this function. Args: ba...
[ "def", "tbptt_split_batch", "(", "self", ",", "batch", ":", "Tensor", ",", "split_size", ":", "int", ")", "->", "list", ":", "time_dims", "=", "[", "len", "(", "x", "[", "0", "]", ")", "for", "x", "in", "batch", "if", "isinstance", "(", "x", ",", ...
[ 1395, 4 ]
[ 1456, 21 ]
python
cy
['en', 'cy', 'hi']
False
LightningModule.freeze
(self)
r""" Freeze all params for inference. Example:: model = MyLightningModule(...) model.freeze()
r""" Freeze all params for inference.
def freeze(self) -> None: r""" Freeze all params for inference. Example:: model = MyLightningModule(...) model.freeze() """ for param in self.parameters(): param.requires_grad = False self.eval()
[ "def", "freeze", "(", "self", ")", "->", "None", ":", "for", "param", "in", "self", ".", "parameters", "(", ")", ":", "param", ".", "requires_grad", "=", "False", "self", ".", "eval", "(", ")" ]
[ 1469, 4 ]
[ 1482, 19 ]
python
cy
['en', 'cy', 'hi']
False
LightningModule.unfreeze
(self)
Unfreeze all parameters for training. .. code-block:: python model = MyLightningModule(...) model.unfreeze()
Unfreeze all parameters for training.
def unfreeze(self) -> None: """ Unfreeze all parameters for training. .. code-block:: python model = MyLightningModule(...) model.unfreeze() """ for param in self.parameters(): param.requires_grad = True self.train()
[ "def", "unfreeze", "(", "self", ")", "->", "None", ":", "for", "param", "in", "self", ".", "parameters", "(", ")", ":", "param", ".", "requires_grad", "=", "True", "self", ".", "train", "(", ")" ]
[ 1484, 4 ]
[ 1497, 20 ]
python
en
['en', 'error', 'th']
False
LightningModule.get_progress_bar_dict
(self)
r""" Implement this to override the default items displayed in the progress bar. By default it includes the average loss value, split index of BPTT (if used) and the version of the experiment when using a logger. .. code-block:: Epoch 1: 4%|▎ | 40/1095 [00:03<01:3...
r""" Implement this to override the default items displayed in the progress bar. By default it includes the average loss value, split index of BPTT (if used) and the version of the experiment when using a logger.
def get_progress_bar_dict(self) -> Dict[str, Union[int, str]]: r""" Implement this to override the default items displayed in the progress bar. By default it includes the average loss value, split index of BPTT (if used) and the version of the experiment when using a logger. .. ...
[ "def", "get_progress_bar_dict", "(", "self", ")", "->", "Dict", "[", "str", ",", "Union", "[", "int", ",", "str", "]", "]", ":", "# call .item() only once but store elements without graphs", "running_train_loss", "=", "self", ".", "trainer", ".", "train_loop", "."...
[ 1499, 4 ]
[ 1543, 24 ]
python
cy
['en', 'cy', 'hi']
False
LightningModule._auto_collect_arguments
(cls, frame=None)
Collect all module arguments in the current constructor and all child constructors. The child constructors are all the ``__init__`` methods that reach the current class through (chained) ``super().__init__()`` calls. Args: frame: instance frame Returns: ...
Collect all module arguments in the current constructor and all child constructors. The child constructors are all the ``__init__`` methods that reach the current class through (chained) ``super().__init__()`` calls.
def _auto_collect_arguments(cls, frame=None) -> Tuple[Dict, Dict]: """ Collect all module arguments in the current constructor and all child constructors. The child constructors are all the ``__init__`` methods that reach the current class through (chained) ``super().__init__()`` calls. ...
[ "def", "_auto_collect_arguments", "(", "cls", ",", "frame", "=", "None", ")", "->", "Tuple", "[", "Dict", ",", "Dict", "]", ":", "if", "not", "frame", ":", "frame", "=", "inspect", ".", "currentframe", "(", ")", "frame_args", "=", "collect_init_args", "(...
[ 1553, 4 ]
[ 1579, 48 ]
python
en
['en', 'error', 'th']
False
LightningModule.save_hyperparameters
(self, *args, frame=None)
Save all model arguments. Args: args: single object of `dict`, `NameSpace` or `OmegaConf` or string names or arguments from class `__init__` >>> class ManuallyArgsModel(LightningModule): ... def __init__(self, arg1, arg2, arg3): ... super().__init__...
Save all model arguments.
def save_hyperparameters(self, *args, frame=None) -> None: """Save all model arguments. Args: args: single object of `dict`, `NameSpace` or `OmegaConf` or string names or arguments from class `__init__` >>> class ManuallyArgsModel(LightningModule): ... def ...
[ "def", "save_hyperparameters", "(", "self", ",", "*", "args", ",", "frame", "=", "None", ")", "->", "None", ":", "if", "not", "frame", ":", "frame", "=", "inspect", ".", "currentframe", "(", ")", ".", "f_back", "init_args", "=", "get_init_args", "(", "...
[ 1581, 4 ]
[ 1649, 60 ]
python
en
['en', 'en', 'en']
True
LightningModule.to_onnx
( self, file_path: Union[str, Path], input_sample: Optional[Any] = None, **kwargs, )
Saves the model in ONNX format Args: file_path: The path of the file the onnx model should be saved to. input_sample: An input for tracing. Default: None (Use self.example_input_array) **kwargs: Will be passed to torch.onnx.export function. Example: ...
Saves the model in ONNX format
def to_onnx( self, file_path: Union[str, Path], input_sample: Optional[Any] = None, **kwargs, ): """ Saves the model in ONNX format Args: file_path: The path of the file the onnx model should be saved to. input_sample: An input for tra...
[ "def", "to_onnx", "(", "self", ",", "file_path", ":", "Union", "[", "str", ",", "Path", "]", ",", "input_sample", ":", "Optional", "[", "Any", "]", "=", "None", ",", "*", "*", "kwargs", ",", ")", ":", "mode", "=", "self", ".", "training", "if", "...
[ 1667, 4 ]
[ 1714, 24 ]
python
en
['en', 'error', 'th']
False
LightningModule.to_torchscript
( self, file_path: Optional[Union[str, Path]] = None, method: Optional[str] = 'script', example_inputs: Optional[Any] = None, **kwargs, )
By default compiles the whole model to a :class:`~torch.jit.ScriptModule`. If you want to use tracing, please provided the argument `method='trace'` and make sure that either the example_inputs argument is provided, or the model has self.example_input_array set. If you would like to cus...
By default compiles the whole model to a :class:`~torch.jit.ScriptModule`. If you want to use tracing, please provided the argument `method='trace'` and make sure that either the example_inputs argument is provided, or the model has self.example_input_array set. If you would like to cus...
def to_torchscript( self, file_path: Optional[Union[str, Path]] = None, method: Optional[str] = 'script', example_inputs: Optional[Any] = None, **kwargs, ) -> Union[ScriptModule, Dict[str, ScriptModule]]: """ By default compiles the whole model to a :class:`~t...
[ "def", "to_torchscript", "(", "self", ",", "file_path", ":", "Optional", "[", "Union", "[", "str", ",", "Path", "]", "]", "=", "None", ",", "method", ":", "Optional", "[", "str", "]", "=", "'script'", ",", "example_inputs", ":", "Optional", "[", "Any",...
[ 1717, 4 ]
[ 1793, 33 ]
python
en
['en', 'error', 'th']
False
LightningModule.__get_hparams_assignment_variable
(self)
looks at the code of the class to figure out what the user named self.hparams this only happens when the user explicitly sets self.hparams
looks at the code of the class to figure out what the user named self.hparams this only happens when the user explicitly sets self.hparams
def __get_hparams_assignment_variable(self): """ looks at the code of the class to figure out what the user named self.hparams this only happens when the user explicitly sets self.hparams """ try: class_code = inspect.getsource(self.__class__) lines = clas...
[ "def", "__get_hparams_assignment_variable", "(", "self", ")", ":", "try", ":", "class_code", "=", "inspect", ".", "getsource", "(", "self", ".", "__class__", ")", "lines", "=", "class_code", ".", "split", "(", "\"\\n\"", ")", "for", "line", "in", "lines", ...
[ 1823, 4 ]
[ 1839, 19 ]
python
en
['en', 'error', 'th']
False
Randint.time_randint_fast
(self)
Compare to uint32 below
Compare to uint32 below
def time_randint_fast(self): """Compare to uint32 below""" np.random.randint(0, 2**30, size=10**5)
[ "def", "time_randint_fast", "(", "self", ")", ":", "np", ".", "random", ".", "randint", "(", "0", ",", "2", "**", "30", ",", "size", "=", "10", "**", "5", ")" ]
[ 40, 4 ]
[ 42, 47 ]
python
en
['en', 'en', 'en']
True
Randint.time_randint_slow
(self)
Compare to uint32 below
Compare to uint32 below
def time_randint_slow(self): """Compare to uint32 below""" np.random.randint(0, 2**30 + 1, size=10**5)
[ "def", "time_randint_slow", "(", "self", ")", ":", "np", ".", "random", ".", "randint", "(", "0", ",", "2", "**", "30", "+", "1", ",", "size", "=", "10", "**", "5", ")" ]
[ 44, 4 ]
[ 46, 51 ]
python
en
['en', 'en', 'en']
True
Bounded.time_bounded
(self, bitgen, args)
Timer for 8-bit bounded values. Parameters (packed as args) ---------- dt : {uint8, uint16, uint32, unit64} output dtype max : int Upper bound for range. Lower is always 0. Must be <= 2**bits.
Timer for 8-bit bounded values.
def time_bounded(self, bitgen, args): """ Timer for 8-bit bounded values. Parameters (packed as args) ---------- dt : {uint8, uint16, uint32, unit64} output dtype max : int Upper bound for range. Lower is always 0. ...
[ "def", "time_bounded", "(", "self", ",", "bitgen", ",", "args", ")", ":", "dt", ",", "max", "=", "args", "if", "bitgen", "==", "'numpy'", ":", "self", ".", "rg", ".", "randint", "(", "0", ",", "max", "+", "1", ",", "nom_size", ",", "dtype", "=", ...
[ 159, 4 ]
[ 174, 64 ]
python
en
['en', 'error', 'th']
False
batch_rename
(work_dir, old_ext, new_ext)
This will batch rename a group of files in a given directory, once you pass the current and new extensions
This will batch rename a group of files in a given directory, once you pass the current and new extensions
def batch_rename(work_dir, old_ext, new_ext): """ This will batch rename a group of files in a given directory, once you pass the current and new extensions """ # files = os.listdir(work_dir) for filename in os.listdir(work_dir): # Get the file extension split_file = os.p...
[ "def", "batch_rename", "(", "work_dir", ",", "old_ext", ",", "new_ext", ")", ":", "# files = os.listdir(work_dir)\r", "for", "filename", "in", "os", ".", "listdir", "(", "work_dir", ")", ":", "# Get the file extension\r", "split_file", "=", "os", ".", "path", "....
[ 16, 0 ]
[ 38, 31 ]
python
en
['en', 'ja', 'th']
False
main
()
This will be called if the script is directly invoked.
This will be called if the script is directly invoked.
def main(): """ This will be called if the script is directly invoked. """ # adding command line argument parser = get_parser() args = vars(parser.parse_args()) # Set the variable work_dir with the first argument passed work_dir = args['work_dir'][0] # Set the variable old...
[ "def", "main", "(", ")", ":", "# adding command line argument\r", "parser", "=", "get_parser", "(", ")", "args", "=", "vars", "(", "parser", ".", "parse_args", "(", ")", ")", "# Set the variable work_dir with the first argument passed\r", "work_dir", "=", "args", "[...
[ 50, 0 ]
[ 69, 44 ]
python
en
['en', 'ja', 'th']
False
test_float_types
(tp)
Check formatting. This is only for the str function, and only for simple types. The precision of np.float32 and np.longdouble aren't the same as the python float precision.
Check formatting.
def test_float_types(tp): """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float32 and np.longdouble aren't the same as the python float precision. """ for x in [0, 1, -1, 1e20]: assert_equal(str(tp(x)), str(float(x)), ...
[ "def", "test_float_types", "(", "tp", ")", ":", "for", "x", "in", "[", "0", ",", "1", ",", "-", "1", ",", "1e20", "]", ":", "assert_equal", "(", "str", "(", "tp", "(", "x", ")", ")", ",", "str", "(", "float", "(", "x", ")", ")", ",", "err_m...
[ 20, 0 ]
[ 38, 70 ]
python
en
['it', 'kk', 'en']
False
test_nan_inf_float
(tp)
Check formatting of nan & inf. This is only for the str function, and only for simple types. The precision of np.float32 and np.longdouble aren't the same as the python float precision.
Check formatting of nan & inf.
def test_nan_inf_float(tp): """ Check formatting of nan & inf. This is only for the str function, and only for simple types. The precision of np.float32 and np.longdouble aren't the same as the python float precision. """ for x in [np.inf, -np.inf, np.nan]: assert_equal(str...
[ "def", "test_nan_inf_float", "(", "tp", ")", ":", "for", "x", "in", "[", "np", ".", "inf", ",", "-", "np", ".", "inf", ",", "np", ".", "nan", "]", ":", "assert_equal", "(", "str", "(", "tp", "(", "x", ")", ")", ",", "_REF", "[", "x", "]", "...
[ 42, 0 ]
[ 52, 70 ]
python
en
['en', 'fil', 'en']
True
test_complex_types
(tp)
Check formatting of complex types. This is only for the str function, and only for simple types. The precision of np.float32 and np.longdouble aren't the same as the python float precision.
Check formatting of complex types.
def test_complex_types(tp): """Check formatting of complex types. This is only for the str function, and only for simple types. The precision of np.float32 and np.longdouble aren't the same as the python float precision. """ for x in [0, 1, -1, 1e20]: assert_equal(str(tp(x)...
[ "def", "test_complex_types", "(", "tp", ")", ":", "for", "x", "in", "[", "0", ",", "1", ",", "-", "1", ",", "1e20", "]", ":", "assert_equal", "(", "str", "(", "tp", "(", "x", ")", ")", ",", "str", "(", "complex", "(", "x", ")", ")", ",", "e...
[ 56, 0 ]
[ 78, 70 ]
python
en
['en', 'en', 'en']
True